diff --git a/.forgejo/workflows/test.yml b/.forgejo/workflows/test.yml index 088ca7c..71f4a3b 100644 --- a/.forgejo/workflows/test.yml +++ b/.forgejo/workflows/test.yml @@ -8,7 +8,7 @@ jobs: with: fetch-depth: 0 - run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.80.1 + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.79.0 source "$HOME/.cargo/env" echo "$PATH" >> "$GITHUB_PATH" - uses: https://github.com/Swatinem/rust-cache@v2 diff --git a/Cargo.toml b/Cargo.toml index 1608a79..f9c13cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ edition = "2021" repository = "https://git.libre-chip.org/libre-chip/fayalite" keywords = ["hdl", "hardware", "semiconductors", "firrtl", "fpga"] categories = ["simulation", "development-tools", "compilers"] -rust-version = "1.80.1" +rust-version = "1.79" [workspace.dependencies] fayalite-proc-macros = { version = "=0.2.0", path = "crates/fayalite-proc-macros" } diff --git a/crates/fayalite-proc-macros-impl/src/fold.rs b/crates/fayalite-proc-macros-impl/src/fold.rs index 49cc8c1..1e1ff42 100644 --- a/crates/fayalite-proc-macros-impl/src/fold.rs +++ b/crates/fayalite-proc-macros-impl/src/fold.rs @@ -224,31 +224,25 @@ forward_fold!(syn::ExprPath => fold_expr_path); forward_fold!(syn::ExprRepeat => fold_expr_repeat); forward_fold!(syn::ExprStruct => fold_expr_struct); forward_fold!(syn::ExprTuple => fold_expr_tuple); -forward_fold!(syn::FieldPat => fold_field_pat); forward_fold!(syn::Ident => fold_ident); forward_fold!(syn::Member => fold_member); forward_fold!(syn::Path => fold_path); forward_fold!(syn::Type => fold_type); forward_fold!(syn::TypePath => fold_type_path); forward_fold!(syn::WherePredicate => fold_where_predicate); -no_op_fold!(proc_macro2::Span); no_op_fold!(syn::parse::Nothing); no_op_fold!(syn::token::Brace); no_op_fold!(syn::token::Bracket); -no_op_fold!(syn::token::Group); no_op_fold!(syn::token::Paren); no_op_fold!(syn::Token![_]); no_op_fold!(syn::Token![,]); no_op_fold!(syn::Token![;]); no_op_fold!(syn::Token![:]); -no_op_fold!(syn::Token![::]); no_op_fold!(syn::Token![..]); no_op_fold!(syn::Token![.]); no_op_fold!(syn::Token![#]); -no_op_fold!(syn::Token![<]); no_op_fold!(syn::Token![=]); no_op_fold!(syn::Token![=>]); -no_op_fold!(syn::Token![>]); no_op_fold!(syn::Token![|]); no_op_fold!(syn::Token![enum]); no_op_fold!(syn::Token![extern]); @@ -257,4 +251,3 @@ no_op_fold!(syn::Token![mut]); no_op_fold!(syn::Token![static]); no_op_fold!(syn::Token![struct]); no_op_fold!(syn::Token![where]); -no_op_fold!(usize); diff --git a/crates/fayalite-proc-macros-impl/src/hdl_bundle.rs b/crates/fayalite-proc-macros-impl/src/hdl_bundle.rs deleted file mode 100644 index f29f43a..0000000 --- a/crates/fayalite-proc-macros-impl/src/hdl_bundle.rs +++ /dev/null @@ -1,857 +0,0 @@ -use crate::{ - hdl_type_common::{ - common_derives, get_target, ItemOptions, MakeHdlTypeExpr, MaybeParsed, ParsedField, - ParsedFieldsNamed, ParsedGenerics, SplitForImpl, TypesParser, WrappedInConst, - }, - kw, Errors, HdlAttr, PairsIterExt, -}; -use proc_macro2::TokenStream; -use quote::{format_ident, quote_spanned, ToTokens}; -use syn::{ - parse_quote, parse_quote_spanned, - punctuated::{Pair, Punctuated}, - spanned::Spanned, - token::Brace, - AngleBracketedGenericArguments, Attribute, Field, FieldMutability, Fields, FieldsNamed, - GenericParam, Generics, Ident, ItemStruct, Path, Token, Type, Visibility, -}; - -#[derive(Clone, Debug)] -pub(crate) struct ParsedBundle { - pub(crate) attrs: Vec, - pub(crate) options: HdlAttr, - pub(crate) vis: Visibility, - pub(crate) struct_token: Token![struct], - pub(crate) ident: Ident, - pub(crate) generics: MaybeParsed, - pub(crate) fields: MaybeParsed, - pub(crate) field_flips: Vec>>, - pub(crate) mask_type_ident: Ident, - pub(crate) mask_type_match_variant_ident: Ident, - pub(crate) match_variant_ident: Ident, - pub(crate) builder_ident: Ident, - pub(crate) mask_type_builder_ident: Ident, -} - -impl ParsedBundle { - fn parse_field( - errors: &mut Errors, - field: &mut Field, - index: usize, - ) -> Option> { - let Field { - attrs, - vis: _, - mutability, - ident, - colon_token, - ty, - } = field; - let ident = ident.get_or_insert_with(|| format_ident!("_{}", index, span = ty.span())); - if !matches!(mutability, FieldMutability::None) { - // FIXME: use mutability as the spanned tokens, - // blocked on https://github.com/dtolnay/syn/issues/1717 - errors.error(&ident, "field mutability is not supported"); - *mutability = FieldMutability::None; - } - *mutability = FieldMutability::None; - colon_token.get_or_insert(Token![:](ident.span())); - let options = errors.unwrap_or_default(HdlAttr::parse_and_take_attr(attrs)); - options - } - fn parse(item: ItemStruct) -> syn::Result { - let ItemStruct { - mut attrs, - vis, - struct_token, - ident, - mut generics, - fields, - semi_token, - } = item; - let mut errors = Errors::new(); - let mut options = errors - .unwrap_or_default(HdlAttr::::parse_and_take_attr(&mut attrs)) - .unwrap_or_default(); - errors.ok(options.body.validate()); - let ItemOptions { - outline_generated: _, - target: _, - custom_bounds, - no_static: _, - no_runtime_generics: _, - } = options.body; - let mut fields = match fields { - syn::Fields::Named(fields) => fields, - syn::Fields::Unnamed(fields) => { - errors.error(&fields, "#[hdl] struct must use curly braces: {}"); - FieldsNamed { - brace_token: Brace(fields.paren_token.span), - named: fields.unnamed, - } - } - syn::Fields::Unit => { - errors.error(&fields, "#[hdl] struct must use curly braces: {}"); - FieldsNamed { - brace_token: Brace(semi_token.unwrap_or_default().span), - named: Punctuated::default(), - } - } - }; - let mut field_flips = Vec::with_capacity(fields.named.len()); - for (index, field) in fields.named.iter_mut().enumerate() { - field_flips.push(Self::parse_field(&mut errors, field, index)); - } - let generics = if custom_bounds.is_some() { - MaybeParsed::Unrecognized(generics) - } else if let Some(generics) = errors.ok(ParsedGenerics::parse(&mut generics)) { - MaybeParsed::Parsed(generics) - } else { - MaybeParsed::Unrecognized(generics) - }; - let fields = TypesParser::maybe_run(generics.as_ref(), fields, &mut errors); - errors.finish()?; - Ok(Self { - attrs, - options, - vis, - struct_token, - generics, - fields, - field_flips, - mask_type_ident: format_ident!("__{}__MaskType", ident), - mask_type_match_variant_ident: format_ident!("__{}__MaskType__MatchVariant", ident), - match_variant_ident: format_ident!("__{}__MatchVariant", ident), - mask_type_builder_ident: format_ident!("__{}__MaskType__Builder", ident), - builder_ident: format_ident!("__{}__Builder", ident), - ident, - }) - } -} - -#[derive(Clone, Debug)] -struct Builder { - vis: Visibility, - struct_token: Token![struct], - ident: Ident, - target: Path, - generics: Generics, - fields: FieldsNamed, -} - -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -enum BuilderFieldState { - Unfilled, - Generic, - Filled, -} - -impl Builder { - fn phantom_field_name(&self) -> Ident { - format_ident!("__phantom", span = self.ident.span()) - } - fn phantom_field(&self) -> Field { - let target = &self.target; - let type_generics = self.generics.split_for_impl().1; - Field { - attrs: vec![], - vis: Visibility::Inherited, - mutability: FieldMutability::None, - ident: Some(self.phantom_field_name()), - colon_token: Some(Token![:](self.ident.span())), - ty: parse_quote_spanned! {self.ident.span()=> - ::fayalite::__std::marker::PhantomData<#target #type_generics> - }, - } - } - fn builder_struct_generics( - &self, - mut get_field_state: impl FnMut(usize) -> BuilderFieldState, - ) -> Generics { - let mut retval = self.generics.clone(); - for param in retval.params.iter_mut() { - match param { - GenericParam::Lifetime(_) => {} - GenericParam::Type(param) => param.default = None, - GenericParam::Const(param) => param.default = None, - } - } - for (field_index, field) in self.fields.named.iter().enumerate() { - match get_field_state(field_index) { - BuilderFieldState::Unfilled | BuilderFieldState::Filled => continue, - BuilderFieldState::Generic => {} - } - if !retval.params.empty_or_trailing() { - retval.params.push_punct(Token![,](self.ident.span())); - } - retval.params.push_value(GenericParam::Type( - type_var_for_field_name(field.ident.as_ref().unwrap()).into(), - )); - } - retval - } - fn builder_struct_ty( - &self, - mut get_field_state: impl FnMut(usize) -> BuilderFieldState, - ) -> Type { - let mut ty_arguments: AngleBracketedGenericArguments = if self.generics.params.is_empty() { - parse_quote_spanned! {self.ident.span()=> - <> - } - } else { - let builder_type_generics = self.generics.split_for_impl().1; - parse_quote! { #builder_type_generics } - }; - for (field_index, Field { ident, ty, .. }) in self.fields.named.iter().enumerate() { - let ident = ident.as_ref().unwrap(); - if !ty_arguments.args.empty_or_trailing() { - ty_arguments.args.push_punct(Token![,](self.ident.span())); - } - ty_arguments - .args - .push_value(match get_field_state(field_index) { - BuilderFieldState::Unfilled => parse_quote_spanned! {self.ident.span()=> - ::fayalite::bundle::Unfilled<#ty> - }, - BuilderFieldState::Generic => { - let type_var = type_var_for_field_name(ident); - parse_quote_spanned! {self.ident.span()=> - #type_var - } - } - BuilderFieldState::Filled => parse_quote_spanned! {self.ident.span()=> - ::fayalite::expr::Expr<#ty> - }, - }); - } - let ident = &self.ident; - parse_quote_spanned! {ident.span()=> - #ident #ty_arguments - } - } -} - -fn type_var_for_field_name(ident: &Ident) -> Ident { - format_ident!("__T_{}", ident) -} - -fn field_fn_for_field_name(ident: &Ident) -> Ident { - format_ident!("field_{}", ident) -} - -impl ToTokens for Builder { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - vis, - struct_token, - ident, - target, - generics: _, - fields, - } = self; - let phantom_field_name = self.phantom_field_name(); - let builder_struct = ItemStruct { - attrs: vec![parse_quote_spanned! {ident.span()=> - #[allow(non_camel_case_types, dead_code)] - }], - vis: vis.clone(), - struct_token: *struct_token, - ident: ident.clone(), - generics: self.builder_struct_generics(|_| BuilderFieldState::Generic), - fields: Fields::Named(FieldsNamed { - brace_token: fields.brace_token, - named: Punctuated::from_iter( - [Pair::Punctuated( - self.phantom_field(), - Token![,](self.ident.span()), - )] - .into_iter() - .chain(fields.named.pairs().map_pair_value_ref(|field| { - let ident = field.ident.as_ref().unwrap(); - let type_var = type_var_for_field_name(ident); - Field { - vis: Visibility::Inherited, - ty: parse_quote_spanned! {ident.span()=> - #type_var - }, - ..field.clone() - } - })), - ), - }), - semi_token: None, - }; - builder_struct.to_tokens(tokens); - let field_idents = Vec::from_iter( - self.fields - .named - .iter() - .map(|field| field.ident.as_ref().unwrap()), - ); - for ( - field_index, - Field { - vis, - ident: field_ident, - ty, - .. - }, - ) in self.fields.named.iter().enumerate() - { - let field_ident = field_ident.as_ref().unwrap(); - let fn_ident = field_fn_for_field_name(field_ident); - let fn_generics = self.builder_struct_generics(|i| { - if i == field_index { - BuilderFieldState::Unfilled - } else { - BuilderFieldState::Generic - } - }); - let (impl_generics, _, where_clause) = fn_generics.split_for_impl(); - let unfilled_ty = self.builder_struct_ty(|i| { - if i == field_index { - BuilderFieldState::Unfilled - } else { - BuilderFieldState::Generic - } - }); - let filled_ty = self.builder_struct_ty(|i| { - if i == field_index { - BuilderFieldState::Filled - } else { - BuilderFieldState::Generic - } - }); - let pat_fields = - Vec::from_iter(self.fields.named.iter().enumerate().map(|(i, field)| { - let field_ident = field.ident.as_ref().unwrap(); - if field_index == i { - quote_spanned! {self.ident.span()=> - #field_ident: _, - } - } else { - quote_spanned! {self.ident.span()=> - #field_ident, - } - } - })); - quote_spanned! {self.ident.span()=> - #[automatically_derived] - #[allow(non_camel_case_types, dead_code)] - impl #impl_generics #unfilled_ty - #where_clause - { - #vis fn #fn_ident( - self, - #field_ident: impl ::fayalite::expr::ToExpr, - ) -> #filled_ty { - let Self { - #phantom_field_name: _, - #(#pat_fields)* - } = self; - let #field_ident = ::fayalite::expr::ToExpr::to_expr(&#field_ident); - #ident { - #phantom_field_name: ::fayalite::__std::marker::PhantomData, - #(#field_idents,)* - } - } - } - } - .to_tokens(tokens); - } - let unfilled_generics = self.builder_struct_generics(|_| BuilderFieldState::Unfilled); - let unfilled_ty = self.builder_struct_ty(|_| BuilderFieldState::Unfilled); - let (unfilled_impl_generics, _, unfilled_where_clause) = unfilled_generics.split_for_impl(); - quote_spanned! {self.ident.span()=> - #[automatically_derived] - #[allow(non_camel_case_types, dead_code)] - impl #unfilled_impl_generics ::fayalite::__std::default::Default for #unfilled_ty - #unfilled_where_clause - { - fn default() -> Self { - #ident { - #phantom_field_name: ::fayalite::__std::marker::PhantomData, - #(#field_idents: ::fayalite::__std::default::Default::default(),)* - } - } - } - } - .to_tokens(tokens); - let filled_generics = self.builder_struct_generics(|_| BuilderFieldState::Filled); - let filled_ty = self.builder_struct_ty(|_| BuilderFieldState::Filled); - let (filled_impl_generics, _, filled_where_clause) = filled_generics.split_for_impl(); - let type_generics = self.generics.split_for_impl().1; - quote_spanned! {self.ident.span()=> - #[automatically_derived] - #[allow(non_camel_case_types, dead_code)] - impl #filled_impl_generics ::fayalite::expr::ToExpr for #filled_ty - #filled_where_clause - { - type Type = #target #type_generics; - fn to_expr( - &self, - ) -> ::fayalite::expr::Expr<::Type> { - let __ty = #target { - #(#field_idents: ::fayalite::expr::Expr::ty(self.#field_idents),)* - }; - let __field_values = [ - #(::fayalite::expr::Expr::canonical(self.#field_idents),)* - ]; - ::fayalite::expr::ToExpr::to_expr( - &::fayalite::expr::ops::BundleLiteral::new( - __ty, - ::fayalite::intern::Intern::intern(&__field_values[..]), - ), - ) - } - } - } - .to_tokens(tokens); - } -} - -impl ToTokens for ParsedBundle { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - attrs, - options, - vis, - struct_token, - ident, - generics, - fields, - field_flips, - mask_type_ident, - mask_type_match_variant_ident, - match_variant_ident, - builder_ident, - mask_type_builder_ident, - } = self; - let ItemOptions { - outline_generated: _, - target, - custom_bounds: _, - no_static, - no_runtime_generics, - } = &options.body; - let target = get_target(target, ident); - let mut item_attrs = attrs.clone(); - item_attrs.push(common_derives(ident.span())); - ItemStruct { - attrs: item_attrs, - vis: vis.clone(), - struct_token: *struct_token, - ident: ident.clone(), - generics: generics.into(), - fields: Fields::Named(fields.clone().into()), - semi_token: None, - } - .to_tokens(tokens); - let (impl_generics, type_generics, where_clause) = generics.split_for_impl(); - if let (MaybeParsed::Parsed(generics), MaybeParsed::Parsed(fields), None) = - (generics, fields, no_runtime_generics) - { - generics.make_runtime_generics(tokens, vis, ident, &target, |context| { - let fields: Vec<_> = fields - .named - .iter() - .map(|ParsedField { ident, ty, .. }| { - let ident = ident.as_ref().unwrap(); - let expr = ty.make_hdl_type_expr(context); - quote_spanned! {ident.span()=> - #ident: #expr, - } - }) - .collect(); - parse_quote_spanned! {ident.span()=> - #target { - #(#fields)* - } - } - }) - } - let mut wrapped_in_const = WrappedInConst::new(tokens, ident.span()); - let tokens = wrapped_in_const.inner(); - let builder = Builder { - vis: vis.clone(), - struct_token: *struct_token, - ident: builder_ident.clone(), - target: target.clone(), - generics: generics.into(), - fields: fields.clone().into(), - }; - builder.to_tokens(tokens); - let unfilled_builder_ty = builder.builder_struct_ty(|_| BuilderFieldState::Unfilled); - let filled_builder_ty = builder.builder_struct_ty(|_| BuilderFieldState::Filled); - let mut mask_type_fields = FieldsNamed::from(fields.clone()); - for Field { ident, ty, .. } in &mut mask_type_fields.named { - let ident = ident.as_ref().unwrap(); - *ty = parse_quote_spanned! {ident.span()=> - <#ty as ::fayalite::ty::Type>::MaskType - }; - } - let mask_type_builder = Builder { - vis: vis.clone(), - struct_token: *struct_token, - ident: mask_type_builder_ident.clone(), - target: mask_type_ident.clone().into(), - generics: generics.into(), - fields: mask_type_fields.clone(), - }; - mask_type_builder.to_tokens(tokens); - let unfilled_mask_type_builder_ty = - mask_type_builder.builder_struct_ty(|_| BuilderFieldState::Unfilled); - let filled_mask_type_builder_ty = - mask_type_builder.builder_struct_ty(|_| BuilderFieldState::Filled); - ItemStruct { - attrs: vec![ - common_derives(ident.span()), - parse_quote_spanned! {ident.span()=> - #[allow(non_camel_case_types, dead_code)] - }, - ], - vis: vis.clone(), - struct_token: *struct_token, - ident: mask_type_ident.clone(), - generics: generics.into(), - fields: Fields::Named(mask_type_fields.clone()), - semi_token: None, - } - .to_tokens(tokens); - let mut mask_type_match_variant_fields = mask_type_fields; - for Field { ident, ty, .. } in &mut mask_type_match_variant_fields.named { - let ident = ident.as_ref().unwrap(); - *ty = parse_quote_spanned! {ident.span()=> - ::fayalite::expr::Expr<#ty> - }; - } - ItemStruct { - attrs: vec![ - common_derives(ident.span()), - parse_quote_spanned! {ident.span()=> - #[allow(non_camel_case_types, dead_code)] - }, - ], - vis: vis.clone(), - struct_token: *struct_token, - ident: mask_type_match_variant_ident.clone(), - generics: generics.into(), - fields: Fields::Named(mask_type_match_variant_fields), - semi_token: None, - } - .to_tokens(tokens); - let mut match_variant_fields = FieldsNamed::from(fields.clone()); - for Field { ident, ty, .. } in &mut match_variant_fields.named { - let ident = ident.as_ref().unwrap(); - *ty = parse_quote_spanned! {ident.span()=> - ::fayalite::expr::Expr<#ty> - }; - } - ItemStruct { - attrs: vec![ - common_derives(ident.span()), - parse_quote_spanned! {ident.span()=> - #[allow(non_camel_case_types, dead_code)] - }, - ], - vis: vis.clone(), - struct_token: *struct_token, - ident: match_variant_ident.clone(), - generics: generics.into(), - fields: Fields::Named(match_variant_fields), - semi_token: None, - } - .to_tokens(tokens); - let match_variant_body_fields = Vec::from_iter(fields.named().into_iter().map(|field| { - let ident: &Ident = field.ident().as_ref().unwrap(); - let ident_str = ident.to_string(); - quote_spanned! {ident.span()=> - #ident: ::fayalite::expr::Expr::field(__this, #ident_str), - } - })); - let mask_type_body_fields = Vec::from_iter(fields.named().into_iter().map(|field| { - let ident: &Ident = field.ident().as_ref().unwrap(); - quote_spanned! {ident.span()=> - #ident: ::fayalite::ty::Type::mask_type(&self.#ident), - } - })); - let from_canonical_body_fields = - Vec::from_iter(fields.named().into_iter().enumerate().zip(field_flips).map( - |((index, field), flip)| { - let ident: &Ident = field.ident().as_ref().unwrap(); - let ident_str = ident.to_string(); - let flipped = flip.is_some(); - quote_spanned! {ident.span()=> - #ident: { - let ::fayalite::bundle::BundleField { - name: __name, - flipped: __flipped, - ty: __ty, - } = __fields[#index]; - ::fayalite::__std::assert_eq!(&*__name, #ident_str); - ::fayalite::__std::assert_eq!(__flipped, #flipped); - ::fayalite::ty::Type::from_canonical(__ty) - }, - } - }, - )); - let fields_body_fields = Vec::from_iter(fields.named().into_iter().zip(field_flips).map( - |(field, flip)| { - let ident: &Ident = field.ident().as_ref().unwrap(); - let ident_str = ident.to_string(); - let flipped = flip.is_some(); - quote_spanned! {ident.span()=> - ::fayalite::bundle::BundleField { - name: ::fayalite::intern::Intern::intern(#ident_str), - flipped: #flipped, - ty: ::fayalite::ty::Type::canonical(&self.#ident), - }, - } - }, - )); - let fields_len = fields.named().into_iter().len(); - quote_spanned! {ident.span()=> - #[automatically_derived] - impl #impl_generics ::fayalite::ty::Type for #mask_type_ident #type_generics - #where_clause - { - type BaseType = ::fayalite::bundle::Bundle; - type MaskType = #mask_type_ident #type_generics; - type MatchVariant = #mask_type_match_variant_ident #type_generics; - type MatchActiveScope = (); - type MatchVariantAndInactiveScope = ::fayalite::ty::MatchVariantWithoutScope< - ::MatchVariant, - >; - type MatchVariantsIter = ::fayalite::__std::iter::Once< - ::MatchVariantAndInactiveScope, - >; - fn match_variants( - __this: ::fayalite::expr::Expr, - __source_location: ::fayalite::source_location::SourceLocation, - ) -> ::MatchVariantsIter { - let __retval = #mask_type_match_variant_ident { - #(#match_variant_body_fields)* - }; - ::fayalite::__std::iter::once(::fayalite::ty::MatchVariantWithoutScope(__retval)) - } - fn mask_type(&self) -> ::MaskType { - *self - } - fn canonical(&self) -> ::fayalite::ty::CanonicalType { - ::fayalite::ty::Type::canonical(&::fayalite::bundle::Bundle::new(::fayalite::bundle::BundleType::fields(self))) - } - #[track_caller] - fn from_canonical(__canonical_type: ::fayalite::ty::CanonicalType) -> Self { - let ::fayalite::ty::CanonicalType::Bundle(__bundle) = __canonical_type else { - ::fayalite::__std::panic!("expected bundle"); - }; - let __fields = ::fayalite::bundle::BundleType::fields(&__bundle); - ::fayalite::__std::assert_eq!(__fields.len(), #fields_len, "bundle has wrong number of fields"); - Self { - #(#from_canonical_body_fields)* - } - } - fn source_location() -> ::fayalite::source_location::SourceLocation { - ::fayalite::source_location::SourceLocation::caller() - } - } - #[automatically_derived] - impl #impl_generics ::fayalite::bundle::BundleType for #mask_type_ident #type_generics - #where_clause - { - type Builder = #unfilled_mask_type_builder_ty; - type FilledBuilder = #filled_mask_type_builder_ty; - fn fields(&self) -> ::fayalite::intern::Interned<[::fayalite::bundle::BundleField]> { - ::fayalite::intern::Intern::intern(&[#(#fields_body_fields)*][..]) - } - } - impl #impl_generics #mask_type_ident #type_generics - #where_clause - { - #vis fn __bundle_builder() -> #unfilled_mask_type_builder_ty { - ::fayalite::__std::default::Default::default() - } - } - #[automatically_derived] - impl #impl_generics ::fayalite::ty::TypeWithDeref for #mask_type_ident #type_generics - #where_clause - { - fn expr_deref(__this: &::fayalite::expr::Expr) -> &::MatchVariant { - let __this = *__this; - let __retval = #mask_type_match_variant_ident { - #(#match_variant_body_fields)* - }; - ::fayalite::intern::Interned::<_>::into_inner(::fayalite::intern::Intern::intern_sized(__retval)) - } - } - #[automatically_derived] - impl #impl_generics ::fayalite::ty::Type for #target #type_generics - #where_clause - { - type BaseType = ::fayalite::bundle::Bundle; - type MaskType = #mask_type_ident #type_generics; - type MatchVariant = #match_variant_ident #type_generics; - type MatchActiveScope = (); - type MatchVariantAndInactiveScope = ::fayalite::ty::MatchVariantWithoutScope< - ::MatchVariant, - >; - type MatchVariantsIter = ::fayalite::__std::iter::Once< - ::MatchVariantAndInactiveScope, - >; - fn match_variants( - __this: ::fayalite::expr::Expr, - __source_location: ::fayalite::source_location::SourceLocation, - ) -> ::MatchVariantsIter { - let __retval = #match_variant_ident { - #(#match_variant_body_fields)* - }; - ::fayalite::__std::iter::once(::fayalite::ty::MatchVariantWithoutScope(__retval)) - } - fn mask_type(&self) -> ::MaskType { - #mask_type_ident { - #(#mask_type_body_fields)* - } - } - fn canonical(&self) -> ::fayalite::ty::CanonicalType { - ::fayalite::ty::Type::canonical(&::fayalite::bundle::Bundle::new(::fayalite::bundle::BundleType::fields(self))) - } - #[track_caller] - fn from_canonical(__canonical_type: ::fayalite::ty::CanonicalType) -> Self { - let ::fayalite::ty::CanonicalType::Bundle(__bundle) = __canonical_type else { - ::fayalite::__std::panic!("expected bundle"); - }; - let __fields = ::fayalite::bundle::BundleType::fields(&__bundle); - ::fayalite::__std::assert_eq!(__fields.len(), #fields_len, "bundle has wrong number of fields"); - Self { - #(#from_canonical_body_fields)* - } - } - fn source_location() -> ::fayalite::source_location::SourceLocation { - ::fayalite::source_location::SourceLocation::caller() - } - } - #[automatically_derived] - impl #impl_generics ::fayalite::bundle::BundleType for #target #type_generics - #where_clause - { - type Builder = #unfilled_builder_ty; - type FilledBuilder = #filled_builder_ty; - fn fields(&self) -> ::fayalite::intern::Interned<[::fayalite::bundle::BundleField]> { - ::fayalite::intern::Intern::intern(&[#(#fields_body_fields)*][..]) - } - } - impl #impl_generics #target #type_generics - #where_clause - { - #vis fn __bundle_builder() -> #unfilled_builder_ty { - ::fayalite::__std::default::Default::default() - } - } - #[automatically_derived] - impl #impl_generics ::fayalite::ty::TypeWithDeref for #target #type_generics - #where_clause - { - fn expr_deref(__this: &::fayalite::expr::Expr) -> &::MatchVariant { - let __this = *__this; - let __retval = #match_variant_ident { - #(#match_variant_body_fields)* - }; - ::fayalite::intern::Interned::<_>::into_inner(::fayalite::intern::Intern::intern_sized(__retval)) - } - } - } - .to_tokens(tokens); - if let (None, MaybeParsed::Parsed(generics)) = (no_static, &self.generics) { - let static_generics = generics.clone().for_static_type(); - let (static_impl_generics, static_type_generics, static_where_clause) = - static_generics.split_for_impl(); - let static_type_body_fields = Vec::from_iter(fields.named().into_iter().map(|field| { - let ident: &Ident = field.ident().as_ref().unwrap(); - let ty = field.ty(); - quote_spanned! {ident.span()=> - #ident: <#ty as ::fayalite::ty::StaticType>::TYPE, - } - })); - let static_mask_type_body_fields = - Vec::from_iter(fields.named().into_iter().map(|field| { - let ident: &Ident = field.ident().as_ref().unwrap(); - let ty = field.ty(); - quote_spanned! {ident.span()=> - #ident: <#ty as ::fayalite::ty::StaticType>::MASK_TYPE, - } - })); - let type_properties = format_ident!("__type_properties", span = ident.span()); - let type_properties_fields = Vec::from_iter(fields.named().into_iter().zip(field_flips).map(|(field, field_flip)| { - let ident: &Ident = field.ident().as_ref().unwrap(); - let flipped = field_flip.is_some(); - let ty = field.ty(); - quote_spanned! {ident.span()=> - let #type_properties = #type_properties.field(#flipped, <#ty as ::fayalite::ty::StaticType>::TYPE_PROPERTIES); - } - })); - let type_properties_mask_fields = Vec::from_iter(fields.named().into_iter().zip(field_flips).map(|(field, field_flip)| { - let ident: &Ident = field.ident().as_ref().unwrap(); - let flipped = field_flip.is_some(); - let ty = field.ty(); - quote_spanned! {ident.span()=> - let #type_properties = #type_properties.field(#flipped, <#ty as ::fayalite::ty::StaticType>::MASK_TYPE_PROPERTIES); - } - })); - quote_spanned! {ident.span()=> - #[automatically_derived] - impl #static_impl_generics ::fayalite::ty::StaticType for #mask_type_ident #static_type_generics - #static_where_clause - { - const TYPE: Self = Self { - #(#static_mask_type_body_fields)* - }; - const MASK_TYPE: ::MaskType = Self { - #(#static_mask_type_body_fields)* - }; - const TYPE_PROPERTIES: ::fayalite::ty::TypeProperties = { - let #type_properties = ::fayalite::bundle::BundleTypePropertiesBuilder::new(); - #(#type_properties_mask_fields)* - #type_properties.finish() - }; - const MASK_TYPE_PROPERTIES: ::fayalite::ty::TypeProperties = { - let #type_properties = ::fayalite::bundle::BundleTypePropertiesBuilder::new(); - #(#type_properties_mask_fields)* - #type_properties.finish() - }; - } - #[automatically_derived] - impl #static_impl_generics ::fayalite::ty::StaticType for #target #static_type_generics - #static_where_clause - { - const TYPE: Self = Self { - #(#static_type_body_fields)* - }; - const MASK_TYPE: ::MaskType = #mask_type_ident { - #(#static_mask_type_body_fields)* - }; - const TYPE_PROPERTIES: ::fayalite::ty::TypeProperties = { - let #type_properties = ::fayalite::bundle::BundleTypePropertiesBuilder::new(); - #(#type_properties_fields)* - #type_properties.finish() - }; - const MASK_TYPE_PROPERTIES: ::fayalite::ty::TypeProperties = { - let #type_properties = ::fayalite::bundle::BundleTypePropertiesBuilder::new(); - #(#type_properties_mask_fields)* - #type_properties.finish() - }; - } - } - .to_tokens(tokens); - } - } -} - -pub(crate) fn hdl_bundle(item: ItemStruct) -> syn::Result { - let item = ParsedBundle::parse(item)?; - let outline_generated = item.options.body.outline_generated; - let mut contents = item.to_token_stream(); - if outline_generated.is_some() { - contents = crate::outline_generated(contents, "hdl-bundle-"); - } - Ok(contents) -} diff --git a/crates/fayalite-proc-macros-impl/src/hdl_enum.rs b/crates/fayalite-proc-macros-impl/src/hdl_enum.rs deleted file mode 100644 index 1e0b66b..0000000 --- a/crates/fayalite-proc-macros-impl/src/hdl_enum.rs +++ /dev/null @@ -1,656 +0,0 @@ -use crate::{ - hdl_type_common::{ - common_derives, get_target, ItemOptions, MakeHdlTypeExpr, MaybeParsed, ParsedGenerics, - ParsedType, SplitForImpl, TypesParser, WrappedInConst, - }, - Errors, HdlAttr, PairsIterExt, -}; -use proc_macro2::TokenStream; -use quote::{format_ident, quote_spanned, ToTokens}; -use syn::{ - parse_quote_spanned, - punctuated::{Pair, Punctuated}, - token::{Brace, Paren}, - Attribute, Field, FieldMutability, Fields, FieldsNamed, FieldsUnnamed, Generics, Ident, - ItemEnum, ItemStruct, Token, Type, Variant, Visibility, -}; - -crate::options! { - #[options = VariantOptions] - pub(crate) enum VariantOption {} -} - -crate::options! { - #[options = FieldOptions] - pub(crate) enum FieldOption {} -} - -#[derive(Clone, Debug)] -pub(crate) struct ParsedVariantField { - pub(crate) paren_token: Paren, - pub(crate) attrs: Vec, - pub(crate) options: HdlAttr, - pub(crate) ty: MaybeParsed, - pub(crate) comma_token: Option, -} - -#[derive(Clone, Debug)] -pub(crate) struct ParsedVariant { - pub(crate) attrs: Vec, - pub(crate) options: HdlAttr, - pub(crate) ident: Ident, - pub(crate) field: Option, -} - -impl ParsedVariant { - fn parse( - errors: &mut Errors, - variant: Variant, - generics: &MaybeParsed, - ) -> Self { - let Variant { - mut attrs, - ident, - fields, - discriminant, - } = variant; - let options = errors - .unwrap_or_default(HdlAttr::parse_and_take_attr(&mut attrs)) - .unwrap_or_default(); - let field = match fields { - Fields::Unnamed(FieldsUnnamed { - paren_token, - unnamed, - }) if unnamed.len() == 1 => { - let (field, comma_token) = unnamed.into_pairs().next().unwrap().into_tuple(); - let Field { - mut attrs, - vis, - mutability, - ident: _, - colon_token: _, - ty, - } = field; - let options = errors - .unwrap_or_default(HdlAttr::parse_and_take_attr(&mut attrs)) - .unwrap_or_default(); - if !matches!(vis, Visibility::Inherited) { - errors.error( - &vis, - "enum variant fields must not have a visibility specifier", - ); - } - if !matches!(mutability, FieldMutability::None) { - // FIXME: use mutability as the spanned tokens, - // blocked on https://github.com/dtolnay/syn/issues/1717 - errors.error(&ty, "field mutability is not supported"); - } - Some(ParsedVariantField { - paren_token, - attrs, - options, - ty: TypesParser::maybe_run(generics.as_ref(), ty, errors), - comma_token, - }) - } - Fields::Unit => None, - Fields::Unnamed(fields) if fields.unnamed.is_empty() => None, - Fields::Named(fields) if fields.named.is_empty() => None, - Fields::Unnamed(_) | Fields::Named(_) => { - errors.error( - fields, - "enum variant must either have no fields or a single parenthesized field", - ); - None - } - }; - if let Some((eq, _)) = discriminant { - errors.error(eq, "custom enum discriminants are not allowed"); - } - Self { - attrs, - options, - ident, - field, - } - } -} - -#[derive(Clone, Debug)] -pub(crate) struct ParsedEnum { - pub(crate) attrs: Vec, - pub(crate) options: HdlAttr, - pub(crate) vis: Visibility, - pub(crate) enum_token: Token![enum], - pub(crate) ident: Ident, - pub(crate) generics: MaybeParsed, - pub(crate) brace_token: Brace, - pub(crate) variants: Punctuated, - pub(crate) match_variant_ident: Ident, -} - -impl ParsedEnum { - fn parse(item: ItemEnum) -> syn::Result { - let ItemEnum { - mut attrs, - vis, - enum_token, - ident, - mut generics, - brace_token, - variants, - } = item; - let mut errors = Errors::new(); - let mut options = errors - .unwrap_or_default(HdlAttr::::parse_and_take_attr(&mut attrs)) - .unwrap_or_default(); - errors.ok(options.body.validate()); - let ItemOptions { - outline_generated: _, - target: _, - custom_bounds, - no_static: _, - no_runtime_generics: _, - } = options.body; - attrs.retain(|attr| { - if attr.path().is_ident("repr") { - errors.error(attr, "#[repr] is not supported on #[hdl] enums"); - false - } else { - true - } - }); - let generics = if custom_bounds.is_some() { - MaybeParsed::Unrecognized(generics) - } else if let Some(generics) = errors.ok(ParsedGenerics::parse(&mut generics)) { - MaybeParsed::Parsed(generics) - } else { - MaybeParsed::Unrecognized(generics) - }; - let variants = Punctuated::from_iter( - variants - .into_pairs() - .map_pair_value(|v| ParsedVariant::parse(&mut errors, v, &generics)), - ); - errors.finish()?; - Ok(Self { - attrs, - options, - vis, - enum_token, - generics, - brace_token, - variants, - match_variant_ident: format_ident!("__{}__MatchVariant", ident), - ident, - }) - } -} - -impl ToTokens for ParsedEnum { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - attrs, - options, - vis, - enum_token, - ident, - generics, - brace_token, - variants, - match_variant_ident, - } = self; - let ItemOptions { - outline_generated: _, - target, - custom_bounds: _, - no_static, - no_runtime_generics, - } = &options.body; - let target = get_target(target, ident); - let mut struct_attrs = attrs.clone(); - struct_attrs.push(common_derives(ident.span())); - struct_attrs.push(parse_quote_spanned! {ident.span()=> - #[allow(non_snake_case)] - }); - let struct_fields = Punctuated::from_iter(variants.pairs().map_pair_value_ref( - |ParsedVariant { - attrs: _, - options, - ident, - field, - }| { - let VariantOptions {} = options.body; - let colon_token; - let ty = if let Some(ParsedVariantField { - paren_token, - attrs: _, - options, - ty, - comma_token: _, - }) = field - { - let FieldOptions {} = options.body; - colon_token = Token![:](paren_token.span.open()); - ty.clone().into() - } else { - colon_token = Token![:](ident.span()); - parse_quote_spanned! {ident.span()=> - () - } - }; - Field { - attrs: vec![], - vis: vis.clone(), - mutability: FieldMutability::None, - ident: Some(ident.clone()), - colon_token: Some(colon_token), - ty, - } - }, - )); - ItemStruct { - attrs: struct_attrs, - vis: vis.clone(), - struct_token: Token![struct](enum_token.span), - ident: ident.clone(), - generics: generics.into(), - fields: if struct_fields.is_empty() { - Fields::Unit - } else { - Fields::Named(FieldsNamed { - brace_token: *brace_token, - named: struct_fields, - }) - }, - semi_token: None, - } - .to_tokens(tokens); - let (impl_generics, type_generics, where_clause) = generics.split_for_impl(); - if let (MaybeParsed::Parsed(generics), None) = (generics, no_runtime_generics) { - generics.make_runtime_generics(tokens, vis, ident, &target, |context| { - let fields: Vec<_> = variants - .iter() - .map(|ParsedVariant { ident, field, .. }| { - if let Some(ParsedVariantField { - ty: MaybeParsed::Parsed(ty), - .. - }) = field - { - let expr = ty.make_hdl_type_expr(context); - quote_spanned! {ident.span()=> - #ident: #expr, - } - } else { - quote_spanned! {ident.span()=> - #ident: (), - } - } - }) - .collect(); - parse_quote_spanned! {ident.span()=> - #target { - #(#fields)* - } - } - }) - } - let mut wrapped_in_const = WrappedInConst::new(tokens, ident.span()); - let tokens = wrapped_in_const.inner(); - { - let mut wrapped_in_const = WrappedInConst::new(tokens, ident.span()); - let tokens = wrapped_in_const.inner(); - let mut enum_attrs = attrs.clone(); - enum_attrs.push(parse_quote_spanned! {ident.span()=> - #[allow(dead_code)] - }); - ItemEnum { - attrs: enum_attrs, - vis: vis.clone(), - enum_token: *enum_token, - ident: ident.clone(), - generics: generics.into(), - brace_token: *brace_token, - variants: Punctuated::from_iter(variants.pairs().map_pair_value_ref( - |ParsedVariant { - attrs, - options: _, - ident, - field, - }| Variant { - attrs: attrs.clone(), - ident: ident.clone(), - fields: match field { - Some(ParsedVariantField { - paren_token, - attrs, - options: _, - ty, - comma_token, - }) => Fields::Unnamed(FieldsUnnamed { - paren_token: *paren_token, - unnamed: Punctuated::from_iter([Pair::new( - Field { - attrs: attrs.clone(), - vis: Visibility::Inherited, - mutability: FieldMutability::None, - ident: None, - colon_token: None, - ty: ty.clone().into(), - }, - *comma_token, - )]), - }), - None => Fields::Unit, - }, - discriminant: None, - }, - )), - } - .to_tokens(tokens); - } - let mut enum_attrs = attrs.clone(); - enum_attrs.push(parse_quote_spanned! {ident.span()=> - #[allow(dead_code, non_camel_case_types)] - }); - ItemEnum { - attrs: enum_attrs, - vis: vis.clone(), - enum_token: *enum_token, - ident: match_variant_ident.clone(), - generics: generics.into(), - brace_token: *brace_token, - variants: Punctuated::from_iter(variants.pairs().map_pair_value_ref( - |ParsedVariant { - attrs, - options: _, - ident, - field, - }| Variant { - attrs: attrs.clone(), - ident: ident.clone(), - fields: match field { - Some(ParsedVariantField { - paren_token, - attrs, - options: _, - ty, - comma_token, - }) => Fields::Unnamed(FieldsUnnamed { - paren_token: *paren_token, - unnamed: Punctuated::from_iter([Pair::new( - Field { - attrs: attrs.clone(), - vis: Visibility::Inherited, - mutability: FieldMutability::None, - ident: None, - colon_token: None, - ty: parse_quote_spanned! {ident.span()=> - ::fayalite::expr::Expr<#ty> - }, - }, - *comma_token, - )]), - }), - None => Fields::Unit, - }, - discriminant: None, - }, - )), - } - .to_tokens(tokens); - for (index, ParsedVariant { ident, field, .. }) in variants.iter().enumerate() { - if let Some(ParsedVariantField { ty, .. }) = field { - quote_spanned! {ident.span()=> - #[automatically_derived] - impl #impl_generics #target #type_generics - #where_clause - { - #[allow(non_snake_case, dead_code)] - #vis fn #ident<__V: ::fayalite::expr::ToExpr>( - self, - v: __V, - ) -> ::fayalite::expr::Expr { - ::fayalite::expr::ToExpr::to_expr( - &::fayalite::expr::ops::EnumLiteral::new_by_index( - self, - #index, - ::fayalite::__std::option::Option::Some( - ::fayalite::expr::Expr::canonical( - ::fayalite::expr::ToExpr::to_expr(&v), - ), - ), - ), - ) - } - } - } - } else { - quote_spanned! {ident.span()=> - #[automatically_derived] - impl #impl_generics #target #type_generics - #where_clause - { - #[allow(non_snake_case, dead_code)] - #vis fn #ident(self) -> ::fayalite::expr::Expr { - ::fayalite::expr::ToExpr::to_expr( - &::fayalite::expr::ops::EnumLiteral::new_by_index( - self, - #index, - ::fayalite::__std::option::Option::None, - ), - ) - } - } - } - } - .to_tokens(tokens); - } - let from_canonical_body_fields = Vec::from_iter(variants.iter().enumerate().map( - |(index, ParsedVariant { ident, field, .. })| { - let ident_str = ident.to_string(); - let val = if field.is_some() { - let missing_value_msg = format!("expected variant {ident} to have a field"); - quote_spanned! {ident.span()=> - ::fayalite::ty::Type::from_canonical(ty.expect(#missing_value_msg)) - } - } else { - quote_spanned! {ident.span()=> - ::fayalite::__std::assert!(ty.is_none()); - } - }; - quote_spanned! {ident.span()=> - #ident: { - let ::fayalite::enum_::EnumVariant { - name, - ty, - } = variants[#index]; - ::fayalite::__std::assert_eq!(&*name, #ident_str); - #val - }, - } - }, - )); - let match_active_scope_match_arms = Vec::from_iter(variants.iter().enumerate().map( - |(index, ParsedVariant { ident, field, .. })| { - if field.is_some() { - quote_spanned! {ident.span()=> - #index => #match_variant_ident::#ident( - ::fayalite::expr::ToExpr::to_expr( - &::fayalite::expr::ops::VariantAccess::new_by_index( - variant_access.base(), - variant_access.variant_index(), - ), - ), - ), - } - } else { - quote_spanned! {ident.span()=> - #index => #match_variant_ident::#ident, - } - } - }, - )); - let variants_body_variants = Vec::from_iter(variants.iter().map( - |ParsedVariant { - attrs: _, - options, - ident, - field, - }| { - let VariantOptions {} = options.body; - let ident_str = ident.to_string(); - match field { - Some(ParsedVariantField { options, .. }) => { - let FieldOptions {} = options.body; - quote_spanned! {ident.span()=> - ::fayalite::enum_::EnumVariant { - name: ::fayalite::intern::Intern::intern(#ident_str), - ty: ::fayalite::__std::option::Option::Some( - ::fayalite::ty::Type::canonical(&self.#ident), - ), - }, - } - } - None => quote_spanned! {ident.span()=> - ::fayalite::enum_::EnumVariant { - name: ::fayalite::intern::Intern::intern(#ident_str), - ty: ::fayalite::__std::option::Option::None, - }, - }, - } - }, - )); - let variants_len = variants.len(); - quote_spanned! {ident.span()=> - #[automatically_derived] - impl #impl_generics ::fayalite::ty::Type for #target #type_generics - #where_clause - { - type BaseType = ::fayalite::enum_::Enum; - type MaskType = ::fayalite::int::Bool; - type MatchVariant = #match_variant_ident #type_generics; - type MatchActiveScope = ::fayalite::module::Scope; - type MatchVariantAndInactiveScope = ::fayalite::enum_::EnumMatchVariantAndInactiveScope; - type MatchVariantsIter = ::fayalite::enum_::EnumMatchVariantsIter; - - fn match_variants( - this: ::fayalite::expr::Expr, - source_location: ::fayalite::source_location::SourceLocation, - ) -> ::MatchVariantsIter { - ::fayalite::module::enum_match_variants_helper(this, source_location) - } - fn mask_type(&self) -> ::MaskType { - ::fayalite::int::Bool - } - fn canonical(&self) -> ::fayalite::ty::CanonicalType { - ::fayalite::ty::CanonicalType::Enum(::fayalite::enum_::Enum::new(::fayalite::enum_::EnumType::variants(self))) - } - #[track_caller] - #[allow(non_snake_case)] - fn from_canonical(canonical_type: ::fayalite::ty::CanonicalType) -> Self { - let ::fayalite::ty::CanonicalType::Enum(enum_) = canonical_type else { - ::fayalite::__std::panic!("expected enum"); - }; - let variants = ::fayalite::enum_::EnumType::variants(&enum_); - ::fayalite::__std::assert_eq!(variants.len(), #variants_len, "enum has wrong number of variants"); - Self { - #(#from_canonical_body_fields)* - } - } - fn source_location() -> ::fayalite::source_location::SourceLocation { - ::fayalite::source_location::SourceLocation::caller() - } - } - #[automatically_derived] - impl #impl_generics ::fayalite::enum_::EnumType for #target #type_generics - #where_clause - { - fn match_activate_scope( - v: ::MatchVariantAndInactiveScope, - ) -> (::MatchVariant, ::MatchActiveScope) { - let (variant_access, scope) = v.activate(); - ( - match variant_access.variant_index() { - #(#match_active_scope_match_arms)* - #variants_len.. => ::fayalite::__std::panic!("invalid variant index"), - }, - scope, - ) - } - fn variants(&self) -> ::fayalite::intern::Interned<[::fayalite::enum_::EnumVariant]> { - ::fayalite::intern::Intern::intern(&[ - #(#variants_body_variants)* - ][..]) - } - } - } - .to_tokens(tokens); - if let (None, MaybeParsed::Parsed(generics)) = (no_static, &self.generics) { - let static_generics = generics.clone().for_static_type(); - let (static_impl_generics, static_type_generics, static_where_clause) = - static_generics.split_for_impl(); - let static_type_body_variants = - Vec::from_iter(variants.iter().map(|ParsedVariant { ident, field, .. }| { - if let Some(_) = field { - quote_spanned! {ident.span()=> - #ident: ::fayalite::ty::StaticType::TYPE, - } - } else { - quote_spanned! {ident.span()=> - #ident: (), - } - } - })); - let type_properties = format_ident!("__type_properties", span = ident.span()); - let type_properties_variants = - Vec::from_iter(variants.iter().map(|ParsedVariant { ident, field, .. }| { - let variant = if let Some(ParsedVariantField { ty, .. }) = field { - quote_spanned! {ident.span()=> - ::fayalite::__std::option::Option::Some( - <#ty as ::fayalite::ty::StaticType>::TYPE_PROPERTIES, - ) - } - } else { - quote_spanned! {ident.span()=> - ::fayalite::__std::option::Option::None - } - }; - quote_spanned! {ident.span()=> - let #type_properties = #type_properties.variant(#variant); - } - })); - quote_spanned! {ident.span()=> - #[automatically_derived] - impl #static_impl_generics ::fayalite::ty::StaticType - for #target #static_type_generics - #static_where_clause - { - const TYPE: Self = Self { - #(#static_type_body_variants)* - }; - const MASK_TYPE: ::MaskType = - ::fayalite::int::Bool; - const TYPE_PROPERTIES: ::fayalite::ty::TypeProperties = { - let #type_properties = ::fayalite::enum_::EnumTypePropertiesBuilder::new(); - #(#type_properties_variants)* - #type_properties.finish() - }; - const MASK_TYPE_PROPERTIES: ::fayalite::ty::TypeProperties = - <::fayalite::int::Bool as ::fayalite::ty::StaticType>::TYPE_PROPERTIES; - } - } - .to_tokens(tokens); - } - } -} - -pub(crate) fn hdl_enum(item: ItemEnum) -> syn::Result { - let item = ParsedEnum::parse(item)?; - let outline_generated = item.options.body.outline_generated; - let mut contents = item.to_token_stream(); - if outline_generated.is_some() { - contents = crate::outline_generated(contents, "hdl-enum-"); - } - Ok(contents) -} diff --git a/crates/fayalite-proc-macros-impl/src/hdl_type_common.rs b/crates/fayalite-proc-macros-impl/src/hdl_type_common.rs deleted file mode 100644 index 88da9a7..0000000 --- a/crates/fayalite-proc-macros-impl/src/hdl_type_common.rs +++ /dev/null @@ -1,4082 +0,0 @@ -use crate::{fold::impl_fold, kw, Errors, HdlAttr, PairsIterExt}; -use proc_macro2::{Span, TokenStream}; -use quote::{format_ident, quote_spanned, ToTokens}; -use std::{collections::HashMap, fmt, mem}; -use syn::{ - parse::{Parse, ParseStream}, - parse_quote, parse_quote_spanned, - punctuated::{Pair, Punctuated}, - spanned::Spanned, - token::{Brace, Bracket, Paren}, - AngleBracketedGenericArguments, Attribute, Block, ConstParam, Expr, ExprBlock, ExprGroup, - ExprIndex, ExprParen, ExprPath, ExprTuple, Field, FieldMutability, Fields, FieldsNamed, - FieldsUnnamed, GenericArgument, GenericParam, Generics, Ident, ImplGenerics, Index, ItemStruct, - Path, PathArguments, PathSegment, PredicateType, QSelf, Stmt, Token, Turbofish, Type, - TypeGenerics, TypeGroup, TypeParam, TypeParen, TypePath, TypeTuple, Visibility, WhereClause, - WherePredicate, -}; - -crate::options! { - #[options = ItemOptions] - pub(crate) enum ItemOption { - OutlineGenerated(outline_generated), - Target(target, Path), - CustomBounds(custom_bounds), - NoStatic(no_static), - NoRuntimeGenerics(no_runtime_generics), - } -} - -impl ItemOptions { - pub(crate) fn validate(&mut self) -> syn::Result<()> { - if let Self { - custom_bounds: Some((custom_bounds,)), - no_static: None, - .. - } = self - { - self.no_static = Some((kw::no_static(custom_bounds.span),)); - } - Ok(()) - } -} - -pub(crate) struct WrappedInConst<'a> { - outer: &'a mut TokenStream, - span: Span, - inner: TokenStream, -} - -impl<'a> WrappedInConst<'a> { - pub(crate) fn new(outer: &'a mut TokenStream, span: Span) -> Self { - Self { - outer, - span, - inner: TokenStream::new(), - } - } - pub(crate) fn inner(&mut self) -> &mut TokenStream { - &mut self.inner - } -} - -impl Drop for WrappedInConst<'_> { - fn drop(&mut self) { - let inner = &self.inner; - quote_spanned! {self.span=> - const _: () = { - #inner - }; - } - .to_tokens(self.outer); - } -} - -pub(crate) fn get_target(target: &Option<(kw::target, Paren, Path)>, item_ident: &Ident) -> Path { - match target { - Some((_, _, target)) => target.clone(), - None => item_ident.clone().into(), - } -} - -pub(crate) fn common_derives(span: Span) -> Attribute { - parse_quote_spanned! {span=> - #[::fayalite::__std::prelude::v1::derive( - ::fayalite::__std::fmt::Debug, - ::fayalite::__std::cmp::Eq, - ::fayalite::__std::cmp::PartialEq, - ::fayalite::__std::hash::Hash, - ::fayalite::__std::marker::Copy, - ::fayalite::__std::clone::Clone, - )] - } -} - -crate::options! { - #[options = LifetimeParamOptions] - enum LifetimeParamOption {} -} - -crate::options! { - #[options = TypeParamOptions] - pub(crate) enum TypeParamOption {} -} - -crate::options! { - #[options = ConstParamOptions] - pub(crate) enum ConstParamOption {} -} - -macro_rules! parse_failed { - ($parser:ident, $tokens:expr, $message:expr) => {{ - $parser.errors().error($tokens, $message); - return Err(ParseFailed); - }}; -} - -#[derive(Copy, Clone, Debug)] -pub(crate) enum ExprDelimiter { - Group(syn::token::Group), - Brace(Brace), - Paren(Paren), -} - -impl_fold! { - enum ExprDelimiter<> { - Group(syn::token::Group), - Brace(Brace), - Paren(Paren), - } -} - -impl ExprDelimiter { - pub(crate) fn surround(self, tokens: &mut TokenStream, f: F) { - match self { - ExprDelimiter::Group(v) => v.surround(tokens, f), - ExprDelimiter::Brace(v) => v.surround(tokens, f), - ExprDelimiter::Paren(v) => v.surround(tokens, f), - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedExprDelimited { - pub(crate) delim: ExprDelimiter, - pub(crate) expr: Box, -} - -impl_fold! { - struct ParsedExprDelimited<> { - delim: ExprDelimiter, - expr: Box, - } -} - -impl From for Expr { - fn from(value: ParsedExprDelimited) -> Self { - let ParsedExprDelimited { delim, expr } = value; - let expr = expr.into(); - match delim { - ExprDelimiter::Group(group_token) => Expr::Group(ExprGroup { - attrs: vec![], - group_token, - expr: Box::new(expr), - }), - ExprDelimiter::Brace(brace_token) => Expr::Block(ExprBlock { - attrs: vec![], - label: None, - block: Block { - brace_token, - stmts: vec![Stmt::Expr(expr, None)], - }, - }), - ExprDelimiter::Paren(paren_token) => Expr::Paren(ExprParen { - attrs: vec![], - paren_token, - expr: Box::new(expr), - }), - } - } -} - -impl ToTokens for ParsedExprDelimited { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { delim, expr } = self; - delim.surround(tokens, |tokens| expr.to_tokens(tokens)); - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedExprNamedParamConst { - pub(crate) ident: Ident, - pub(crate) param_index: usize, -} - -impl_fold! { - struct ParsedExprNamedParamConst<> { - ident: Ident, - param_index: usize, - } -} - -impl ToTokens for ParsedExprNamedParamConst { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - ident, - param_index: _, - } = self; - ident.to_tokens(tokens); - } -} - -impl From for Expr { - fn from(value: ParsedExprNamedParamConst) -> Self { - Expr::Path(ExprPath { - attrs: vec![], - qself: None, - path: value.ident.into(), - }) - } -} - -#[derive(Clone, Debug)] -pub(crate) enum ParsedExpr { - Delimited(ParsedExprDelimited), - NamedParamConst(ParsedExprNamedParamConst), - Other(Box), -} - -impl ParsedExpr { - pub(crate) fn named_param_const(mut self: &Self) -> Option<&ParsedExprNamedParamConst> { - loop { - match self { - ParsedExpr::Delimited(ParsedExprDelimited { expr, .. }) => self = &**expr, - ParsedExpr::NamedParamConst(retval) => return Some(retval), - ParsedExpr::Other(_) => return None, - } - } - } -} - -impl_fold! { - enum ParsedExpr<> { - Delimited(ParsedExprDelimited), - NamedParamConst(ParsedExprNamedParamConst), - Other(Box), - } -} - -impl ToTokens for ParsedExpr { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - ParsedExpr::Delimited(v) => v.to_tokens(tokens), - ParsedExpr::NamedParamConst(v) => v.to_tokens(tokens), - ParsedExpr::Other(v) => v.to_tokens(tokens), - } - } -} - -impl From for Expr { - fn from(value: ParsedExpr) -> Self { - match value { - ParsedExpr::Delimited(expr) => expr.into(), - ParsedExpr::NamedParamConst(expr) => expr.into(), - ParsedExpr::Other(expr) => *expr, - } - } -} - -impl From> for Expr { - fn from(value: Box) -> Self { - (*value).into() - } -} - -impl ParseTypes for ParsedExpr { - fn parse_types(input: &mut Expr, parser: &mut TypesParser<'_>) -> Result { - match input { - Expr::Block(ExprBlock { - attrs, - label: None, - block: Block { brace_token, stmts }, - }) if attrs.is_empty() && stmts.len() == 1 => { - if let Stmt::Expr(expr, None) = &mut stmts[0] { - return Ok(ParsedExpr::Delimited(ParsedExprDelimited { - delim: ExprDelimiter::Brace(*brace_token), - expr: Box::new(parser.parse(expr)?), - })); - } - } - Expr::Group(ExprGroup { - attrs, - group_token, - expr, - }) if attrs.is_empty() => { - return Ok(ParsedExpr::Delimited(ParsedExprDelimited { - delim: ExprDelimiter::Group(*group_token), - expr: parser.parse(expr)?, - })) - } - Expr::Paren(ExprParen { - attrs, - paren_token, - expr, - }) if attrs.is_empty() => { - return Ok(ParsedExpr::Delimited(ParsedExprDelimited { - delim: ExprDelimiter::Paren(*paren_token), - expr: parser.parse(expr)?, - })) - } - Expr::Path(ExprPath { - attrs, - qself: None, - path, - }) if attrs.is_empty() => { - if let Some((param_index, ident)) = parser.get_named_param(path) { - return Ok(Self::NamedParamConst( - match parser.generics().params[param_index] { - ParsedGenericParam::Const(_) => ParsedExprNamedParamConst { - ident: ident.clone(), - param_index, - }, - ParsedGenericParam::Type(ParsedTypeParam { ref ident, .. }) - | ParsedGenericParam::SizeType(ParsedSizeTypeParam { - ref ident, .. - }) => { - parser - .errors - .error(ident, "type provided when a constant was expected"); - return Err(ParseFailed); - } - }, - )); - } - } - _ => {} - } - Ok(ParsedExpr::Other(Box::new(input.clone()))) - } -} - -#[derive(Copy, Clone, Debug)] -pub(crate) enum TypeDelimiter { - Group(syn::token::Group), - Paren(Paren), -} - -impl_fold! { - enum TypeDelimiter<> { - Group(syn::token::Group), - Paren(Paren), - } -} - -impl TypeDelimiter { - pub(crate) fn surround(self, tokens: &mut TokenStream, f: F) { - match self { - TypeDelimiter::Group(v) => v.surround(tokens, f), - TypeDelimiter::Paren(v) => v.surround(tokens, f), - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedTypeDelimited { - pub(crate) delim: TypeDelimiter, - pub(crate) elem: Box, -} - -impl_fold! { - struct ParsedTypeDelimited<> { - delim: TypeDelimiter, - elem: Box, - } -} - -impl From for Type { - fn from(value: ParsedTypeDelimited) -> Self { - let ParsedTypeDelimited { delim, elem } = value; - let elem = Box::new(elem.into()); - match delim { - TypeDelimiter::Group(group_token) => Type::Group(TypeGroup { group_token, elem }), - TypeDelimiter::Paren(paren_token) => Type::Paren(TypeParen { paren_token, elem }), - } - } -} - -impl ToTokens for ParsedTypeDelimited { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { delim, elem } = self; - delim.surround(tokens, |tokens| elem.to_tokens(tokens)); - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedTypeTuple { - pub(crate) paren_token: Paren, - pub(crate) elems: Punctuated, -} - -impl_fold! { - struct ParsedTypeTuple<> { - paren_token: Paren, - elems: Punctuated, - } -} - -impl From for Type { - fn from(value: ParsedTypeTuple) -> Self { - let ParsedTypeTuple { paren_token, elems } = value; - Type::Tuple(TypeTuple { - paren_token, - elems: Punctuated::from_iter(elems.into_pairs().map_pair_value(Into::into)), - }) - } -} - -impl ToTokens for ParsedTypeTuple { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { paren_token, elems } = self; - paren_token.surround(tokens, |tokens| { - elems.to_tokens(tokens); - if elems.len() == 1 && !elems.trailing_punct() { - // trailing comma needed to distinguish from just parenthesis - Token![,](paren_token.span.close()).to_tokens(tokens); - } - }) - } -} - -impl ParseTypes for ParsedTypeTuple { - fn parse_types(ty: &mut TypeTuple, parser: &mut TypesParser<'_>) -> Result { - Ok(Self { - paren_token: ty.paren_token, - elems: parser.parse(&mut ty.elems)?, - }) - } -} - -#[derive(Debug, Clone)] -pub(crate) enum ParsedGenericArgument { - Type(ParsedType), - Const(ParsedExpr), -} - -impl_fold! { - enum ParsedGenericArgument<> { - Type(ParsedType), - Const(ParsedExpr), - } -} - -impl ToTokens for ParsedGenericArgument { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - Self::Type(ty) => ty.to_tokens(tokens), - Self::Const(expr) => expr.to_tokens(tokens), - } - } -} - -impl ParseTypes for ParsedGenericArgument { - fn parse_types( - arg: &mut GenericArgument, - parser: &mut TypesParser<'_>, - ) -> Result { - match arg { - GenericArgument::Type(ty) => { - { - let mut ty = &*ty; - while let Type::Group(TypeGroup { elem, .. }) = ty { - ty = &**elem; - } - if let Type::Path(TypePath { qself: None, path }) = ty { - if let Some((param_index, ident)) = parser.get_named_param(path) { - match parser.generics.params[param_index] { - ParsedGenericParam::Type(_) | ParsedGenericParam::SizeType(_) => {} - ParsedGenericParam::Const(_) => { - return Ok(Self::Const(ParsedExpr::NamedParamConst( - ParsedExprNamedParamConst { - ident: ident.clone(), - param_index, - }, - ))); - } - } - } - } - } - Ok(Self::Type(parser.parse(ty)?)) - } - GenericArgument::Const(expr) => Ok(Self::Const(parser.parse(expr)?)), - _ => parse_failed!(parser, arg, "expected type or const generic argument"), - } - } -} - -impl From for GenericArgument { - fn from(value: ParsedGenericArgument) -> Self { - match value { - ParsedGenericArgument::Type(ty) => Self::Type(ty.into()), - ParsedGenericArgument::Const(expr) => Self::Const(expr.into()), - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedGenericArguments { - pub(crate) colon2_token: Option, - pub(crate) lt_token: Token![<], - pub(crate) args: Punctuated, - pub(crate) gt_token: Token![>], -} - -impl_fold! { - struct ParsedGenericArguments<> { - colon2_token: Option, - lt_token: Token![<], - args: Punctuated, - gt_token: Token![>], - } -} - -impl ToTokens for ParsedGenericArguments { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - colon2_token, - lt_token, - args, - gt_token, - } = self; - colon2_token.to_tokens(tokens); - lt_token.to_tokens(tokens); - args.to_tokens(tokens); - gt_token.to_tokens(tokens); - } -} - -impl ParseTypes for ParsedGenericArguments { - fn parse_types( - args: &mut AngleBracketedGenericArguments, - parser: &mut TypesParser<'_>, - ) -> Result { - let AngleBracketedGenericArguments { - colon2_token, - lt_token, - ref mut args, - gt_token, - } = *args; - Ok(Self { - colon2_token, - lt_token, - args: parser.parse(args)?, - gt_token, - }) - } -} - -impl From for AngleBracketedGenericArguments { - fn from(value: ParsedGenericArguments) -> Self { - let ParsedGenericArguments { - colon2_token, - lt_token, - args, - gt_token, - } = value; - AngleBracketedGenericArguments { - colon2_token, - lt_token, - args: Punctuated::from_iter(args.into_pairs().map_pair_value(Into::into)), - gt_token, - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedTypeNamed { - pub(crate) path: Path, - pub(crate) args: Option, -} - -impl_fold! { - struct ParsedTypeNamed<> { - path: Path, - args: Option, - } -} - -impl From for Type { - fn from(value: ParsedTypeNamed) -> Self { - let ParsedTypeNamed { path, args } = value; - Type::Path(TypePath { - qself: None, - path: Path { - leading_colon: path.leading_colon, - segments: { - let mut segments = path.segments.clone(); - if let Some(args) = args { - segments.last_mut().unwrap().arguments = - PathArguments::AngleBracketed(args.into()); - } - segments - }, - }, - }) - } -} - -impl ToTokens for ParsedTypeNamed { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { path, args } = self; - path.to_tokens(tokens); - args.to_tokens(tokens); - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedTypeNamedParamType { - pub(crate) ident: Ident, - pub(crate) param_index: usize, -} - -impl_fold! { - struct ParsedTypeNamedParamType<> { - ident: Ident, - param_index: usize, - } -} - -impl ToTokens for ParsedTypeNamedParamType { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - ident, - param_index: _, - } = self; - ident.to_tokens(tokens); - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedTypeNamedParamSizeType { - pub(crate) ident: Ident, - pub(crate) param_index: usize, -} - -impl_fold! { - struct ParsedTypeNamedParamSizeType<> { - ident: Ident, - param_index: usize, - } -} - -impl ToTokens for ParsedTypeNamedParamSizeType { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - ident, - param_index: _, - } = self; - ident.to_tokens(tokens); - } -} - -#[derive(Debug, Clone)] -pub(crate) enum ParsedTypeNamedParam { - Type(ParsedTypeNamedParamType), - SizeType(ParsedTypeNamedParamSizeType), -} - -impl_fold! { - enum ParsedTypeNamedParam<> { - Type(ParsedTypeNamedParamType), - SizeType(ParsedTypeNamedParamSizeType), - } -} - -impl ParsedTypeNamedParam { - pub(crate) fn into_ident(self) -> Ident { - match self { - Self::Type(v) => v.ident, - Self::SizeType(v) => v.ident, - } - } - #[allow(dead_code)] - pub(crate) fn ident(&self) -> &Ident { - match self { - Self::Type(v) => &v.ident, - Self::SizeType(v) => &v.ident, - } - } - #[allow(dead_code)] - pub(crate) fn param_index(&self) -> usize { - match self { - Self::Type(v) => v.param_index, - Self::SizeType(v) => v.param_index, - } - } -} - -impl From for Type { - fn from(value: ParsedTypeNamedParam) -> Self { - Type::Path(TypePath { - qself: None, - path: value.into_ident().into(), - }) - } -} - -impl ToTokens for ParsedTypeNamedParam { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - Self::Type(v) => v.to_tokens(tokens), - Self::SizeType(v) => v.to_tokens(tokens), - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedTypeConstUsize { - pub(crate) const_usize: known_items::ConstUsize, - pub(crate) lt_token: Token![<], - pub(crate) value: ParsedExpr, - pub(crate) gt_token: Token![>], -} - -impl_fold! { - struct ParsedTypeConstUsize<> { - const_usize: known_items::ConstUsize, - lt_token: Token![<], - value: ParsedExpr, - gt_token: Token![>], - } -} - -impl From for Path { - fn from(value: ParsedTypeConstUsize) -> Self { - let ParsedTypeConstUsize { - const_usize, - lt_token, - value, - gt_token, - } = value; - let path = const_usize.path; - let args = Punctuated::from_iter([GenericArgument::Const(value.into())]); - let args = AngleBracketedGenericArguments { - colon2_token: Some(Token![::](lt_token.span)), - lt_token, - args, - gt_token, - }; - let mut segments = path.segments.clone(); - segments.last_mut().unwrap().arguments = PathArguments::AngleBracketed(args); - Path { - leading_colon: path.leading_colon, - segments, - } - } -} - -impl From for Type { - fn from(value: ParsedTypeConstUsize) -> Self { - Type::Path(TypePath { - qself: None, - path: value.into(), - }) - } -} - -impl MakeHdlTypeExpr for ParsedTypeConstUsize { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - if let Some(named_param_const) = self.value.named_param_const() { - named_param_const.make_hdl_type_expr(context) - } else { - Expr::Path(ExprPath { - attrs: vec![], - qself: None, - path: self.clone().into(), - }) - } - } -} - -impl ToTokens for ParsedTypeConstUsize { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - const_usize, - lt_token, - value, - gt_token, - } = self; - const_usize.to_tokens(tokens); - lt_token.to_tokens(tokens); - value.to_tokens(tokens); - gt_token.to_tokens(tokens); - } -} - -impl ParsedTypeConstUsize { - fn try_from_named( - named: ParsedTypeNamed, - parser: &mut TypesParser<'_>, - ) -> Result, ParseFailed> { - let ParsedTypeNamed { path, args } = named; - let const_usize = match known_items::ConstUsize::parse_path(path) { - Ok(const_usize) => const_usize, - Err(path) => return Ok(Err(ParsedTypeNamed { path, args })), - }; - let Some(ParsedGenericArguments { - colon2_token: _, - lt_token, - args, - gt_token, - }) = args - else { - parser - .errors() - .error(const_usize, "ConstUsize type is missing generic arguments"); - return Err(ParseFailed); - }; - let args_len = args.len(); - let mut args = args.into_iter(); - let (Some(value), None) = (args.next(), args.next()) else { - parser.errors().error( - const_usize, - format_args!("ConstUsize type takes 1 generic argument, but got {args_len}"), - ); - return Err(ParseFailed); - }; - let ParsedGenericArgument::Const(value) = value else { - parser.errors().error(value, "expected a constant"); - return Err(ParseFailed); - }; - Ok(Ok(Self { - const_usize, - lt_token, - value, - gt_token, - })) - } -} - -macro_rules! make_parsed_type_or_const { - ( - @count_arg($min:ident, $max:ident) - #[type(default = |$type_arg_default_span:ident| $type_arg_default:expr)] - $type_arg:ident: $type_arg_ty:ty, - ) => { - let $max = $max + 1; - }; - ( - @count_arg($min:ident, $max:ident) - #[type] - $type_arg:ident: $type_arg_ty:ty, - ) => { - let $min = $min + 1; - let $max = $max + 1; - }; - ( - @default_fn - #[type(default = |$type_arg_default_span:ident| $type_arg_default:expr)] - $type_arg:ident: $type_arg_ty:ty, - ) => { - |$type_arg_default_span| $type_arg_default - }; - ( - @default_fn - #[type] - $type_arg:ident: $type_arg_ty:ty, - ) => { - |_| unreachable!() - }; - ( - @parse_arg($is_const:ident, $parser:ident, $span:expr) - #[type$((default = |$type_arg_default_span:ident| $type_arg_default:expr))?] - $type_arg:ident: $type_arg_ty:ty, - $(#[separator] - $separator:ident: $separator_ty:ty,)? - ) => { - $(let $separator;)? - let $type_arg = Box::new(if let Some($type_arg) = $type_arg { - let ($type_arg, _punct) = $type_arg.into_tuple(); - $($separator = _punct;)? - let ParsedGenericArgument::Type($type_arg) = $type_arg else { - $parser.errors().error($type_arg, "expected a type"); - return Err(ParseFailed); - }; - $type_arg - } else { - $($separator = None;)? - let default_fn = make_parsed_type_or_const! { - @default_fn - #[type$((default = |$type_arg_default_span| $type_arg_default))?] - $type_arg: $type_arg_ty, - }; - default_fn($span) - }); - $(let $separator = $separator.unwrap_or_else(|| { - let mut $separator = <$separator_ty>::default(); - $separator.span = $span; - $separator - });)? - }; - ( - @parse_arg($is_const:ident, $parser:ident, $span:expr) - #[const] - $const_arg:ident: $const_arg_ty:ty, - #[type$((default = |$type_arg_default_span:ident| $type_arg_default:expr))?] - $type_arg:ident: $type_arg_ty:ty, - $(#[separator] - $separator:ident: $separator_ty:ty,)? - ) => { - $(let $separator;)? - let ($type_arg, $const_arg) = if let Some($type_arg) = $type_arg { - let ($type_arg, _punct) = $type_arg.into_tuple(); - $($separator = _punct;)? - if $is_const { - let ParsedGenericArgument::Const($const_arg) = $type_arg else { - $parser.errors().error($type_arg, "expected a constant"); - return Err(ParseFailed); - }; - let $type_arg = Box::new(ParsedType::ConstUsize(ParsedTypeConstUsize { - const_usize: known_items::ConstUsize($span), - lt_token: Token![<]($span), - value: $const_arg.clone(), - gt_token: Token![>]($span), - })); - ($type_arg, Some(Box::new($const_arg))) - } else { - let ParsedGenericArgument::Type($type_arg) = $type_arg else { - $parser.errors().error($type_arg, "expected a type"); - return Err(ParseFailed); - }; - (Box::new($type_arg), None) - } - } else { - $($separator = None;)? - let default_fn = make_parsed_type_or_const! { - @default_fn - #[type$((default = |$type_arg_default_span| $type_arg_default))?] - $type_arg: $type_arg_ty, - }; - (Box::new(default_fn($span)), None) - }; - $(let $separator = $separator.unwrap_or_else(|| { - let mut $separator = <$separator_ty>::default(); - $separator.span = $span; - $separator - });)? - }; - ( - $(#[$struct_meta:meta])* - $vis:vis struct $struct_name:ident { - $const_name_field:ident: known_items::$const_name:ident, - $type_name_field:ident: known_items::$type_name:ident, - $lt_token:ident: $lt_token_ty:ty, - $( - $( - #[const] - $const_arg:ident: $const_arg_ty:ty, - )? - #[type$((default = |$type_arg_default_span:ident| $type_arg_default:expr))?] - $type_arg:ident: $type_arg_ty:ty, - $( - #[separator] - $separator:ident: $separator_ty:ty, - )? - )* - $gt_token:ident: $gt_token_ty:ty, - } - ) => { - $(#[$struct_meta])* - $vis struct $struct_name { - $vis $const_name_field: known_items::$const_name, - $vis $type_name_field: known_items::$type_name, - $vis $lt_token: $lt_token_ty, - $( - $($vis $const_arg: $const_arg_ty,)? - $vis $type_arg: $type_arg_ty, - $($vis $separator: $separator_ty,)? - )* - $vis $gt_token: $gt_token_ty, - } - - impl_fold! { - struct $struct_name<> { - $const_name_field: known_items::$const_name, - $type_name_field: known_items::$type_name, - $lt_token: $lt_token_ty, - $( - $($const_arg: $const_arg_ty,)? - $type_arg: $type_arg_ty, - $($separator: $separator_ty,)? - )* - $gt_token: $gt_token_ty, - } - } - - impl $struct_name { - $vis fn try_from_named( - named: ParsedTypeNamed, - parser: &mut TypesParser<'_>, - ) -> Result, ParseFailed> { - let ParsedTypeNamed { path, args } = named; - let $const_name_field; - let $type_name_field; - let parsed_path = known_items::$const_name::parse_path(path); - let parsed_path = parsed_path.map_err(known_items::$type_name::parse_path); - let is_const = match parsed_path { - Ok(const_path) => { - $type_name_field = known_items::$type_name(const_path.span); - $const_name_field = const_path; - true - } - Err(Ok(type_path)) => { - $const_name_field = known_items::$const_name(type_path.span); - $type_name_field = type_path; - false - } - Err(Err(path)) => return Ok(Err(ParsedTypeNamed { path, args })), - }; - let min_expected_args = 0; - let max_expected_args = 0; - $(make_parsed_type_or_const! { - @count_arg(min_expected_args, max_expected_args) - #[type$((default = |$type_arg_default_span| $type_arg_default))?] - $type_arg: $type_arg_ty, - })* - let ParsedGenericArguments { - colon2_token: _, - $lt_token, - args, - $gt_token, - } = if let Some(args) = args { - args - } else { - if min_expected_args > 0 { - parser - .errors() - .error($const_name_field, "type requires generic arguments"); - return Err(ParseFailed); - } - ParsedGenericArguments { - colon2_token: None, - lt_token: Token![<]($const_name_field.span), - args: Punctuated::new(), - gt_token: Token![>]($const_name_field.span), - } - }; - let args_len = args.len(); - if args_len < min_expected_args { - parser.errors().error( - $const_name_field, - format_args!("wrong number of generic arguments supplied: got {args_len}, expected at least {min_expected_args}"), - ); - return Err(ParseFailed); - } - if args_len > max_expected_args { - parser.errors().error( - &$const_name_field, - format_args!("wrong number of generic arguments supplied: got {args_len}, expected at most {max_expected_args}"), - ); - } - let mut args = args.into_pairs(); - $(let $type_arg = args.next();)* - $(make_parsed_type_or_const! { - @parse_arg(is_const, parser, $const_name_field.span) - $( - #[const] - $const_arg: $const_arg_ty, - )? - #[type$((default = |$type_arg_default_span| $type_arg_default))?] - $type_arg: $type_arg_ty, - $( - #[separator] - $separator: $separator_ty, - )? - })* - Ok(Ok(Self { - $const_name_field, - $type_name_field, - $lt_token, - $( - $($const_arg,)? - $type_arg, - $($separator,)? - )* - $gt_token, - })) - } - #[allow(dead_code)] - $vis fn is_const(&self) -> bool { - matches!(self, Self { - $($($const_arg: Some(_),)?)* - .. - }) - } - } - - impl From<$struct_name> for Type { - fn from(value: $struct_name) -> Type { - let $struct_name { - $const_name_field, - $type_name_field, - $lt_token, - $( - $($const_arg,)? - $type_arg, - $($separator,)? - )* - $gt_token, - } = value; - let (path, args) = if let ($($(Some($const_arg),)?)*) = ($($($const_arg,)?)*) { - let path = $const_name_field.path; - let mut args = Punctuated::new(); - $( - args.push(( - ($(|| GenericArgument::Const($const_arg.into()),)? - || GenericArgument::Type($type_arg.into()), - ).0)()); - $(args.push_punct($separator);)? - )* - (path, args) - } else { - let path = $type_name_field.path; - let mut args = Punctuated::new(); - $( - args.push(GenericArgument::Type($type_arg.into())); - $(args.push_punct($separator);)? - )* - (path, args) - }; - let args = AngleBracketedGenericArguments { - colon2_token: Some(Token![::]($lt_token.span)), - $lt_token, - args, - $gt_token, - }; - let mut segments = path.segments.clone(); - segments.last_mut().unwrap().arguments = PathArguments::AngleBracketed(args); - Type::Path(TypePath { - qself: None, - path: Path { - leading_colon: path.leading_colon, - segments, - }, - }) - } - } - - impl MakeHdlTypeExpr for $struct_name { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - let $struct_name { - $const_name_field, - $type_name_field: _, - $lt_token: _, - $( - $($const_arg: _,)? - $type_arg, - $($separator: _,)? - )* - $gt_token: _, - } = self; - let span = $const_name_field.span; - if context.is_const { - return parse_quote_spanned! {span=> - ::fayalite::ty::StaticType::TYPE - }; - } - let mut retval = Expr::Path(ExprPath { - attrs: vec![], - qself: None, - path: $const_name_field.path.clone(), - }); - $( - retval = Expr::Index(ExprIndex { - attrs: vec![], - expr: Box::new(retval), - bracket_token: Bracket(span), - index: Box::new($type_arg.make_hdl_type_expr(context)), - }); - )* - retval - } - } - - impl ToTokens for $struct_name { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - $const_name_field, - $type_name_field, - $lt_token, - $( - $($const_arg,)? - $type_arg, - $($separator,)? - )* - $gt_token, - } = self; - if let ($($(Some($const_arg),)?)*) = ($($($const_arg,)?)*) { - $const_name_field.to_tokens(tokens); - $lt_token.to_tokens(tokens); - $( - if (( - $(|| { - $const_arg.to_tokens(tokens); - false - },)? - || true, - ).0)() { - $type_arg.to_tokens(tokens); - } - $($separator.to_tokens(tokens);)? - )* - $gt_token.to_tokens(tokens); - } else { - $type_name_field.to_tokens(tokens); - $lt_token.to_tokens(tokens); - $( - $type_arg.to_tokens(tokens); - $($separator.to_tokens(tokens);)? - )* - $gt_token.to_tokens(tokens); - } - } - } - }; -} - -make_parsed_type_or_const! { - #[derive(Debug, Clone)] - pub(crate) struct ParsedTypeArray { - array: known_items::Array, - array_type: known_items::ArrayType, - lt_token: Token![<], - #[type(default = |span| ParsedType::CanonicalType(known_items::CanonicalType(span)))] - element: Box, - #[separator] - comma_token: Token![,], - #[const] - const_len: Option>, - #[type(default = |span| ParsedType::DynSize(known_items::DynSize(span)))] - type_len: Box, - gt_token: Token![>], - } -} - -make_parsed_type_or_const! { - #[derive(Debug, Clone)] - pub(crate) struct ParsedTypeUInt { - uint: known_items::UInt, - uint_type: known_items::UIntType, - lt_token: Token![<], - #[const] - const_width: Option>, - #[type(default = |span| ParsedType::DynSize(known_items::DynSize(span)))] - type_width: Box, - gt_token: Token![>], - } -} - -make_parsed_type_or_const! { - #[derive(Debug, Clone)] - pub(crate) struct ParsedTypeSInt { - uint: known_items::SInt, - uint_type: known_items::SIntType, - lt_token: Token![<], - #[const] - const_width: Option>, - #[type(default = |span| ParsedType::DynSize(known_items::DynSize(span)))] - type_width: Box, - gt_token: Token![>], - } -} - -#[derive(Debug, Clone)] -pub(crate) enum ParsedType { - Delimited(ParsedTypeDelimited), - Named(ParsedTypeNamed), - NamedParam(ParsedTypeNamedParam), - Tuple(ParsedTypeTuple), - ConstUsize(ParsedTypeConstUsize), - Array(ParsedTypeArray), - UInt(ParsedTypeUInt), - SInt(ParsedTypeSInt), - CanonicalType(known_items::CanonicalType), - DynSize(known_items::DynSize), -} - -impl_fold! { - enum ParsedType<> { - Delimited(ParsedTypeDelimited), - Named(ParsedTypeNamed), - NamedParam(ParsedTypeNamedParam), - Tuple(ParsedTypeTuple), - ConstUsize(ParsedTypeConstUsize), - Array(ParsedTypeArray), - UInt(ParsedTypeUInt), - SInt(ParsedTypeSInt), - CanonicalType(known_items::CanonicalType), - DynSize(known_items::DynSize), - } -} - -impl From for Type { - fn from(value: ParsedType) -> Self { - match value { - ParsedType::Delimited(v) => v.into(), - ParsedType::Named(v) => v.into(), - ParsedType::NamedParam(v) => v.into(), - ParsedType::Tuple(v) => v.into(), - ParsedType::ConstUsize(v) => v.into(), - ParsedType::Array(v) => v.into(), - ParsedType::UInt(v) => v.into(), - ParsedType::SInt(v) => v.into(), - ParsedType::CanonicalType(v) => v.into(), - ParsedType::DynSize(v) => v.into(), - } - } -} - -impl From for Type { - fn from(value: known_items::CanonicalType) -> Self { - Self::Path(TypePath { - qself: None, - path: value.path, - }) - } -} - -impl From for Type { - fn from(value: known_items::DynSize) -> Self { - Self::Path(TypePath { - qself: None, - path: value.path, - }) - } -} - -impl From> for Type { - fn from(value: MaybeParsed) -> Self { - match value { - MaybeParsed::Unrecognized(value) => value, - MaybeParsed::Parsed(value) => value.into(), - } - } -} - -impl From> for Type { - fn from(value: Box) -> Self { - (*value).into() - } -} - -impl ToTokens for ParsedType { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - ParsedType::Delimited(ty) => ty.to_tokens(tokens), - ParsedType::NamedParam(ty) => ty.to_tokens(tokens), - ParsedType::Named(ty) => ty.to_tokens(tokens), - ParsedType::Tuple(ty) => ty.to_tokens(tokens), - ParsedType::ConstUsize(ty) => ty.to_tokens(tokens), - ParsedType::Array(ty) => ty.to_tokens(tokens), - ParsedType::UInt(ty) => ty.to_tokens(tokens), - ParsedType::SInt(ty) => ty.to_tokens(tokens), - ParsedType::CanonicalType(ty) => ty.to_tokens(tokens), - ParsedType::DynSize(ty) => ty.to_tokens(tokens), - } - } -} - -impl ParsedType { - #[allow(dead_code)] - pub(crate) fn unwrap_delimiters(mut self) -> Self { - loop { - match self { - ParsedType::Delimited(ty) => self = *ty.elem, - _ => return self, - } - } - } - #[allow(dead_code)] - pub(crate) fn unwrap_delimiters_ref(mut self: &Self) -> &Self { - loop { - match self { - ParsedType::Delimited(ty) => self = &*ty.elem, - _ => return self, - } - } - } - #[allow(dead_code)] - pub(crate) fn unwrap_delimiters_mut(mut self: &mut Self) -> &mut Self { - loop { - match self { - ParsedType::Delimited(ty) => self = &mut *ty.elem, - _ => return self, - } - } - } -} - -impl ParseTypes for ParsedType { - fn parse_types(path: &mut Path, parser: &mut TypesParser<'_>) -> Result { - let Path { - leading_colon, - ref mut segments, - } = *path; - if segments.is_empty() { - parse_failed!(parser, path, "path must not be empty"); - } - let mut args = None; - let segments = Punctuated::from_iter(segments.pairs_mut().map_pair_value_mut(|segment| { - let PathSegment { ident, arguments } = segment; - if let Some(_) = args { - parser - .errors() - .error(&ident, "associated types/consts are not yet implemented"); - } - args = match arguments { - PathArguments::None => None, - PathArguments::AngleBracketed(args) => parser.parse(args).ok(), - PathArguments::Parenthesized(_) => { - parser - .errors() - .error(&segment, "function traits are not allowed"); - None - } - }; - PathSegment::from(segment.ident.clone()) - })); - let named = ParsedTypeNamed { - path: Path { - leading_colon, - segments, - }, - args, - }; - if let Some((param_index, ident)) = parser.get_named_param(&named.path) { - return Ok(Self::NamedParam( - match parser.generics().params[param_index] { - ParsedGenericParam::Type(_) => { - ParsedTypeNamedParam::Type(ParsedTypeNamedParamType { - ident: ident.clone(), - param_index, - }) - } - ParsedGenericParam::SizeType(_) => { - ParsedTypeNamedParam::SizeType(ParsedTypeNamedParamSizeType { - ident: ident.clone(), - param_index, - }) - } - ParsedGenericParam::Const(ParsedConstParam { ref ident, .. }) => { - parser - .errors - .error(ident, "constant provided when a type was expected"); - return Err(ParseFailed); - } - }, - )); - } - let named = match ParsedTypeArray::try_from_named(named, parser)? { - Ok(v) => return Ok(Self::Array(v)), - Err(named) => named, - }; - let named = match ParsedTypeConstUsize::try_from_named(named, parser)? { - Ok(v) => return Ok(Self::ConstUsize(v)), - Err(named) => named, - }; - let named = match ParsedTypeUInt::try_from_named(named, parser)? { - Ok(v) => return Ok(Self::UInt(v)), - Err(named) => named, - }; - let named = match ParsedTypeSInt::try_from_named(named, parser)? { - Ok(v) => return Ok(Self::SInt(v)), - Err(named) => named, - }; - let named = match known_items::CanonicalType::try_from_named(named, parser)? { - Ok(v) => return Ok(Self::CanonicalType(v)), - Err(named) => named, - }; - let named = match known_items::DynSize::try_from_named(named, parser)? { - Ok(v) => return Ok(Self::DynSize(v)), - Err(named) => named, - }; - Ok(Self::Named(named)) - } -} - -impl ParseTypes for ParsedType { - fn parse_types(ty: &mut TypePath, parser: &mut TypesParser<'_>) -> Result { - let TypePath { qself, path } = ty; - if let Some(_qself) = qself { - // TODO: implement - parse_failed!( - parser, - ty, - "associated types/consts are not yet implemented" - ); - } else { - parser.parse(path) - } - } -} - -impl ParseTypes for ParsedType { - fn parse_types(ty: &mut Type, parser: &mut TypesParser<'_>) -> Result { - Ok(match ty { - Type::Array(_) => parse_failed!( - parser, - ty, - "Rust array types are not allowed here, \ - use Array or ArrayType instead" - ), - Type::BareFn(_) => parse_failed!(parser, ty, "fn() types are not allowed here"), - Type::Group(TypeGroup { group_token, elem }) => Self::Delimited(ParsedTypeDelimited { - delim: TypeDelimiter::Group(*group_token), - elem: parser.parse(elem)?, - }), - Type::ImplTrait(_) => { - parse_failed!(parser, ty, "impl Trait types are not allowed here") - } - Type::Infer(_) => parse_failed!(parser, ty, "inferred types are not allowed here"), - Type::Macro(_) => parse_failed!(parser, ty, "macro types are not allowed here"), - Type::Never(_) => parse_failed!(parser, ty, "the never type is not allowed here"), - Type::Paren(TypeParen { paren_token, elem }) => Self::Delimited(ParsedTypeDelimited { - delim: TypeDelimiter::Paren(*paren_token), - elem: parser.parse(elem)?, - }), - Type::Path(ty) => parser.parse(ty)?, - Type::Ptr(_) => parse_failed!(parser, ty, "pointer types are not allowed here"), - Type::Reference(_) => parse_failed!(parser, ty, "reference types are not allowed here"), - Type::Slice(_) => parse_failed!(parser, ty, "slice types are not allowed here"), - Type::TraitObject(_) => { - parse_failed!(parser, ty, "dyn Trait types are not allowed here") - } - Type::Tuple(ty) => Self::Tuple(parser.parse(ty)?), - Type::Verbatim(_) => parse_failed!(parser, ty, "unknown type kind"), - _ => parse_failed!(parser, ty, "unknown type kind"), - }) - } -} - -#[derive(Debug, Clone)] -pub(crate) enum ParsedConstGenericType { - Usize(known_items::usize), -} - -impl_fold! { - enum ParsedConstGenericType<> { - Usize(known_items::usize), - } -} - -impl From for Type { - fn from(value: ParsedConstGenericType) -> Self { - match value { - ParsedConstGenericType::Usize(v) => parse_quote! { #v }, - } - } -} - -impl From> for Type { - fn from(value: MaybeParsed) -> Self { - match value { - MaybeParsed::Unrecognized(value) => value, - MaybeParsed::Parsed(value) => value.into(), - } - } -} - -impl From> for Type { - fn from(value: Box) -> Self { - (*value).into() - } -} - -impl ToTokens for ParsedConstGenericType { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - ParsedConstGenericType::Usize(ty) => ty.to_tokens(tokens), - } - } -} - -impl ParseTypes for ParsedConstGenericType { - fn parse_types(path: &mut Path, parser: &mut TypesParser<'_>) -> Result { - let Path { - leading_colon, - ref mut segments, - } = *path; - if segments.is_empty() { - parse_failed!(parser, path, "path must not be empty"); - } - let mut args = None; - let segments = Punctuated::from_iter(segments.pairs_mut().map_pair_value_mut(|segment| { - let PathSegment { ident, arguments } = segment; - if let Some(_) = args { - parser - .errors() - .error(&ident, "associated types/consts are not yet implemented"); - } - args = match arguments { - PathArguments::None => None, - PathArguments::AngleBracketed(args) => parser.parse(args).ok(), - PathArguments::Parenthesized(_) => { - parser - .errors() - .error(&segment, "function traits are not allowed"); - None - } - }; - PathSegment::from(segment.ident.clone()) - })); - let named = ParsedTypeNamed { - path: Path { - leading_colon, - segments, - }, - args, - }; - let named = match known_items::usize::try_from_named(named, parser)? { - Ok(v) => return Ok(Self::Usize(v)), - Err(named) => named, - }; - parser.errors.error( - named, - "const parameter types other than `usize` are not yet implemented", - ); - Err(ParseFailed) - } -} - -impl ParseTypes for ParsedConstGenericType { - fn parse_types(ty: &mut TypePath, parser: &mut TypesParser<'_>) -> Result { - let TypePath { qself, path } = ty; - if let Some(_qself) = qself { - parse_failed!( - parser, - ty, - "associated types/consts are not yet implemented" - ); - } else { - parser.parse(path) - } - } -} - -impl ParseTypes for ParsedConstGenericType { - fn parse_types(ty: &mut Type, parser: &mut TypesParser<'_>) -> Result { - Ok(match ty { - Type::Path(ty) => parser.parse(ty)?, - _ => parse_failed!(parser, ty, "unsupported const generic type"), - }) - } -} - -pub(crate) struct ParseFailed; - -impl fmt::Display for ParseFailed { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("unknown parse failure") - } -} - -pub(crate) struct TypesParser<'a> { - generics: &'a ParsedGenerics, - /// used when parsing generic parameter defaults so - /// earlier parameter defaults can't refer to later parameters - cur_param_index: Option, - errors: &'a mut Errors, -} - -impl<'a> TypesParser<'a> { - pub(crate) fn run_with_errors, I>( - generics: &ParsedGenerics, - input: &mut I, - errors: &mut Errors, - ) -> Result { - TypesParser { - generics, - cur_param_index: None, - errors, - } - .parse(input) - } - pub(crate) fn maybe_run, I, G>( - generics: MaybeParsed<&ParsedGenerics, G>, - mut input: I, - errors: &mut Errors, - ) -> MaybeParsed { - let MaybeParsed::Parsed(generics) = generics else { - return MaybeParsed::Unrecognized(input); - }; - match Self::run_with_errors(generics, &mut input, errors) { - Ok(v) => MaybeParsed::Parsed(v), - Err(ParseFailed {}) => MaybeParsed::Unrecognized(input), - } - } - pub(crate) fn generics(&self) -> &'a ParsedGenerics { - self.generics - } - pub(crate) fn errors(&mut self) -> &mut Errors { - self.errors - } - pub(crate) fn parse, I>(&mut self, input: &mut I) -> Result { - T::parse_types(input, self) - } - pub(crate) fn get_named_param<'b>(&mut self, path: &'b Path) -> Option<(usize, &'b Ident)> { - let ident = path.get_ident()?; - let param_index = *self.generics().param_name_to_index_map.get(ident)?; - if self - .cur_param_index - .is_some_and(|cur_param_index| param_index >= cur_param_index) - { - self.errors - .error(path, "cannot use forward declared identifier here"); - } - Some((param_index, ident)) - } -} - -pub(crate) trait ParseTypes: Sized { - fn parse_types(input: &mut I, parser: &mut TypesParser<'_>) -> Result; -} - -impl, I> ParseTypes> for Box { - fn parse_types(input: &mut Box, parser: &mut TypesParser<'_>) -> Result { - Ok(Box::new(parser.parse(&mut **input)?)) - } -} - -impl, I, P: Clone> ParseTypes> for Punctuated { - fn parse_types( - input: &mut Punctuated, - parser: &mut TypesParser<'_>, - ) -> Result { - let retval = Punctuated::from_iter( - input - .pairs_mut() - .filter_map_pair_value_mut(|input| parser.parse(input).ok()), - ); - Ok(retval) - } -} - -#[derive(Debug, Clone)] -pub(crate) enum UnparsedGenericParam { - Type { - attrs: Vec, - options: HdlAttr, - ident: Ident, - colon_token: Token![:], - bounds: ParsedBounds, - mask_type_bounds: ParsedTypeBounds, - }, - Const { - attrs: Vec, - options: HdlAttr, - const_token: Token![const], - ident: Ident, - colon_token: Token![:], - ty: ParsedConstGenericType, - bounds: Option, - }, -} - -pub(crate) mod known_items { - use proc_macro2::{Ident, Span, TokenStream}; - use quote::ToTokens; - use syn::{ - parse::{Parse, ParseStream}, - Path, PathArguments, PathSegment, Token, - }; - - macro_rules! impl_known_item_body { - ($known_item:ident) => { - #[derive(Clone, Debug)] - #[allow(dead_code, non_camel_case_types)] - pub(crate) struct $known_item { - pub(crate) path: Path, - pub(crate) span: Span, - } - - #[allow(non_snake_case, dead_code)] - pub(crate) fn $known_item(span: Span) -> $known_item { - let segments = $known_item::PATH_SEGMENTS.iter() - .copied() - .map(|seg| PathSegment::from(Ident::new(seg, span))) - .collect(); - $known_item { - path: Path { - leading_colon: Some(Token![::](span)), - segments, - }, - span, - } - } - - impl ToTokens for $known_item { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.path.to_tokens(tokens); - } - } - - impl $known_item { - pub(crate) fn parse_path(path: Path) -> Result { - if let Some(ident) = path.get_ident() { - if ident == stringify!($known_item) { - return Ok(Self { span: ident.span(), path }); - } - } - if path.segments.len() == Self::PATH_SEGMENTS.len() - && path - .segments - .iter() - .zip(Self::PATH_SEGMENTS) - .all(|(seg, expected)| { - matches!(seg.arguments, PathArguments::None) - && seg.ident == *expected - }) - { - Ok(Self { span: path.segments.last().unwrap().ident.span(), path }) - } else { - Err(path) - } - } - #[allow(dead_code)] - pub(crate) fn parse_path_with_arguments(mut path: Path) -> Result<(Self, PathArguments), Path> { - let Some(last_segment) = path.segments.last_mut() else { - return Err(path); - }; - let arguments = std::mem::replace(&mut last_segment.arguments, PathArguments::None); - match Self::parse_path(path) { - Ok(retval) => Ok((retval, arguments)), - Err(mut path) => { - path.segments.last_mut().unwrap().arguments = arguments; - Err(path) - } - } - } - } - - impl Parse for $known_item { - fn parse(input: ParseStream) -> syn::Result { - Self::parse_path(Path::parse_mod_style(input)?).map_err(|path| { - syn::Error::new_spanned( - path, - concat!("expected ", stringify!($known_item)), - ) - }) - } - } - - crate::fold::no_op_fold!($known_item); - - impl $known_item { - #[allow(dead_code)] - pub(crate) fn try_from_named( - named: super::ParsedTypeNamed, - parser: &mut super::TypesParser<'_>, - ) -> Result, super::ParseFailed> { - let super::ParsedTypeNamed { path, args } = named; - let path = match Self::parse_path(path) { - Ok(path) => path, - Err(path) => return Ok(Err(super::ParsedTypeNamed { path, args })), - }; - if let Some(args) = args.filter(|args| !args.args.is_empty()) { - parser.errors().error( - &path, - format_args!("wrong number of generic arguments supplied: got {}, expected at most 0", args.args.len()), - ); - } - Ok(Ok(path)) - } - } - }; - } - - macro_rules! impl_known_item { - ($([$(::$head:ident)*])? ::$next:ident $(::$tail:ident)+) => { - impl_known_item!([$($(::$head)*)? ::$next] $(::$tail)+); - }; - ([$(::$seg:ident)+] ::$known_item:ident) => { - impl_known_item_body!($known_item); - - impl $known_item { - pub(crate) const PATH_SEGMENTS: &'static [&'static str] = &[ - $(stringify!($seg),)+ - stringify!($known_item), - ]; - } - }; - } - - impl_known_item!(::fayalite::array::Array); - impl_known_item!(::fayalite::array::ArrayType); - impl_known_item!(::fayalite::bundle::BundleType); - impl_known_item!(::fayalite::enum_::EnumType); - impl_known_item!(::fayalite::int::DynSize); - impl_known_item!(::fayalite::int::IntType); - impl_known_item!(::fayalite::int::KnownSize); - impl_known_item!(::fayalite::int::SInt); - impl_known_item!(::fayalite::int::SIntType); - impl_known_item!(::fayalite::int::Size); - impl_known_item!(::fayalite::int::UInt); - impl_known_item!(::fayalite::int::UIntType); - impl_known_item!(::fayalite::ty::CanonicalType); - impl_known_item!(::fayalite::ty::StaticType); - impl_known_item!(::fayalite::ty::Type); - impl_known_item!(::fayalite::ty::Type::MaskType); - impl_known_item!(::fayalite::util::ConstUsize); - impl_known_item!(::fayalite::__std::primitive::usize); -} - -macro_rules! impl_bounds { - ( - #[struct = $struct_type:ident] - $vis:vis enum $enum_type:ident { - $( - $Variant:ident, - )* - } - ) => { - #[derive(Clone, Debug)] - $vis enum $enum_type { - $($Variant(known_items::$Variant),)* - } - - $(impl From for $enum_type { - fn from(v: known_items::$Variant) -> Self { - Self::$Variant(v) - } - })* - - impl ToTokens for $enum_type { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - $(Self::$Variant(v) => v.to_tokens(tokens),)* - } - } - } - - impl $enum_type { - $vis fn parse_path(path: Path) -> Result { - $(let path = match known_items::$Variant::parse_path(path) { - Ok(v) => return Ok(Self::$Variant(v)), - Err(path) => path, - };)* - Err(path) - } - } - - impl Parse for $enum_type { - fn parse(input: ParseStream) -> syn::Result { - Self::parse_path(Path::parse_mod_style(input)?).map_err(|path| { - syn::Error::new_spanned( - path, - format_args!("expected one of: {}", [$(stringify!($Variant)),*].join(", ")), - ) - }) - } - } - - #[derive(Clone, Debug, Default)] - #[allow(non_snake_case)] - $vis struct $struct_type { - $($vis $Variant: Option,)* - } - - impl ToTokens for $struct_type { - #[allow(unused_mut, unused_variables, unused_assignments)] - fn to_tokens(&self, tokens: &mut TokenStream) { - let mut separator = None; - $(if let Some(v) = &self.$Variant { - separator.to_tokens(tokens); - separator = Some(::default()); - v.to_tokens(tokens); - })* - } - } - - const _: () = { - #[derive(Clone, Debug)] - $vis struct Iter($vis $struct_type); - - impl IntoIterator for $struct_type { - type Item = $enum_type; - type IntoIter = Iter; - - fn into_iter(self) -> Self::IntoIter { - Iter(self) - } - } - - impl Iterator for Iter { - type Item = $enum_type; - - - fn next(&mut self) -> Option { - $( - if let Some(value) = self.0.$Variant.take() { - return Some($enum_type::$Variant(value)); - } - )* - None - } - - #[allow(unused_mut, unused_variables)] - fn fold B>(mut self, mut init: B, mut f: F) -> B { - $( - if let Some(value) = self.0.$Variant.take() { - init = f(init, $enum_type::$Variant(value)); - } - )* - init - } - } - }; - - impl Extend<$enum_type> for $struct_type { - fn extend>(&mut self, iter: T) { - iter.into_iter().for_each(|v| match v { - $($enum_type::$Variant(v) => { - self.$Variant = Some(v); - })* - }); - } - } - - impl FromIterator<$enum_type> for $struct_type { - fn from_iter>(iter: T) -> Self { - let mut retval = Self::default(); - retval.extend(iter); - retval - } - } - - impl Extend<$struct_type> for $struct_type { - fn extend>(&mut self, iter: T) { - iter.into_iter().for_each(|v| { - $(if let Some(v) = v.$Variant { - self.$Variant = Some(v); - })* - }); - } - } - - impl FromIterator<$struct_type> for $struct_type { - fn from_iter>(iter: T) -> Self { - let mut retval = Self::default(); - retval.extend(iter); - retval - } - } - - impl Parse for $struct_type { - fn parse(input: ParseStream) -> syn::Result { - let mut retval = Self::default(); - while !input.is_empty() { - retval.extend([input.parse::<$enum_type>()?]); - if input.is_empty() { - break; - } - input.parse::()?; - } - Ok(retval) - } - } - - impl $struct_type { - #[allow(dead_code)] - $vis fn add_implied_bounds(&mut self) { - let orig_bounds = self.clone(); - self.extend( - self.clone() - .into_iter() - .map($enum_type::implied_bounds), - ); - self.extend([orig_bounds]); // keep spans of explicitly provided bounds - } - } - }; -} - -impl_bounds! { - #[struct = ParsedBounds] - pub(crate) enum ParsedBound { - BundleType, - EnumType, - IntType, - KnownSize, - Size, - StaticType, - Type, - } -} - -impl_bounds! { - #[struct = ParsedTypeBounds] - pub(crate) enum ParsedTypeBound { - BundleType, - EnumType, - IntType, - StaticType, - Type, - } -} - -impl From for ParsedBound { - fn from(value: ParsedTypeBound) -> Self { - match value { - ParsedTypeBound::BundleType(v) => ParsedBound::BundleType(v), - ParsedTypeBound::EnumType(v) => ParsedBound::EnumType(v), - ParsedTypeBound::IntType(v) => ParsedBound::IntType(v), - ParsedTypeBound::StaticType(v) => ParsedBound::StaticType(v), - ParsedTypeBound::Type(v) => ParsedBound::Type(v), - } - } -} - -impl From for ParsedBounds { - fn from(value: ParsedTypeBounds) -> Self { - let ParsedTypeBounds { - BundleType, - EnumType, - IntType, - StaticType, - Type, - } = value; - Self { - BundleType, - EnumType, - IntType, - KnownSize: None, - Size: None, - StaticType, - Type, - } - } -} - -impl ParsedTypeBound { - fn implied_bounds(self) -> ParsedTypeBounds { - let span = self.span(); - match self { - Self::BundleType(v) => ParsedTypeBounds::from_iter([ - ParsedTypeBound::from(v), - ParsedTypeBound::Type(known_items::Type(span)), - ]), - Self::EnumType(v) => ParsedTypeBounds::from_iter([ - ParsedTypeBound::from(v), - ParsedTypeBound::Type(known_items::Type(span)), - ]), - Self::IntType(v) => ParsedTypeBounds::from_iter([ - ParsedTypeBound::from(v), - ParsedTypeBound::Type(known_items::Type(span)), - ]), - Self::StaticType(v) => ParsedTypeBounds::from_iter([ - ParsedTypeBound::from(v), - ParsedTypeBound::Type(known_items::Type(span)), - ]), - Self::Type(v) => ParsedTypeBounds::from_iter([ParsedTypeBound::from(v)]), - } - } -} - -impl_bounds! { - #[struct = ParsedSizeTypeBounds] - pub(crate) enum ParsedSizeTypeBound { - KnownSize, - Size, - } -} - -impl From for ParsedBound { - fn from(value: ParsedSizeTypeBound) -> Self { - match value { - ParsedSizeTypeBound::KnownSize(v) => ParsedBound::KnownSize(v), - ParsedSizeTypeBound::Size(v) => ParsedBound::Size(v), - } - } -} - -impl From for ParsedBounds { - fn from(value: ParsedSizeTypeBounds) -> Self { - let ParsedSizeTypeBounds { KnownSize, Size } = value; - Self { - BundleType: None, - EnumType: None, - IntType: None, - KnownSize, - Size, - StaticType: None, - Type: None, - } - } -} - -impl ParsedSizeTypeBound { - fn implied_bounds(self) -> ParsedSizeTypeBounds { - let span = self.span(); - match self { - Self::KnownSize(v) => ParsedSizeTypeBounds::from_iter([ - ParsedSizeTypeBound::from(v), - ParsedSizeTypeBound::Size(known_items::Size(span)), - ]), - Self::Size(v) => ParsedSizeTypeBounds::from_iter([ParsedSizeTypeBound::from(v)]), - } - } -} - -#[derive(Clone, Debug)] -pub(crate) enum ParsedBoundsCategory { - Type(ParsedTypeBounds), - SizeType(ParsedSizeTypeBounds), -} - -impl ParsedBounds { - fn categorize(self, errors: &mut Errors, span: Span) -> ParsedBoundsCategory { - let mut type_bounds = None; - let mut size_type_bounds = None; - self.into_iter().for_each(|bound| match bound.categorize() { - ParsedBoundCategory::Type(bound) => { - type_bounds - .get_or_insert_with(ParsedTypeBounds::default) - .extend([bound]); - } - ParsedBoundCategory::SizeType(bound) => { - size_type_bounds - .get_or_insert_with(ParsedSizeTypeBounds::default) - .extend([bound]); - } - }); - match (type_bounds, size_type_bounds) { - (None, None) => ParsedBoundsCategory::Type(ParsedTypeBounds { - Type: Some(known_items::Type(span)), - ..Default::default() - }), - (None, Some(bounds)) => ParsedBoundsCategory::SizeType(bounds), - (Some(bounds), None) => ParsedBoundsCategory::Type(bounds), - (Some(type_bounds), Some(size_type_bounds)) => { - errors.error( - size_type_bounds - .Size - .unwrap_or_else(|| known_items::Size(span)), - "conflicting bounds: can't use `Size` bounds with `Type` bounds", - ); - ParsedBoundsCategory::Type(type_bounds) - } - } - } -} - -#[derive(Clone, Debug)] -pub(crate) enum ParsedBoundCategory { - Type(ParsedTypeBound), - SizeType(ParsedSizeTypeBound), -} - -impl ParsedBound { - fn categorize(self) -> ParsedBoundCategory { - match self { - Self::BundleType(v) => ParsedBoundCategory::Type(ParsedTypeBound::BundleType(v)), - Self::EnumType(v) => ParsedBoundCategory::Type(ParsedTypeBound::EnumType(v)), - Self::IntType(v) => ParsedBoundCategory::Type(ParsedTypeBound::IntType(v)), - Self::KnownSize(v) => ParsedBoundCategory::SizeType(ParsedSizeTypeBound::KnownSize(v)), - Self::Size(v) => ParsedBoundCategory::SizeType(ParsedSizeTypeBound::Size(v)), - Self::StaticType(v) => ParsedBoundCategory::Type(ParsedTypeBound::StaticType(v)), - Self::Type(v) => ParsedBoundCategory::Type(ParsedTypeBound::Type(v)), - } - } - fn implied_bounds(self) -> ParsedBounds { - match self.categorize() { - ParsedBoundCategory::Type(v) => v.implied_bounds().into(), - ParsedBoundCategory::SizeType(v) => v.implied_bounds().into(), - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedTypeParam { - pub(crate) attrs: Vec, - pub(crate) options: HdlAttr, - pub(crate) ident: Ident, - pub(crate) colon_token: Token![:], - pub(crate) bounds: ParsedTypeBounds, - pub(crate) default: Option<(Token![=], ParsedType)>, -} - -impl ToTokens for ParsedTypeParam { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - attrs, - options, - ident, - colon_token, - bounds, - default, - } = self; - let TypeParamOptions {} = options.body; - for attr in attrs { - attr.to_tokens(tokens); - } - ident.to_tokens(tokens); - colon_token.to_tokens(tokens); - bounds.to_tokens(tokens); - if let Some((eq, ty)) = default { - eq.to_tokens(tokens); - ty.to_tokens(tokens); - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedSizeTypeParam { - pub(crate) attrs: Vec, - pub(crate) options: HdlAttr, - pub(crate) ident: Ident, - pub(crate) colon_token: Token![:], - pub(crate) bounds: ParsedSizeTypeBounds, - pub(crate) default: Option<(Token![=], ParsedType)>, -} - -impl ToTokens for ParsedSizeTypeParam { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - attrs, - options, - ident, - colon_token, - bounds, - default, - } = self; - let TypeParamOptions {} = options.body; - for attr in attrs { - attr.to_tokens(tokens); - } - ident.to_tokens(tokens); - colon_token.to_tokens(tokens); - bounds.to_tokens(tokens); - if let Some((eq, ty)) = default { - eq.to_tokens(tokens); - ty.to_tokens(tokens); - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedConstParamWhereBounds { - pub(crate) const_usize: known_items::ConstUsize, - pub(crate) lt_token: Token![<], - pub(crate) ident: Ident, - pub(crate) gt_token: Token![>], - pub(crate) colon_token: Token![:], - pub(crate) bounds: ParsedSizeTypeBounds, -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedConstParam { - pub(crate) attrs: Vec, - pub(crate) options: HdlAttr, - pub(crate) const_token: Token![const], - pub(crate) ident: Ident, - pub(crate) colon_token: Token![:], - pub(crate) ty: ParsedConstGenericType, - pub(crate) bounds: ParsedConstParamWhereBounds, -} - -impl ToTokens for ParsedConstParam { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - attrs, - options, - const_token, - ident, - colon_token, - ty, - bounds: _, - } = self; - let ConstParamOptions {} = options.body; - for attr in attrs { - attr.to_tokens(tokens); - } - const_token.to_tokens(tokens); - ident.to_tokens(tokens); - colon_token.to_tokens(tokens); - ty.to_tokens(tokens); - } -} - -#[derive(Debug, Clone)] -pub(crate) enum ParsedGenericParam { - Type(ParsedTypeParam), - SizeType(ParsedSizeTypeParam), - Const(ParsedConstParam), -} - -impl ToTokens for ParsedGenericParam { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - ParsedGenericParam::Type(v) => v.to_tokens(tokens), - ParsedGenericParam::SizeType(v) => v.to_tokens(tokens), - ParsedGenericParam::Const(v) => v.to_tokens(tokens), - } - } -} - -impl ParsedGenericParam { - pub(crate) fn ident(&self) -> &Ident { - match self { - ParsedGenericParam::Type(v) => &v.ident, - ParsedGenericParam::SizeType(v) => &v.ident, - ParsedGenericParam::Const(v) => &v.ident, - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedGenerics { - pub(crate) lt_token: Option, - pub(crate) params: Punctuated, - pub(crate) gt_token: Option]>, - pub(crate) param_name_to_index_map: HashMap, -} - -impl ParsedGenerics { - pub(crate) fn for_static_type(mut self) -> ParsedGenerics { - for param in self.params.iter_mut() { - match param { - ParsedGenericParam::Type(ParsedTypeParam { ident, bounds, .. }) => { - bounds - .StaticType - .get_or_insert_with(|| known_items::StaticType(ident.span())); - } - ParsedGenericParam::SizeType(ParsedSizeTypeParam { ident, bounds, .. }) => { - bounds - .KnownSize - .get_or_insert_with(|| known_items::KnownSize(ident.span())); - } - ParsedGenericParam::Const(ParsedConstParam { ident, bounds, .. }) => { - bounds - .bounds - .KnownSize - .get_or_insert_with(|| known_items::KnownSize(ident.span())); - } - } - } - self - } - pub(crate) fn to_generics(&self, param_count: Option) -> Generics { - let param_count = param_count.unwrap_or(self.params.len()); - if param_count == 0 || self.params.is_empty() { - return Generics::default(); - } - let where_clause = ParsedGenericsWhereClause { - generics: self, - param_count, - } - .to_token_stream(); - let where_clause = if where_clause.is_empty() { - None - } else { - Some(parse_quote! { #where_clause }) - }; - Generics { - lt_token: self.lt_token, - params: self - .params - .pairs() - .take(param_count) - .map_pair_value_ref(|param| parse_quote! { #param }) - .collect(), - gt_token: self.gt_token, - where_clause, - } - } - pub(crate) fn generics_accumulation_type( - &self, - vis: Visibility, - ident: Ident, - param_count: usize, - ) -> ItemStruct { - let span = ident.span(); - ItemStruct { - attrs: vec![ - common_derives(span), - parse_quote_spanned! {span=> - #[allow(non_camel_case_types)] - }, - ], - vis, - struct_token: Token![struct](span), - ident: format_ident!("__{}__GenericsAccumulation{}", ident, param_count), - generics: self.to_generics(Some(param_count)), - fields: if self.params.is_empty() || param_count == 0 { - Fields::Unnamed(parse_quote_spanned! {span=> - (()) - }) - } else { - FieldsUnnamed { - paren_token: Paren(span), - unnamed: self - .params - .pairs() - .take(param_count) - .map_pair_value_ref(|param| match param { - ParsedGenericParam::Type(param) => { - let ident = ¶m.ident; - parse_quote! { #ident } - } - ParsedGenericParam::SizeType(param) => { - let ident = ¶m.ident; - parse_quote_spanned! {span=> - <#ident as ::fayalite::int::Size>::SizeType - } - } - ParsedGenericParam::Const(param) => { - let ident = ¶m.ident; - parse_quote_spanned! {span=> - <::fayalite::util::ConstUsize<#ident> - as ::fayalite::int::Size>::SizeType - } - } - }) - .collect(), - } - .into() - }, - semi_token: Some(Token![;](span)), - } - } - pub(crate) fn make_runtime_generics( - &self, - tokens: &mut TokenStream, - vis: &Visibility, - ident: &Ident, - target: &Path, - mut target_expr: impl FnMut(&MakeHdlTypeExprContext) -> Expr, - ) { - if self.params.is_empty() { - let target_expr = target_expr(&MakeHdlTypeExprContext { - named_param_values: vec![], - is_const: true, - }); - quote_spanned! {ident.span()=> - #[allow(non_upper_case_globals, dead_code)] - #vis const #ident: #target = #target_expr; - } - .to_tokens(tokens); - return; - } - let generics_accumulation_types = - Vec::from_iter((0..self.params.len()).map(|param_count| { - self.generics_accumulation_type(vis.clone(), ident.clone(), param_count) - })); - generics_accumulation_types[0].to_tokens(tokens); - let generics_accumulation_ident_0 = &generics_accumulation_types[0].ident; - quote_spanned! {ident.span()=> - #[allow(non_upper_case_globals, dead_code)] - #vis const #ident: #generics_accumulation_ident_0 = #generics_accumulation_ident_0(()); - } - .to_tokens(tokens); - let mut wrapped_in_const = WrappedInConst::new(tokens, ident.span()); - let tokens = wrapped_in_const.inner(); - for i in &generics_accumulation_types[1..] { - i.to_tokens(tokens) - } - let final_generics = Generics::from(self); - let self_members: Vec = (0..self.params.len()) - .map(|index| { - let mut member = Index::from(index); - member.span = ident.span(); - parse_quote_spanned! {ident.span()=> - self.#member - } - }) - .collect(); - for (param_count, (generics_accumulation_type, next_param)) in generics_accumulation_types - .iter() - .zip(&self.params) - .enumerate() - { - let cur_generics = &generics_accumulation_type.generics; - let cur_target = &generics_accumulation_type.ident; - let next_param_count = param_count + 1; - let is_last = next_param_count == self.params.len(); - let next_target = if is_last { - target.clone() - } else { - generics_accumulation_types[next_param_count] - .ident - .clone() - .into() - }; - let make_next_target_args = |next_arg: Option| { - let generics = if is_last { - &final_generics - } else { - &generics_accumulation_types[next_param_count].generics - }; - let type_generics = generics.split_for_impl().1; - let turbofish = type_generics.as_turbofish(); - let mut retval: AngleBracketedGenericArguments = parse_quote! { #turbofish }; - if let Some(next_arg) = next_arg { - *retval.args.last_mut().unwrap() = next_arg; - } - retval - }; - let (cur_impl_generics, cur_type_generics, cur_where_clause) = - cur_generics.split_for_impl(); - match next_param { - ParsedGenericParam::Type(ParsedTypeParam { - ident: param_ident, - default, - .. - }) => { - let next_generics = if is_last { - &final_generics - } else { - &generics_accumulation_types[next_param_count].generics - }; - let (_next_impl_generics, next_type_generics, _next_where_clause) = - next_generics.split_for_impl(); - let next_turbofish = next_type_generics.as_turbofish(); - let mut param: Expr = parse_quote_spanned! {ident.span()=> - __param - }; - let mut generics = next_generics.clone(); - let mut index_type = param_ident.clone(); - if let Some((_, default)) = default { - index_type = format_ident!("__Param", span = ident.span()); - generics.params.push(parse_quote! { #index_type }); - generics.make_where_clause().predicates.push(parse_quote_spanned! {ident.span()=> - #index_type: ::fayalite::ty::TypeOrDefault<#default, Type = #param_ident> - }); - let default_expr = default.make_hdl_type_expr(&MakeHdlTypeExprContext { - named_param_values: self_members[..param_count].to_vec(), - is_const: false, - }); - param = parse_quote_spanned! {ident.span()=> - ::fayalite::ty::TypeOrDefault::get(__param, || #default_expr) - }; - let context = MakeHdlTypeExprContext { - named_param_values: self_members[..param_count] - .iter() - .cloned() - .chain([default_expr]) - .collect(), - is_const: false, - }; - let output_expr = { - let next_turbofish = next_type_generics.as_turbofish(); - if is_last { - target_expr(&context) - } else { - let args = &context.named_param_values[..next_param_count]; - parse_quote_spanned! {ident.span()=> - #next_target #next_turbofish(#(#args),*) - } - } - }; - let next_target_args = make_next_target_args(Some(GenericArgument::Type( - default.clone().into(), - ))); - quote_spanned! {ident.span()=> - impl #cur_impl_generics ::fayalite::ty::FillInDefaultedGenerics - for #cur_target #cur_type_generics - #cur_where_clause - { - type Type = #next_target #next_target_args; - fn fill_in_defaulted_generics( - self, - ) -> ::Type { - #output_expr - } - } - } - .to_tokens(tokens); - } - let (impl_generics, _type_generics, where_clause) = generics.split_for_impl(); - let context = MakeHdlTypeExprContext { - named_param_values: self_members[..param_count] - .iter() - .cloned() - .chain([param]) - .collect(), - is_const: false, - }; - let output_expr = if is_last { - target_expr(&context) - } else { - let args = &context.named_param_values[..next_param_count]; - parse_quote_spanned! {ident.span()=> - #next_target #next_turbofish(#(#args),*) - } - }; - quote_spanned! {ident.span()=> - #[allow(non_upper_case_globals)] - #[automatically_derived] - impl #impl_generics ::fayalite::__std::ops::Index<#index_type> - for #cur_target #cur_type_generics - #where_clause - { - type Output = #next_target #next_type_generics; - - fn index(&self, __param: #index_type) -> &Self::Output { - ::fayalite::intern::Interned::<_>::into_inner( - ::fayalite::intern::Intern::intern_sized(#output_expr), - ) - } - } - } - .to_tokens(tokens); - } - ParsedGenericParam::SizeType(ParsedSizeTypeParam { - ident: param_ident, - bounds, - default, - .. - }) => { - { - let context = MakeHdlTypeExprContext { - named_param_values: self_members[..param_count] - .iter() - .cloned() - .chain([parse_quote_spanned! {ident.span()=> - __param - }]) - .collect(), - is_const: false, - }; - let next_target_args = - make_next_target_args(Some(parse_quote_spanned! {ident.span()=> - <#param_ident as ::fayalite::int::SizeType>::Size - })); - let output_expr = if is_last { - target_expr(&context) - } else { - let args = &context.named_param_values[..next_param_count]; - parse_quote_spanned! {ident.span()=> - #next_target #next_target_args(#(#args),*) - } - }; - let mut next_generics = cur_generics.clone(); - next_generics - .params - .push(parse_quote_spanned! {ident.span()=> - #param_ident: ::fayalite::int::SizeType - }); - next_generics.make_where_clause().predicates.push( - parse_quote_spanned! {ident.span()=> - <#param_ident as ::fayalite::int::SizeType>::Size: #bounds - }, - ); - let (next_impl_generics, _next_type_generics, next_where_clause) = - next_generics.split_for_impl(); - quote_spanned! {ident.span()=> - #[allow(non_upper_case_globals)] - #[automatically_derived] - impl #next_impl_generics ::fayalite::__std::ops::Index<#param_ident> - for #cur_target #cur_type_generics - #next_where_clause - { - type Output = #next_target #next_target_args; - - fn index(&self, __param: #param_ident) -> &Self::Output { - ::fayalite::intern::Interned::<_>::into_inner( - ::fayalite::intern::Intern::intern_sized(#output_expr), - ) - } - } - } - .to_tokens(tokens); - } - if let Some((_, default)) = default { - let _ = default; - todo!(); - } - } - ParsedGenericParam::Const(ParsedConstParam { - attrs: _, - options: _, - const_token, - ident: param_ident, - colon_token, - ty: ParsedConstGenericType::Usize(ty), - bounds: ParsedConstParamWhereBounds { bounds, .. }, - }) => { - let context = MakeHdlTypeExprContext { - named_param_values: self_members[..param_count] - .iter() - .cloned() - .chain([parse_quote_spanned! {ident.span()=> - __param - }]) - .collect(), - is_const: false, - }; - let next_target_args = - make_next_target_args(Some(parse_quote! { #param_ident })); - let output_expr = if is_last { - target_expr(&context) - } else { - let args = &context.named_param_values[..next_param_count]; - parse_quote_spanned! {ident.span()=> - #next_target #next_target_args(#(#args),*) - } - }; - let mut next_generics = cur_generics.clone(); - next_generics - .params - .push(parse_quote! { #const_token #param_ident #colon_token #ty }); - next_generics - .params - .push(parse_quote_spanned! {ident.span()=> - __Param: ::fayalite::int::SizeType< - Size = ::fayalite::util::ConstUsize<#param_ident>, - > - }); - next_generics.make_where_clause().predicates.push( - parse_quote_spanned! {ident.span()=> - ::fayalite::util::ConstUsize<#param_ident>: ::fayalite::int::Size + #bounds - }, - ); - let (next_impl_generics, _next_type_generics, next_where_clause) = - next_generics.split_for_impl(); - quote_spanned! {ident.span()=> - #[allow(non_upper_case_globals)] - #[automatically_derived] - impl #next_impl_generics ::fayalite::__std::ops::Index<__Param> - for #cur_target #cur_type_generics - #next_where_clause - { - type Output = #next_target #next_target_args; - - fn index(&self, __param: __Param) -> &Self::Output { - ::fayalite::intern::Interned::<_>::into_inner( - ::fayalite::intern::Intern::intern_sized(#output_expr), - ) - } - } - } - .to_tokens(tokens); - } - }; - } - } - pub(crate) fn parse<'a>(generics: &'a mut Generics) -> syn::Result { - let Generics { - lt_token, - params: input_params, - gt_token, - where_clause, - } = generics; - let mut errors = Errors::new(); - let mut predicates: Vec = Vec::with_capacity(input_params.len()); - struct LateParsedParam<'a> { - default: Option<(Token![=], &'a mut Type)>, - const_param_type: Option<&'a mut Type>, - } - let mut late_parsed_params: Vec> = - Vec::with_capacity(input_params.len()); - let mut unparsed_params: Punctuated = Punctuated::new(); - for input_param in input_params.pairs_mut() { - let (input_param, punct) = input_param.into_tuple(); - let (unparsed_param, late_parsed_param) = match input_param { - GenericParam::Lifetime(param) => { - errors.unwrap_or_default(HdlAttr::::parse_and_take_attr( - &mut param.attrs, - )); - errors.error(param, "lifetime generics are not supported by #[hdl]"); - continue; - } - GenericParam::Type(TypeParam { - attrs, - ident, - colon_token, - bounds, - eq_token, - default, - }) => { - let span = ident.span(); - let options = errors - .unwrap_or_default(HdlAttr::::parse_and_take_attr(attrs)) - .unwrap_or_default(); - let colon_token = colon_token.unwrap_or_else(|| Token![:](span)); - if !bounds.is_empty() { - predicates.push(WherePredicate::Type(PredicateType { - lifetimes: None, - bounded_ty: parse_quote! { #ident }, - colon_token, - bounds: bounds.clone(), - })); - } - ( - UnparsedGenericParam::Type { - attrs: attrs.clone(), - options, - ident: ident.clone(), - colon_token, - bounds: ParsedBounds::default(), - mask_type_bounds: ParsedTypeBounds::default(), - }, - LateParsedParam { - default: default - .as_mut() - .map(|v| (eq_token.unwrap_or_else(|| Token![=](span)), v)), - const_param_type: None, - }, - ) - } - GenericParam::Const(ConstParam { - attrs, - const_token, - ident, - colon_token, - ty, - eq_token, - default, - }) => { - let options = errors - .unwrap_or_default(HdlAttr::::parse_and_take_attr(attrs)) - .unwrap_or_default(); - if let Some(default) = default { - let _ = eq_token; - errors.error( - default, - "const generics' default values are not yet implemented", - ); - } - ( - UnparsedGenericParam::Const { - attrs: attrs.clone(), - options, - const_token: *const_token, - ident: ident.clone(), - colon_token: *colon_token, - ty: ParsedConstGenericType::Usize(known_items::usize(ident.span())), - bounds: None, - }, - LateParsedParam { - default: None, - const_param_type: Some(ty), - }, - ) - } - }; - late_parsed_params.push(late_parsed_param); - unparsed_params.extend([Pair::new(unparsed_param, punct.cloned())]); - } - let param_name_to_index_map: HashMap = unparsed_params - .iter() - .enumerate() - .map(|(index, param)| { - let (UnparsedGenericParam::Type { ident, .. } - | UnparsedGenericParam::Const { ident, .. }) = param; - (ident.clone(), index) - }) - .collect(); - if let Some(where_clause) = where_clause { - predicates.extend(where_clause.predicates.iter().cloned()); - } - for predicate in predicates { - let WherePredicate::Type(PredicateType { - lifetimes: None, - bounded_ty: - Type::Path(TypePath { - qself, - path: bounded_ty, - }), - colon_token, - bounds: unparsed_bounds, - }) = predicate - else { - errors.error(predicate, "unsupported where predicate kind"); - continue; - }; - if let Some(qself) = &qself { - if let QSelf { - lt_token: _, - ty: base_ty, - position: 3, - as_token: Some(_), - gt_token: _, - } = qself - { - if bounded_ty.segments.len() == 4 && unparsed_bounds.len() == 1 { - if let ( - Ok(_), - Type::Path(TypePath { - qself: None, - path: base_ty, - }), - ) = ( - known_items::MaskType::parse_path(bounded_ty.clone()), - &**base_ty, - ) { - let Some(&index) = base_ty - .get_ident() - .and_then(|base_ty| param_name_to_index_map.get(base_ty)) - else { - errors.error( - TypePath { - qself: Some(qself.clone()), - path: bounded_ty, - }, - "unsupported where predicate kind", - ); - continue; - }; - let parsed_bounds = match &mut unparsed_params[index] { - UnparsedGenericParam::Type { - mask_type_bounds, .. - } => mask_type_bounds, - UnparsedGenericParam::Const { ident, .. } => { - errors.error( - bounded_ty, - format_args!( - "expected type, found const parameter `{ident}`" - ), - ); - continue; - } - }; - parsed_bounds.extend(errors.ok(syn::parse2::( - unparsed_bounds.to_token_stream(), - ))); - continue; - } - } - } - errors.error( - TypePath { - qself: Some(qself.clone()), - path: bounded_ty, - }, - "unsupported where predicate kind", - ); - continue; - } - if let Ok(( - const_usize, - PathArguments::AngleBracketed(AngleBracketedGenericArguments { - colon2_token: _, - lt_token, - args, - gt_token, - }), - )) = known_items::ConstUsize::parse_path_with_arguments(bounded_ty.clone()) - { - if args.len() != 1 { - errors.error(const_usize, "ConstUsize must have one argument"); - continue; - } - let GenericArgument::Type(Type::Path(TypePath { - qself: None, - path: arg, - })) = &args[0] - else { - errors.error( - const_usize, - "the only supported ConstUsize argument is a const generic parameter", - ); - continue; - }; - let arg = arg.get_ident(); - let Some((arg, &index)) = - arg.and_then(|arg| Some((arg, param_name_to_index_map.get(arg)?))) - else { - errors.error( - const_usize, - "the only supported ConstUsize argument is a const generic parameter", - ); - continue; - }; - let parsed_bounds = match &mut unparsed_params[index] { - UnparsedGenericParam::Const { bounds, .. } => bounds, - UnparsedGenericParam::Type { ident, .. } => { - errors.error( - bounded_ty, - format_args!("expected const generic parameter, found type `{ident}`"), - ); - continue; - } - }; - parsed_bounds - .get_or_insert_with(|| ParsedConstParamWhereBounds { - const_usize, - lt_token, - ident: arg.clone(), - gt_token, - colon_token, - bounds: ParsedSizeTypeBounds::default(), - }) - .bounds - .extend(errors.ok(syn::parse2::( - unparsed_bounds.to_token_stream(), - ))); - continue; - } - let Some(&index) = bounded_ty - .get_ident() - .and_then(|bounded_ty| param_name_to_index_map.get(bounded_ty)) - else { - errors.error( - bounded_ty, - "where predicate bounded type must be one of the generic type \ - parameters or `ConstUsize`", - ); - continue; - }; - let parsed_bounds = match &mut unparsed_params[index] { - UnparsedGenericParam::Type { bounds, .. } => bounds, - UnparsedGenericParam::Const { ident, .. } => { - errors.error( - bounded_ty, - format_args!("expected type, found const parameter `{ident}`"), - ); - continue; - } - }; - parsed_bounds.extend(errors.ok(syn::parse2::( - unparsed_bounds.to_token_stream(), - ))); - } - let params = - Punctuated::from_iter(unparsed_params.into_pairs().map_pair_value( - |param| match param { - UnparsedGenericParam::Type { - attrs, - options, - ident, - colon_token, - mut bounds, - mask_type_bounds, - } => { - for bound in mask_type_bounds { - bounds - .Type - .get_or_insert_with(|| known_items::Type(bound.span())); - match bound { - ParsedTypeBound::BundleType(_) - | ParsedTypeBound::EnumType(_) - | ParsedTypeBound::IntType(_) => { - errors.error(bound, "bound on mask type not implemented"); - } - ParsedTypeBound::StaticType(bound) => { - if bounds.StaticType.is_none() { - errors.error(bound, "StaticType bound on mask type without corresponding StaticType bound on original type is not implemented"); - } - }, - ParsedTypeBound::Type(_) => {} - } - } - bounds.add_implied_bounds(); - match bounds.categorize(&mut errors, ident.span()) { - ParsedBoundsCategory::Type(bounds) => { - ParsedGenericParam::Type(ParsedTypeParam { - attrs, - options, - ident, - colon_token, - bounds, - default: None, - }) - } - ParsedBoundsCategory::SizeType(bounds) => { - ParsedGenericParam::SizeType(ParsedSizeTypeParam { - attrs, - options, - ident, - colon_token, - bounds, - default: None, - }) - } - } - } - UnparsedGenericParam::Const { - attrs, - options, - const_token, - ident, - colon_token, - ty, - bounds, - } => { - let span = ident.span(); - let mut bounds = bounds.unwrap_or_else(|| ParsedConstParamWhereBounds { - const_usize: known_items::ConstUsize(span), - lt_token: Token![<](span), - ident: ident.clone(), - gt_token: Token![>](span), - colon_token: Token![:](span), - bounds: ParsedSizeTypeBounds { - KnownSize: None, - Size: Some(known_items::Size(span)), - }, - }); - bounds - .bounds - .Size - .get_or_insert_with(|| known_items::Size(span)); - bounds.bounds.add_implied_bounds(); - ParsedGenericParam::Const(ParsedConstParam { - bounds, - attrs, - options, - const_token, - ident, - colon_token, - ty, - }) - } - }, - )); - let mut retval = Self { - lt_token: *lt_token, - params, - gt_token: *gt_token, - param_name_to_index_map, - }; - for ( - cur_param_index, - LateParsedParam { - default, - const_param_type, - }, - ) in late_parsed_params.into_iter().enumerate() - { - let mut parser = TypesParser { - generics: &retval, - cur_param_index: Some(cur_param_index), - errors: &mut errors, - }; - let parsed_default = default.and_then(|(eq, ty)| { - let ty = parser.parse(ty).ok()?; - Some((eq, ty)) - }); - let parsed_const_param_type = const_param_type.and_then(|ty| parser.parse(ty).ok()); - match &mut retval.params[cur_param_index] { - ParsedGenericParam::Type(ParsedTypeParam { default, .. }) - | ParsedGenericParam::SizeType(ParsedSizeTypeParam { default, .. }) => { - *default = parsed_default; - } - ParsedGenericParam::Const(ParsedConstParam { - attrs: _, - options: _, - const_token: _, - ident: _, - colon_token: _, - ty, - bounds: _, - }) => { - if let Some(parsed_const_param_type) = parsed_const_param_type { - *ty = parsed_const_param_type; - } - } - } - } - errors.finish()?; - Ok(retval) - } -} - -impl ToTokens for ParsedGenerics { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - lt_token, - params, - gt_token, - param_name_to_index_map: _, - } = self; - if params.is_empty() { - return; - } - lt_token.unwrap_or_default().to_tokens(tokens); - params.to_tokens(tokens); - gt_token.unwrap_or_default().to_tokens(tokens); - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedGenericsImplGenerics<'a> { - generics: &'a ParsedGenerics, - param_count: usize, -} - -impl ToTokens for ParsedGenericsImplGenerics<'_> { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - generics, - param_count, - } = *self; - let ParsedGenerics { - lt_token, - params, - gt_token, - param_name_to_index_map: _, - } = generics; - if params.is_empty() || param_count == 0 { - return; - } - lt_token.unwrap_or_default().to_tokens(tokens); - for param in params.pairs().take(param_count) { - let (param, punct) = param.into_tuple(); - match param { - ParsedGenericParam::Type(ParsedTypeParam { - attrs: _, - options, - ident, - colon_token, - bounds, - default: _, - }) => { - let TypeParamOptions {} = options.body; - ident.to_tokens(tokens); - colon_token.to_tokens(tokens); - bounds.to_tokens(tokens); - } - ParsedGenericParam::SizeType(ParsedSizeTypeParam { - attrs: _, - options, - ident, - colon_token, - bounds, - default: _, - }) => { - let TypeParamOptions {} = options.body; - ident.to_tokens(tokens); - colon_token.to_tokens(tokens); - bounds.to_tokens(tokens); - } - ParsedGenericParam::Const(ParsedConstParam { - attrs: _, - options, - const_token, - ident, - colon_token, - ty, - bounds: _, - }) => { - let ConstParamOptions {} = options.body; - const_token.to_tokens(tokens); - ident.to_tokens(tokens); - colon_token.to_tokens(tokens); - ty.to_tokens(tokens); - } - } - punct.to_tokens(tokens); - } - gt_token.unwrap_or_default().to_tokens(tokens); - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedGenericsTurbofish<'a> { - generics: &'a ParsedGenerics, - param_count: usize, -} - -impl ToTokens for ParsedGenericsTurbofish<'_> { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - generics, - param_count, - } = *self; - if generics.params.is_empty() || param_count == 0 { - return; - } - Token![::](generics.lt_token.unwrap_or_default().span).to_tokens(tokens); - ParsedGenericsTypeGenerics { - generics, - param_count, - } - .to_tokens(tokens); - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedGenericsTypeGenerics<'a> { - generics: &'a ParsedGenerics, - param_count: usize, -} - -impl ToTokens for ParsedGenericsTypeGenerics<'_> { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - generics, - param_count, - } = *self; - let ParsedGenerics { - lt_token, - params, - gt_token, - param_name_to_index_map: _, - } = generics; - if params.is_empty() || param_count == 0 { - return; - } - lt_token.unwrap_or_default().to_tokens(tokens); - for param in params.pairs().take(param_count) { - let (param, punct) = param.into_tuple(); - param.ident().to_tokens(tokens); - punct.to_tokens(tokens); - } - gt_token.unwrap_or_default().to_tokens(tokens); - } -} - -#[derive(Debug, Clone)] -#[allow(dead_code)] -pub(crate) struct ParsedGenericsWhereClause<'a> { - generics: &'a ParsedGenerics, - param_count: usize, -} - -impl ToTokens for ParsedGenericsWhereClause<'_> { - fn to_tokens(&self, tokens: &mut TokenStream) { - let mut need_where_token = true; - let mut where_token = |span: Span| -> Option { - mem::replace(&mut need_where_token, false).then(|| Token![where](span)) - }; - for param in self.generics.params.pairs().take(self.param_count) { - let (param, comma_token) = param.into_tuple(); - match param { - ParsedGenericParam::Type(ParsedTypeParam { - ident, - colon_token, - bounds, - .. - }) => { - if let Some(static_type) = &bounds.StaticType { - where_token(static_type.span).to_tokens(tokens); - quote_spanned! {static_type.span=> - <#ident as ::fayalite::ty::Type>::MaskType #colon_token #static_type #comma_token - } - .to_tokens(tokens); - } - } - ParsedGenericParam::SizeType(_) => {} - ParsedGenericParam::Const(ParsedConstParam { - ident: _, - bounds: - ParsedConstParamWhereBounds { - const_usize, - lt_token, - ident, - gt_token, - colon_token, - bounds, - }, - .. - }) => { - where_token(ident.span()).to_tokens(tokens); - const_usize.to_tokens(tokens); - lt_token.to_tokens(tokens); - ident.to_tokens(tokens); - gt_token.to_tokens(tokens); - colon_token.to_tokens(tokens); - bounds.to_tokens(tokens); - comma_token.to_tokens(tokens); - } - } - } - } -} - -#[allow(dead_code)] -pub(crate) trait AsTurbofish { - type Turbofish<'a>: 'a + ToTokens + Clone + fmt::Debug - where - Self: 'a; - fn as_turbofish(&self) -> Self::Turbofish<'_>; -} - -impl AsTurbofish for TypeGenerics<'_> { - type Turbofish<'a> = Turbofish<'a> where Self: 'a; - - fn as_turbofish(&self) -> Self::Turbofish<'_> { - TypeGenerics::as_turbofish(self) - } -} - -impl AsTurbofish for ParsedGenericsTypeGenerics<'_> { - type Turbofish<'a> = ParsedGenericsTurbofish<'a> - where - Self: 'a; - - fn as_turbofish(&self) -> Self::Turbofish<'_> { - let Self { - generics, - param_count, - } = *self; - ParsedGenericsTurbofish { - generics, - param_count, - } - } -} - -pub(crate) trait SplitForImpl { - type ImplGenerics<'a>: 'a + ToTokens + Clone + fmt::Debug - where - Self: 'a; - type TypeGenerics<'a>: 'a + AsTurbofish + ToTokens + Clone + fmt::Debug - where - Self: 'a; - type WhereClause<'a>: 'a + ToTokens + Clone + fmt::Debug - where - Self: 'a; - fn split_for_impl( - &self, - ) -> ( - Self::ImplGenerics<'_>, - Self::TypeGenerics<'_>, - Self::WhereClause<'_>, - ); -} - -impl SplitForImpl for Generics { - type ImplGenerics<'a> = ImplGenerics<'a>; - type TypeGenerics<'a> = TypeGenerics<'a>; - type WhereClause<'a> = Option<&'a WhereClause>; - fn split_for_impl( - &self, - ) -> ( - Self::ImplGenerics<'_>, - Self::TypeGenerics<'_>, - Self::WhereClause<'_>, - ) { - Generics::split_for_impl(&self) - } -} - -impl SplitForImpl for ParsedGenerics { - type ImplGenerics<'a> = ParsedGenericsImplGenerics<'a> - where - Self: 'a; - - type TypeGenerics<'a> = ParsedGenericsTypeGenerics<'a> - where - Self: 'a; - - type WhereClause<'a> = ParsedGenericsWhereClause<'a> - where - Self: 'a; - - fn split_for_impl( - &self, - ) -> ( - Self::ImplGenerics<'_>, - Self::TypeGenerics<'_>, - Self::WhereClause<'_>, - ) { - ( - ParsedGenericsImplGenerics { - generics: self, - param_count: self.params.len(), - }, - ParsedGenericsTypeGenerics { - generics: self, - param_count: self.params.len(), - }, - ParsedGenericsWhereClause { - generics: self, - param_count: self.params.len(), - }, - ) - } -} - -impl From<&'_ ParsedGenerics> for Generics { - fn from(value: &ParsedGenerics) -> Self { - value.to_generics(None) - } -} - -impl From for Generics { - fn from(value: ParsedGenerics) -> Self { - From::<&ParsedGenerics>::from(&value) - } -} - -#[derive(Debug, Copy, Clone)] -pub(crate) enum MaybeParsed { - Unrecognized(U), - Parsed(P), -} - -impl MaybeParsed { - pub(crate) fn as_ref(&self) -> MaybeParsed<&P, &U> { - match self { - MaybeParsed::Unrecognized(v) => MaybeParsed::Unrecognized(v), - MaybeParsed::Parsed(v) => MaybeParsed::Parsed(v), - } - } - #[allow(dead_code)] - pub(crate) fn as_mut(&mut self) -> MaybeParsed<&mut P, &mut U> { - match self { - MaybeParsed::Unrecognized(v) => MaybeParsed::Unrecognized(v), - MaybeParsed::Parsed(v) => MaybeParsed::Parsed(v), - } - } - pub(crate) fn map PR, UF: FnOnce(U) -> UR, PR, UR>( - self, - pf: PF, - uf: UF, - ) -> MaybeParsed { - match self { - MaybeParsed::Unrecognized(v) => MaybeParsed::Unrecognized(uf(v)), - MaybeParsed::Parsed(v) => MaybeParsed::Parsed(pf(v)), - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct MaybeParsedIter(pub(crate) MaybeParsed); - -impl Iterator for MaybeParsedIter { - type Item = MaybeParsed; - - fn next(&mut self) -> Option { - match &mut self.0 { - MaybeParsed::Unrecognized(i) => i.next().map(MaybeParsed::Unrecognized), - MaybeParsed::Parsed(i) => i.next().map(MaybeParsed::Parsed), - } - } - - fn size_hint(&self) -> (usize, Option) { - match &self.0 { - MaybeParsed::Unrecognized(i) => i.size_hint(), - MaybeParsed::Parsed(i) => i.size_hint(), - } - } -} - -impl ExactSizeIterator for MaybeParsedIter {} - -impl DoubleEndedIterator for MaybeParsedIter { - fn next_back(&mut self) -> Option { - match &mut self.0 { - MaybeParsed::Unrecognized(i) => i.next_back().map(MaybeParsed::Unrecognized), - MaybeParsed::Parsed(i) => i.next_back().map(MaybeParsed::Parsed), - } - } -} - -impl IntoIterator for MaybeParsed { - type Item = MaybeParsed; - type IntoIter = MaybeParsedIter; - - fn into_iter(self) -> Self::IntoIter { - MaybeParsedIter(match self { - MaybeParsed::Unrecognized(v) => MaybeParsed::Unrecognized(v.into_iter()), - MaybeParsed::Parsed(v) => MaybeParsed::Parsed(v.into_iter()), - }) - } -} - -impl MaybeParsed { - #[allow(dead_code)] - pub(crate) fn iter<'a>( - &'a self, - ) -> MaybeParsedIter<<&'a P as IntoIterator>::IntoIter, <&'a U as IntoIterator>::IntoIter> - where - &'a P: IntoIterator, - &'a U: IntoIterator, - { - self.into_iter() - } - #[allow(dead_code)] - pub(crate) fn iter_mut<'a>( - &'a mut self, - ) -> MaybeParsedIter<<&'a mut P as IntoIterator>::IntoIter, <&'a mut U as IntoIterator>::IntoIter> - where - &'a mut P: IntoIterator, - &'a mut U: IntoIterator, - { - self.into_iter() - } -} - -impl<'a, P, U> IntoIterator for &'a MaybeParsed -where - &'a P: IntoIterator, - &'a U: IntoIterator, -{ - type Item = MaybeParsed<<&'a P as IntoIterator>::Item, <&'a U as IntoIterator>::Item>; - type IntoIter = - MaybeParsedIter<<&'a P as IntoIterator>::IntoIter, <&'a U as IntoIterator>::IntoIter>; - - fn into_iter(self) -> Self::IntoIter { - MaybeParsedIter(match self { - MaybeParsed::Unrecognized(v) => MaybeParsed::Unrecognized(v.into_iter()), - MaybeParsed::Parsed(v) => MaybeParsed::Parsed(v.into_iter()), - }) - } -} - -impl<'a, P, U> IntoIterator for &'a mut MaybeParsed -where - &'a mut P: IntoIterator, - &'a mut U: IntoIterator, -{ - type Item = MaybeParsed<<&'a mut P as IntoIterator>::Item, <&'a mut U as IntoIterator>::Item>; - type IntoIter = MaybeParsedIter< - <&'a mut P as IntoIterator>::IntoIter, - <&'a mut U as IntoIterator>::IntoIter, - >; - - fn into_iter(self) -> Self::IntoIter { - MaybeParsedIter(match self { - MaybeParsed::Unrecognized(v) => MaybeParsed::Unrecognized(v.into_iter()), - MaybeParsed::Parsed(v) => MaybeParsed::Parsed(v.into_iter()), - }) - } -} - -impl From> for Generics { - fn from(value: MaybeParsed) -> Self { - match value { - MaybeParsed::Unrecognized(value) => value, - MaybeParsed::Parsed(value) => value.into(), - } - } -} - -impl From<&'_ MaybeParsed> for Generics { - fn from(value: &MaybeParsed) -> Self { - match value { - MaybeParsed::Unrecognized(value) => value.clone(), - MaybeParsed::Parsed(value) => value.into(), - } - } -} - -impl ToTokens for MaybeParsed { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - MaybeParsed::Unrecognized(v) => v.to_tokens(tokens), - MaybeParsed::Parsed(v) => v.to_tokens(tokens), - } - } - - fn to_token_stream(&self) -> TokenStream { - match self { - MaybeParsed::Unrecognized(v) => v.to_token_stream(), - MaybeParsed::Parsed(v) => v.to_token_stream(), - } - } - - fn into_token_stream(self) -> TokenStream { - match self { - MaybeParsed::Unrecognized(v) => v.into_token_stream(), - MaybeParsed::Parsed(v) => v.into_token_stream(), - } - } -} - -impl AsTurbofish for MaybeParsed { - type Turbofish<'a> = MaybeParsed, U::Turbofish<'a>> - where - Self: 'a; - - fn as_turbofish(&self) -> Self::Turbofish<'_> { - match self { - MaybeParsed::Unrecognized(v) => MaybeParsed::Unrecognized(v.as_turbofish()), - MaybeParsed::Parsed(v) => MaybeParsed::Parsed(v.as_turbofish()), - } - } -} - -impl SplitForImpl for MaybeParsed { - type ImplGenerics<'a> = MaybeParsed, U::ImplGenerics<'a>> - where - Self: 'a; - type TypeGenerics<'a> = MaybeParsed, U::TypeGenerics<'a>> - where - Self: 'a; - type WhereClause<'a> = MaybeParsed, U::WhereClause<'a>> - where - Self: 'a; - - fn split_for_impl( - &self, - ) -> ( - Self::ImplGenerics<'_>, - Self::TypeGenerics<'_>, - Self::WhereClause<'_>, - ) { - match self { - MaybeParsed::Unrecognized(v) => { - let (i, t, w) = v.split_for_impl(); - ( - MaybeParsed::Unrecognized(i), - MaybeParsed::Unrecognized(t), - MaybeParsed::Unrecognized(w), - ) - } - MaybeParsed::Parsed(v) => { - let (i, t, w) = v.split_for_impl(); - ( - MaybeParsed::Parsed(i), - MaybeParsed::Parsed(t), - MaybeParsed::Parsed(w), - ) - } - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedField { - pub(crate) attrs: Vec, - pub(crate) vis: Visibility, - pub(crate) ident: Option, - pub(crate) colon_token: Option, - pub(crate) ty: ParsedType, -} - -impl ParseTypes for ParsedField { - fn parse_types(input: &mut Field, parser: &mut TypesParser<'_>) -> Result { - let Field { - attrs, - vis, - mutability, - ident, - colon_token, - ty, - } = input; - if !matches!(mutability, FieldMutability::None) { - // FIXME: use mutability as the spanned tokens, - // blocked on https://github.com/dtolnay/syn/issues/1717 - parser - .errors() - .error(&ident, "field mutability is not supported"); - *mutability = FieldMutability::None; - } - *mutability = FieldMutability::None; - Ok(Self { - attrs: attrs.clone(), - vis: vis.clone(), - ident: ident.clone(), - colon_token: *colon_token, - ty: parser.parse(ty)?, - }) - } -} - -impl From for Field { - fn from(value: ParsedField) -> Self { - Self { - attrs: value.attrs, - vis: value.vis, - mutability: FieldMutability::None, - ident: value.ident, - colon_token: value.colon_token, - ty: value.ty.into(), - } - } -} - -impl<'a> MaybeParsed<&'a ParsedField, &'a Field> { - pub(crate) fn ident(self) -> &'a Option { - match self { - MaybeParsed::Unrecognized(v) => &v.ident, - MaybeParsed::Parsed(v) => &v.ident, - } - } - pub(crate) fn ty(self) -> MaybeParsed<&'a ParsedType, &'a Type> { - match self { - MaybeParsed::Unrecognized(v) => MaybeParsed::Unrecognized(&v.ty), - MaybeParsed::Parsed(v) => MaybeParsed::Parsed(&v.ty), - } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ParsedFieldsNamed { - pub(crate) brace_token: Brace, - pub(crate) named: Punctuated, -} - -impl ParseTypes for ParsedFieldsNamed { - fn parse_types( - input: &mut FieldsNamed, - parser: &mut TypesParser<'_>, - ) -> Result { - let FieldsNamed { brace_token, named } = input; - Ok(Self { - brace_token: *brace_token, - named: parser.parse(named)?, - }) - } -} - -impl From for FieldsNamed { - fn from(value: ParsedFieldsNamed) -> Self { - Self { - brace_token: value.brace_token, - named: value - .named - .into_pairs() - .map_pair_value(Into::into) - .collect(), - } - } -} - -impl MaybeParsed { - pub(crate) fn named( - &self, - ) -> MaybeParsed<&Punctuated, &Punctuated> { - self.as_ref().map(|v| &v.named, |v| &v.named) - } -} - -impl From> for FieldsNamed { - fn from(value: MaybeParsed) -> Self { - match value { - MaybeParsed::Unrecognized(value) => value, - MaybeParsed::Parsed(value) => value.into(), - } - } -} - -#[derive(Debug)] -pub(crate) struct MakeHdlTypeExprContext { - pub(crate) named_param_values: Vec, - pub(crate) is_const: bool, -} - -pub(crate) trait MakeHdlTypeExpr { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr; -} - -impl MakeHdlTypeExpr for ParsedType { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - match self { - Self::Delimited(v) => v.make_hdl_type_expr(context), - Self::Named(v) => v.make_hdl_type_expr(context), - Self::NamedParam(v) => v.make_hdl_type_expr(context), - Self::Tuple(v) => v.make_hdl_type_expr(context), - Self::ConstUsize(v) => v.make_hdl_type_expr(context), - Self::Array(v) => v.make_hdl_type_expr(context), - Self::UInt(v) => v.make_hdl_type_expr(context), - Self::SInt(v) => v.make_hdl_type_expr(context), - Self::CanonicalType(v) => v.make_hdl_type_expr(context), - Self::DynSize(v) => v.make_hdl_type_expr(context), - } - } -} - -impl MakeHdlTypeExpr for known_items::CanonicalType { - fn make_hdl_type_expr(&self, _context: &MakeHdlTypeExprContext) -> Expr { - Expr::Path(ExprPath { - attrs: vec![], - qself: None, - path: self.path.clone(), - }) - } -} - -impl MakeHdlTypeExpr for known_items::DynSize { - fn make_hdl_type_expr(&self, _context: &MakeHdlTypeExprContext) -> Expr { - Expr::Path(ExprPath { - attrs: vec![], - qself: None, - path: self.path.clone(), - }) - } -} - -impl MakeHdlTypeExpr for ParsedExprDelimited { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - self.expr.make_hdl_type_expr(context) - } -} - -impl MakeHdlTypeExpr for ParsedExprNamedParamConst { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - context.named_param_values[self.param_index].clone() - } -} - -impl MakeHdlTypeExpr for ParsedExpr { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - match self { - ParsedExpr::Delimited(expr) => expr.make_hdl_type_expr(context), - ParsedExpr::NamedParamConst(expr) => expr.make_hdl_type_expr(context), - ParsedExpr::Other(expr) => (**expr).clone(), - } - } -} - -impl MakeHdlTypeExpr for ParsedTypeDelimited { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - self.elem.make_hdl_type_expr(context) - } -} - -impl MakeHdlTypeExpr for ParsedTypeNamed { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - let Self { path, args } = self; - let span = path - .segments - .last() - .map(|v| v.ident.span()) - .unwrap_or_else(Span::call_site); - if context.is_const { - return parse_quote_spanned! {span=> - ::fayalite::ty::StaticType::TYPE - }; - } - let mut retval = Expr::Path(ExprPath { - attrs: vec![], - qself: None, - path: path.clone(), - }); - if let Some(ParsedGenericArguments { lt_token, args, .. }) = args { - for arg in args { - retval = Expr::Index(ExprIndex { - attrs: vec![], - expr: Box::new(retval), - bracket_token: Bracket(lt_token.span), - index: Box::new(arg.make_hdl_type_expr(context)), - }); - } - } - Expr::Call(syn::ExprCall { - attrs: vec![], - func: parse_quote_spanned! {span=> - ::fayalite::ty::FillInDefaultedGenerics::fill_in_defaulted_generics - }, - paren_token: Paren(span), - args: Punctuated::from_iter([retval]), - }) - } -} - -impl MakeHdlTypeExpr for ParsedGenericArgument { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - match self { - ParsedGenericArgument::Type(v) => v.make_hdl_type_expr(context), - ParsedGenericArgument::Const(v) => v.make_hdl_type_expr(context), - } - } -} - -impl MakeHdlTypeExpr for ParsedTypeNamedParam { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - match self { - Self::Type(v) => v.make_hdl_type_expr(context), - Self::SizeType(v) => v.make_hdl_type_expr(context), - } - } -} - -impl MakeHdlTypeExpr for ParsedTypeNamedParamType { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - context.named_param_values[self.param_index].clone() - } -} - -impl MakeHdlTypeExpr for ParsedTypeNamedParamSizeType { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - context.named_param_values[self.param_index].clone() - } -} - -impl MakeHdlTypeExpr for ParsedTypeTuple { - fn make_hdl_type_expr(&self, context: &MakeHdlTypeExprContext) -> Expr { - let Self { paren_token, elems } = self; - Expr::Tuple(ExprTuple { - attrs: vec![], - paren_token: *paren_token, - elems: elems - .pairs() - .map_pair_value_ref(|v| v.make_hdl_type_expr(context)) - .collect(), - }) - } -} diff --git a/crates/fayalite-proc-macros-impl/src/lib.rs b/crates/fayalite-proc-macros-impl/src/lib.rs index 94fb040..920a27b 100644 --- a/crates/fayalite-proc-macros-impl/src/lib.rs +++ b/crates/fayalite-proc-macros-impl/src/lib.rs @@ -13,15 +13,15 @@ use syn::{ }; mod fold; -mod hdl_bundle; -mod hdl_enum; -mod hdl_type_common; mod module; -//mod value_derive_common; -//mod value_derive_struct; +mod value_derive_common; +mod value_derive_enum; +mod value_derive_struct; mod kw { - pub(crate) use syn::token::Extern as extern_; + pub(crate) use syn::token::{ + Enum as enum_, Extern as extern_, Static as static_, Struct as struct_, Where as where_, + }; macro_rules! custom_keyword { ($kw:ident) => { @@ -43,7 +43,6 @@ mod kw { custom_keyword!(clock_domain); custom_keyword!(connect_inexact); - custom_keyword!(custom_bounds); custom_keyword!(flip); custom_keyword!(hdl); custom_keyword!(input); @@ -53,8 +52,6 @@ mod kw { custom_keyword!(memory_array); custom_keyword!(memory_with_init); custom_keyword!(no_reset); - custom_keyword!(no_runtime_generics); - custom_keyword!(no_static); custom_keyword!(outline_generated); custom_keyword!(output); custom_keyword!(reg_builder); @@ -522,26 +519,6 @@ macro_rules! impl_extra_traits_for_options { ) => { impl Copy for $option_enum_name {} - impl PartialEq for $option_enum_name { - fn eq(&self, other: &Self) -> bool { - self.cmp(other).is_eq() - } - } - - impl Eq for $option_enum_name {} - - impl PartialOrd for $option_enum_name { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } - } - - impl Ord for $option_enum_name { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.variant().cmp(&other.variant()) - } - } - impl quote::IdentFragment for $option_enum_name { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let _ = f; @@ -577,66 +554,6 @@ pub(crate) use impl_extra_traits_for_options; macro_rules! options { ( #[options = $options_name:ident] - $($tt:tt)* - ) => { - crate::options! { - #[options = $options_name, punct = syn::Token![,], allow_duplicates = false] - $($tt)* - } - }; - ( - #[options = $options_name:ident, punct = $Punct:ty, allow_duplicates = true] - $(#[$($enum_meta:tt)*])* - $enum_vis:vis enum $option_enum_name:ident { - $($Variant:ident($key:ident $(, $value:ty)?),)* - } - ) => { - crate::options! { - #[options = $options_name, punct = $Punct, allow_duplicates = (true)] - $(#[$($enum_meta)*])* - $enum_vis enum $option_enum_name { - $($Variant($key $(, $value)?),)* - } - } - - impl Extend<$option_enum_name> for $options_name { - fn extend>(&mut self, iter: T) { - iter.into_iter().for_each(|v| match v { - $($option_enum_name::$Variant(v) => { - self.$key = Some(v); - })* - }); - } - } - - impl FromIterator<$option_enum_name> for $options_name { - fn from_iter>(iter: T) -> Self { - let mut retval = Self::default(); - retval.extend(iter); - retval - } - } - - impl Extend<$options_name> for $options_name { - fn extend>(&mut self, iter: T) { - iter.into_iter().for_each(|v| { - $(if let Some(v) = v.$key { - self.$key = Some(v); - })* - }); - } - } - - impl FromIterator<$options_name> for $options_name { - fn from_iter>(iter: T) -> Self { - let mut retval = Self::default(); - retval.extend(iter); - retval - } - } - }; - ( - #[options = $options_name:ident, punct = $Punct:ty, allow_duplicates = $allow_duplicates:expr] $(#[$($enum_meta:tt)*])* $enum_vis:vis enum $option_enum_name:ident { $($Variant:ident($key:ident $(, $value:ty)?),)* @@ -650,11 +567,8 @@ macro_rules! options { } #[derive(Clone, Debug, Default)] - #[allow(non_snake_case)] $enum_vis struct $options_name { - $( - $enum_vis $key: Option<(crate::kw::$key, $(syn::token::Paren, $value)?)>, - )* + $($enum_vis $key: Option<(crate::kw::$key, $(syn::token::Paren, $value)?)>,)* } crate::fold::impl_fold! { @@ -663,43 +577,6 @@ macro_rules! options { } } - const _: () = { - #[derive(Clone, Debug)] - $enum_vis struct Iter($enum_vis $options_name); - - impl IntoIterator for $options_name { - type Item = $option_enum_name; - type IntoIter = Iter; - - fn into_iter(self) -> Self::IntoIter { - Iter(self) - } - } - - impl Iterator for Iter { - type Item = $option_enum_name; - - fn next(&mut self) -> Option { - $( - if let Some(value) = self.0.$key.take() { - return Some($option_enum_name::$Variant(value)); - } - )* - None - } - - #[allow(unused_mut, unused_variables)] - fn fold B>(mut self, mut init: B, mut f: F) -> B { - $( - if let Some(value) = self.0.$key.take() { - init = f(init, $option_enum_name::$Variant(value)); - } - )* - init - } - } - }; - impl syn::parse::Parse for $options_name { fn parse(input: syn::parse::ParseStream) -> syn::Result { #![allow(unused_mut, unused_variables, unreachable_code)] @@ -708,7 +585,7 @@ macro_rules! options { let old_input = input.fork(); match input.parse::<$option_enum_name>()? { $($option_enum_name::$Variant(v) => { - if retval.$key.replace(v).is_some() && !$allow_duplicates { + if retval.$key.replace(v).is_some() { return Err(old_input.error(concat!("duplicate ", stringify!($key), " option"))); } })* @@ -716,7 +593,7 @@ macro_rules! options { if input.is_empty() { break; } - input.parse::<$Punct>()?; + input.parse::()?; } Ok(retval) } @@ -725,7 +602,7 @@ macro_rules! options { impl quote::ToTokens for $options_name { #[allow(unused_mut, unused_variables, unused_assignments)] fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { - let mut separator: Option<$Punct> = None; + let mut separator: Option = None; $(if let Some(v) = &self.$key { separator.to_tokens(tokens); separator = Some(Default::default()); @@ -796,20 +673,6 @@ macro_rules! options { } } } - - impl $option_enum_name { - #[allow(dead_code)] - fn variant(&self) -> usize { - #[repr(usize)] - enum Variant { - $($Variant,)* - __Last, // so it doesn't complain about zero-variant enums - } - match *self { - $(Self::$Variant(..) => Variant::$Variant as usize,)* - } - } - } }; } @@ -823,15 +686,6 @@ pub(crate) fn outline_generated(contents: TokenStream, prefix: &str) -> TokenStr .suffix(".tmp.rs") .tempfile_in(out_dir) .unwrap(); - struct PrintOnPanic<'a>(&'a TokenStream); - impl Drop for PrintOnPanic<'_> { - fn drop(&mut self) { - if std::thread::panicking() { - println!("{}", self.0); - } - } - } - let _print_on_panic = PrintOnPanic(&contents); let contents = prettyplease::unparse(&parse_quote! { #contents }); let hash = ::digest(&contents); let hash = base16ct::HexDisplay(&hash[..5]); @@ -852,7 +706,7 @@ pub(crate) fn outline_generated(contents: TokenStream, prefix: &str) -> TokenStr } } -pub fn hdl_module(attr: TokenStream, item: TokenStream) -> syn::Result { +pub fn module(attr: TokenStream, item: TokenStream) -> syn::Result { let options = syn::parse2::(attr)?; let options = HdlAttr::from(options); let func = syn::parse2::(quote! { #options #item })?; @@ -863,14 +717,14 @@ pub fn hdl_module(attr: TokenStream, item: TokenStream) -> syn::Result syn::Result { - let item = syn::parse2::(quote! { #[hdl(#attr)] #item })?; +pub fn value_derive(item: TokenStream) -> syn::Result { + let item = syn::parse2::(item)?; match item { - Item::Enum(item) => hdl_enum::hdl_enum(item), - Item::Struct(item) => hdl_bundle::hdl_bundle(item), + Item::Enum(item) => value_derive_enum::value_derive_enum(item), + Item::Struct(item) => value_derive_struct::value_derive_struct(item), _ => Err(syn::Error::new( Span::call_site(), - "top-level #[hdl] can only be used on structs or enums", + "derive(Value) can only be used on structs or enums", )), } } diff --git a/crates/fayalite-proc-macros-impl/src/module.rs b/crates/fayalite-proc-macros-impl/src/module.rs index 0945abb..ff5c1e5 100644 --- a/crates/fayalite-proc-macros-impl/src/module.rs +++ b/crates/fayalite-proc-macros-impl/src/module.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // See Notices.txt for copyright information use crate::{ - hdl_type_common::{ParsedGenerics, SplitForImpl}, + is_hdl_attr, module::transform_body::{HdlLet, HdlLetKindIO}, options, Errors, HdlAttr, PairsIterExt, }; @@ -57,6 +57,13 @@ impl Visit<'_> for CheckNameConflictsWithModuleBuilderVisitor<'_> { } } +fn retain_struct_attrs bool>(item: &mut ItemStruct, mut f: F) { + item.attrs.retain(&mut f); + for field in item.fields.iter_mut() { + field.attrs.retain(&mut f); + } +} + pub(crate) type ModuleIO = HdlLet; pub(crate) struct ModuleFn { @@ -66,8 +73,8 @@ pub(crate) struct ModuleFn { vis: Visibility, sig: Signature, block: Box, - struct_generics: ParsedGenerics, - the_struct: TokenStream, + io: Vec, + struct_generics: Generics, } #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] @@ -213,52 +220,9 @@ impl Parse for ModuleFn { "return type not allowed here", )); } - let struct_generics = errors.ok(ParsedGenerics::parse(&mut { struct_generics })); - let body_results = struct_generics.as_ref().and_then(|struct_generics| { - errors.ok(transform_body::transform_body( - module_kind, - block, - struct_generics, - )) - }); + let body_results = errors.ok(transform_body::transform_body(module_kind, block)); errors.finish()?; - let struct_generics = struct_generics.unwrap(); let (block, io) = body_results.unwrap(); - let (_struct_impl_generics, _struct_type_generics, struct_where_clause) = - struct_generics.split_for_impl(); - let struct_where_clause: Option = parse_quote! { #struct_where_clause }; - if let Some(struct_where_clause) = &struct_where_clause { - sig.generics - .where_clause - .get_or_insert_with(|| WhereClause { - where_token: struct_where_clause.where_token, - predicates: Default::default(), - }) - .predicates - .extend(struct_where_clause.predicates.clone()); - } - let fn_name = &sig.ident; - let io_flips = io - .iter() - .map(|io| match io.kind.kind { - ModuleIOKind::Input((input,)) => quote_spanned! {input.span=> - #[hdl(flip)] - }, - ModuleIOKind::Output(_) => quote! {}, - }) - .collect::>(); - let io_types = io.iter().map(|io| &io.kind.ty).collect::>(); - let io_names = io.iter().map(|io| &io.name).collect::>(); - let the_struct: ItemStruct = parse_quote! { - #[allow(non_camel_case_types)] - #[hdl(no_runtime_generics, no_static)] - #vis struct #fn_name #struct_generics #struct_where_clause { - #( - #io_flips - #vis #io_names: #io_types,)* - } - }; - let the_struct = crate::hdl_bundle::hdl_bundle(the_struct)?; Ok(Self { attrs, config_options, @@ -266,8 +230,8 @@ impl Parse for ModuleFn { vis, sig, block, + io, struct_generics, - the_struct, }) } } @@ -281,8 +245,8 @@ impl ModuleFn { vis, sig, block, + io, struct_generics, - the_struct, } = self; let ConfigOptions { outline_generated: _, @@ -309,18 +273,19 @@ impl ModuleFn { }); name })); - let module_kind_value = match module_kind { - ModuleKind::Extern => quote! { ::fayalite::module::ModuleKind::Extern }, - ModuleKind::Normal => quote! { ::fayalite::module::ModuleKind::Normal }, + let module_kind_ty = match module_kind { + ModuleKind::Extern => quote! { ::fayalite::module::ExternModule }, + ModuleKind::Normal => quote! { ::fayalite::module::NormalModule }, }; let fn_name = &outer_sig.ident; - let (_struct_impl_generics, struct_type_generics, _struct_where_clause) = + let (_struct_impl_generics, struct_type_generics, struct_where_clause) = struct_generics.split_for_impl(); let struct_ty = quote! {#fn_name #struct_type_generics}; body_sig.ident = parse_quote! {__body}; - body_sig - .inputs - .insert(0, parse_quote! { m: &::fayalite::module::ModuleBuilder }); + body_sig.inputs.insert( + 0, + parse_quote! {m: &mut ::fayalite::module::ModuleBuilder<#struct_ty, #module_kind_ty>}, + ); let body_fn = ItemFn { attrs: vec![], vis: Visibility::Inherited, @@ -329,17 +294,50 @@ impl ModuleFn { }; outer_sig.output = parse_quote! {-> ::fayalite::intern::Interned<::fayalite::module::Module<#struct_ty>>}; + let io_flips = io + .iter() + .map(|io| match io.kind.kind { + ModuleIOKind::Input((input,)) => quote_spanned! {input.span=> + #[hdl(flip)] + }, + ModuleIOKind::Output(_) => quote! {}, + }) + .collect::>(); + let io_types = io.iter().map(|io| &io.kind.ty).collect::>(); + let io_names = io.iter().map(|io| &io.name).collect::>(); let fn_name_str = fn_name.to_string(); let (_, body_type_generics, _) = body_fn.sig.generics.split_for_impl(); let body_turbofish_type_generics = body_type_generics.as_turbofish(); let block = parse_quote! {{ #body_fn - ::fayalite::module::ModuleBuilder::run( - #fn_name_str, - #module_kind_value, - |m| __body #body_turbofish_type_generics(m, #(#param_names,)*), - ) + ::fayalite::module::ModuleBuilder::run(#fn_name_str, |m| __body #body_turbofish_type_generics(m, #(#param_names,)*)) }}; + let static_type = io.iter().all(|io| io.kind.ty_expr.is_none()); + let struct_options = if static_type { + quote! { #[hdl(static)] } + } else { + quote! {} + }; + let the_struct: ItemStruct = parse_quote! { + #[derive(::fayalite::__std::clone::Clone, + ::fayalite::__std::hash::Hash, + ::fayalite::__std::cmp::PartialEq, + ::fayalite::__std::cmp::Eq, + ::fayalite::__std::fmt::Debug)] + #[allow(non_camel_case_types)] + #struct_options + #vis struct #fn_name #struct_generics #struct_where_clause { + #( + #io_flips + #vis #io_names: #io_types,)* + } + }; + let mut struct_without_hdl_attrs = the_struct.clone(); + let mut struct_without_derives = the_struct; + retain_struct_attrs(&mut struct_without_hdl_attrs, |attr| !is_hdl_attr(attr)); + retain_struct_attrs(&mut struct_without_derives, |attr| { + !attr.path().is_ident("derive") + }); let outer_fn = ItemFn { attrs, vis, @@ -347,7 +345,10 @@ impl ModuleFn { block, }; let mut retval = outer_fn.into_token_stream(); - retval.extend(the_struct); + struct_without_hdl_attrs.to_tokens(&mut retval); + retval.extend( + crate::value_derive_struct::value_derive_struct(struct_without_derives).unwrap(), + ); retval } } diff --git a/crates/fayalite-proc-macros-impl/src/module/transform_body.rs b/crates/fayalite-proc-macros-impl/src/module/transform_body.rs index 76e1d69..d2b3e77 100644 --- a/crates/fayalite-proc-macros-impl/src/module/transform_body.rs +++ b/crates/fayalite-proc-macros-impl/src/module/transform_body.rs @@ -2,14 +2,11 @@ // See Notices.txt for copyright information use crate::{ fold::{impl_fold, DoFold}, - hdl_type_common::{ - known_items, ParseFailed, ParseTypes, ParsedGenerics, ParsedType, TypesParser, - }, is_hdl_attr, kw, module::{check_name_conflicts_with_module_builder, ModuleIO, ModuleIOKind, ModuleKind}, options, Errors, HdlAttr, }; -use num_bigint::BigInt; +use num_bigint::{BigInt, Sign}; use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use std::{borrow::Borrow, convert::Infallible}; @@ -90,9 +87,9 @@ macro_rules! with_debug_clone_and_fold { pub(crate) use with_debug_clone_and_fold; with_debug_clone_and_fold! { - pub(crate) struct HdlLetKindIO { + pub(crate) struct HdlLetKindIO { pub(crate) colon_token: Token![:], - pub(crate) ty: Box, + pub(crate) ty: Box, pub(crate) m: kw::m, pub(crate) dot_token: Token![.], pub(crate) kind: Kind, @@ -101,32 +98,6 @@ with_debug_clone_and_fold! { } } -impl, I> ParseTypes> for HdlLetKindIO { - fn parse_types( - input: &mut HdlLetKindIO, - parser: &mut TypesParser<'_>, - ) -> Result { - let HdlLetKindIO { - colon_token, - ty, - m, - dot_token, - kind, - paren, - ty_expr, - } = input; - Ok(Self { - colon_token: *colon_token, - ty: ParseTypes::parse_types(ty, parser)?, - m: *m, - dot_token: *dot_token, - kind: kind.clone(), - paren: *paren, - ty_expr: ty_expr.clone(), - }) - } -} - pub(crate) fn parse_single_fn_arg(input: ParseStream) -> syn::Result> { let retval = input.parse()?; let _: Option = input.parse()?; @@ -174,19 +145,17 @@ impl HdlLetKindToTokens for HdlLetKindIO { #[derive(Clone, Debug)] pub(crate) struct HdlLetKindInstance { + pub(crate) m: kw::m, + pub(crate) dot_token: Token![.], pub(crate) instance: kw::instance, pub(crate) paren: Paren, pub(crate) module: Box, } -impl ParseTypes for HdlLetKindInstance { - fn parse_types(input: &mut Self, _parser: &mut TypesParser<'_>) -> Result { - Ok(input.clone()) - } -} - impl_fold! { struct HdlLetKindInstance<> { + m: kw::m, + dot_token: Token![.], instance: kw::instance, paren: Paren, module: Box, @@ -198,10 +167,14 @@ impl HdlLetKindToTokens for HdlLetKindInstance { fn expr_to_tokens(&self, tokens: &mut TokenStream) { let Self { + m, + dot_token, instance, paren, module, } = self; + m.to_tokens(tokens); + dot_token.to_tokens(tokens); instance.to_tokens(tokens); paren.surround(tokens, |tokens| module.to_tokens(tokens)); } @@ -408,21 +381,19 @@ make_builder_method_enum! { #[derive(Clone, Debug)] pub(crate) struct HdlLetKindRegBuilder { pub(crate) ty: Option<(Token![:], Box)>, + pub(crate) m: kw::m, + pub(crate) dot_token: Token![.], pub(crate) reg_builder: kw::reg_builder, pub(crate) reg_builder_paren: Paren, pub(crate) clock_domain: Option, pub(crate) reset: RegBuilderReset, } -impl ParseTypes for HdlLetKindRegBuilder { - fn parse_types(input: &mut Self, _parser: &mut TypesParser<'_>) -> Result { - Ok(input.clone()) - } -} - impl_fold! { struct HdlLetKindRegBuilder<> { ty: Option<(Token![:], Box)>, + m: kw::m, + dot_token: Token![.], reg_builder: kw::reg_builder, reg_builder_paren: Paren, clock_domain: Option, @@ -435,10 +406,10 @@ impl HdlLetKindRegBuilder { input: ParseStream, parsed_ty: Option<(Token![:], Box)>, _after_ty: Token![=], - m_dot: Option<(kw::m, Token![.])>, + m: kw::m, + dot_token: Token![.], reg_builder: kw::reg_builder, ) -> syn::Result { - check_empty_m_dot(m_dot, reg_builder)?; let _reg_builder_paren_inner; let reg_builder_paren = parenthesized!(_reg_builder_paren_inner in input); let mut clock_domain = None; @@ -459,6 +430,8 @@ impl HdlLetKindRegBuilder { } Ok(Self { ty: parsed_ty, + m, + dot_token, reg_builder, reg_builder_paren, clock_domain, @@ -478,11 +451,15 @@ impl HdlLetKindToTokens for HdlLetKindRegBuilder { fn expr_to_tokens(&self, tokens: &mut TokenStream) { let Self { ty: _, + m, + dot_token, reg_builder, reg_builder_paren, clock_domain, reset, } = self; + m.to_tokens(tokens); + dot_token.to_tokens(tokens); reg_builder.to_tokens(tokens); reg_builder_paren.surround(tokens, |_tokens| {}); clock_domain.to_tokens(tokens); @@ -493,20 +470,18 @@ impl HdlLetKindToTokens for HdlLetKindRegBuilder { #[derive(Clone, Debug)] pub(crate) struct HdlLetKindWire { pub(crate) ty: Option<(Token![:], Box)>, + pub(crate) m: kw::m, + pub(crate) dot_token: Token![.], pub(crate) wire: kw::wire, pub(crate) paren: Paren, pub(crate) ty_expr: Option>, } -impl ParseTypes for HdlLetKindWire { - fn parse_types(input: &mut Self, _parser: &mut TypesParser<'_>) -> Result { - Ok(input.clone()) - } -} - impl_fold! { struct HdlLetKindWire<> { ty: Option<(Token![:], Box)>, + m: kw::m, + dot_token: Token![.], wire: kw::wire, paren: Paren, ty_expr: Option>, @@ -524,10 +499,14 @@ impl HdlLetKindToTokens for HdlLetKindWire { fn expr_to_tokens(&self, tokens: &mut TokenStream) { let Self { ty: _, + m, + dot_token, wire, paren, ty_expr, } = self; + m.to_tokens(tokens); + dot_token.to_tokens(tokens); wire.to_tokens(tokens); paren.surround(tokens, |tokens| ty_expr.to_tokens(tokens)); } @@ -648,18 +627,16 @@ impl ToTokens for MemoryFn { #[derive(Clone, Debug)] pub(crate) struct HdlLetKindMemory { pub(crate) ty: Option<(Token![:], Box)>, + pub(crate) m: kw::m, + pub(crate) dot_token: Token![.], pub(crate) memory_fn: MemoryFn, } -impl ParseTypes for HdlLetKindMemory { - fn parse_types(input: &mut Self, _parser: &mut TypesParser<'_>) -> Result { - Ok(input.clone()) - } -} - impl_fold! { struct HdlLetKindMemory<> { ty: Option<(Token![:], Box)>, + m: kw::m, + dot_token: Token![.], memory_fn: MemoryFn, } } @@ -673,7 +650,14 @@ impl HdlLetKindToTokens for HdlLetKindMemory { } fn expr_to_tokens(&self, tokens: &mut TokenStream) { - let Self { ty: _, memory_fn } = self; + let Self { + ty: _, + m, + dot_token, + memory_fn, + } = self; + m.to_tokens(tokens); + dot_token.to_tokens(tokens); memory_fn.to_tokens(tokens); } } @@ -683,20 +667,22 @@ impl HdlLetKindMemory { input: ParseStream, parsed_ty: Option<(Token![:], Box)>, _after_ty: Token![=], - m_dot: Option<(kw::m, Token![.])>, + m: kw::m, + dot_token: Token![.], memory_fn_name: MemoryFnName, ) -> syn::Result { - check_empty_m_dot(m_dot, memory_fn_name)?; Ok(Self { ty: parsed_ty, + m, + dot_token, memory_fn: MemoryFn::parse_rest(input, memory_fn_name)?, }) } } #[derive(Clone, Debug)] -pub(crate) enum HdlLetKind { - IO(HdlLetKindIO), +pub(crate) enum HdlLetKind { + IO(HdlLetKindIO), Instance(HdlLetKindInstance), RegBuilder(HdlLetKindRegBuilder), Wire(HdlLetKindWire), @@ -704,8 +690,8 @@ pub(crate) enum HdlLetKind { } impl_fold! { - enum HdlLetKind { - IO(HdlLetKindIO), + enum HdlLetKind<> { + IO(HdlLetKindIO), Instance(HdlLetKindInstance), RegBuilder(HdlLetKindRegBuilder), Wire(HdlLetKindWire), @@ -713,27 +699,6 @@ impl_fold! { } } -impl, I> ParseTypes> for HdlLetKind { - fn parse_types( - input: &mut HdlLetKind, - parser: &mut TypesParser<'_>, - ) -> Result { - match input { - HdlLetKind::IO(input) => ParseTypes::parse_types(input, parser).map(HdlLetKind::IO), - HdlLetKind::Instance(input) => { - ParseTypes::parse_types(input, parser).map(HdlLetKind::Instance) - } - HdlLetKind::RegBuilder(input) => { - ParseTypes::parse_types(input, parser).map(HdlLetKind::RegBuilder) - } - HdlLetKind::Wire(input) => ParseTypes::parse_types(input, parser).map(HdlLetKind::Wire), - HdlLetKind::Memory(input) => { - ParseTypes::parse_types(input, parser).map(HdlLetKind::Memory) - } - } - } -} - fn parsed_ty_or_err( parsed_ty: Option<(Token![:], Box)>, after_ty: Token![=], @@ -745,15 +710,15 @@ fn parsed_ty_or_err( } } -impl HdlLetKindIO { +impl HdlLetKindIO { fn rest_of_parse( input: ParseStream, parsed_ty: Option<(Token![:], Box)>, after_ty: Token![=], - m_dot: Option<(kw::m, Token![.])>, + m: kw::m, + dot_token: Token![.], kind: ModuleIOKind, ) -> syn::Result { - let (m, dot_token) = unwrap_m_dot(m_dot, kind)?; let (colon_token, ty) = parsed_ty_or_err(parsed_ty, after_ty)?; let paren_contents; Ok(Self { @@ -768,36 +733,7 @@ impl HdlLetKindIO { } } -fn check_empty_m_dot(m_dot: Option<(kw::m, Token![.])>, kind: impl ToTokens) -> syn::Result<()> { - if let Some((m, dot_token)) = m_dot { - Err(Error::new_spanned( - quote! {#m #dot_token #kind}, - format_args!( - "{} is a free function, not a method of ModuleBuilder: try removing the `m.`", - kind.to_token_stream() - ), - )) - } else { - Ok(()) - } -} - -fn unwrap_m_dot( - m_dot: Option<(kw::m, Token![.])>, - kind: impl ToTokens, -) -> syn::Result<(kw::m, Token![.])> { - m_dot.ok_or_else(|| { - Error::new_spanned( - &kind, - format_args!( - "{} is a ModuleBuilder method, not a free function: try prefixing it with `m.`", - kind.to_token_stream() - ), - ) - }) -} - -impl HdlLetKindParse for HdlLetKind { +impl HdlLetKindParse for HdlLetKind { type ParsedTy = Option<(Token![:], Box)>; fn parse_ty(input: ParseStream) -> syn::Result { @@ -817,20 +753,16 @@ impl HdlLetKindParse for HdlLetKind { after_ty: Token![=], input: ParseStream, ) -> syn::Result { - let m_dot = if input.peek(kw::m) && input.peek2(Token![.]) { - let m = input.parse()?; - let dot_token = input.parse()?; - Some((m, dot_token)) - } else { - None - }; + let m = input.parse()?; + let dot_token = input.parse()?; let kind: LetFnKind = input.parse()?; match kind { LetFnKind::Input(input_token) => HdlLetKindIO::rest_of_parse( input, parsed_ty, after_ty, - m_dot, + m, + dot_token, ModuleIOKind::Input(input_token), ) .map(Self::IO), @@ -838,7 +770,8 @@ impl HdlLetKindParse for HdlLetKind { input, parsed_ty, after_ty, - m_dot, + m, + dot_token, ModuleIOKind::Output(output), ) .map(Self::IO), @@ -849,23 +782,30 @@ impl HdlLetKindParse for HdlLetKind { "type annotation not allowed for instance", )); } - check_empty_m_dot(m_dot, kind)?; let paren_contents; Ok(Self::Instance(HdlLetKindInstance { + m, + dot_token, instance, paren: parenthesized!(paren_contents in input), module: paren_contents.call(parse_single_fn_arg)?, })) } - LetFnKind::RegBuilder((reg_builder,)) => { - HdlLetKindRegBuilder::rest_of_parse(input, parsed_ty, after_ty, m_dot, reg_builder) - .map(Self::RegBuilder) - } + LetFnKind::RegBuilder((reg_builder,)) => HdlLetKindRegBuilder::rest_of_parse( + input, + parsed_ty, + after_ty, + m, + dot_token, + reg_builder, + ) + .map(Self::RegBuilder), LetFnKind::Wire((wire,)) => { - check_empty_m_dot(m_dot, wire)?; let paren_contents; Ok(Self::Wire(HdlLetKindWire { ty: parsed_ty, + m, + dot_token, wire, paren: parenthesized!(paren_contents in input), ty_expr: paren_contents.call(parse_optional_fn_arg)?, @@ -875,7 +815,8 @@ impl HdlLetKindParse for HdlLetKind { input, parsed_ty, after_ty, - m_dot, + m, + dot_token, MemoryFnName::Memory(fn_name), ) .map(Self::Memory), @@ -883,7 +824,8 @@ impl HdlLetKindParse for HdlLetKind { input, parsed_ty, after_ty, - m_dot, + m, + dot_token, MemoryFnName::MemoryArray(fn_name), ) .map(Self::Memory), @@ -891,7 +833,8 @@ impl HdlLetKindParse for HdlLetKind { input, parsed_ty, after_ty, - m_dot, + m, + dot_token, MemoryFnName::MemoryWithInit(fn_name), ) .map(Self::Memory), @@ -935,34 +878,6 @@ with_debug_clone_and_fold! { } } -impl, I> ParseTypes> for HdlLet { - fn parse_types( - input: &mut HdlLet, - parser: &mut TypesParser<'_>, - ) -> Result { - let HdlLet { - attrs, - hdl_attr, - let_token, - mut_token, - name, - eq_token, - kind, - semi_token, - } = input; - Ok(Self { - attrs: attrs.clone(), - hdl_attr: hdl_attr.clone(), - let_token: *let_token, - mut_token: *mut_token, - name: name.clone(), - eq_token: *eq_token, - kind: T::parse_types(kind, parser)?, - semi_token: *semi_token, - }) - } -} - impl HdlLet { pub(crate) fn try_map( self, @@ -1091,7 +1006,7 @@ fn wrap_ty_with_expr(ty: impl ToTokens) -> Type { fn unwrap_or_static_type(expr: Option, span: Span) -> TokenStream { expr.map(ToTokens::into_token_stream).unwrap_or_else(|| { quote_spanned! {span=> - ::fayalite::ty::StaticType::TYPE + ::fayalite::ty::StaticType::static_type() } }) } @@ -1111,15 +1026,14 @@ impl ToTokens for ImplicitName { } } -struct Visitor<'a> { +struct Visitor { module_kind: ModuleKind, errors: Errors, io: Vec, block_depth: usize, - parsed_generics: &'a ParsedGenerics, } -impl Visitor<'_> { +impl Visitor { fn take_hdl_attr(&mut self, attrs: &mut Vec) -> Option> { self.errors.unwrap_or( HdlAttr::parse_and_take_attr(attrs), @@ -1172,7 +1086,7 @@ impl Visitor<'_> { parse_quote_spanned! {if_token.span=> #(#attrs)* { - let mut __scope = ::fayalite::module::if_(#cond); + let mut __scope = m.if_(#cond); let _: () = #then_branch; let mut __scope = __scope.else_(); let _: () = #else_expr; @@ -1182,7 +1096,7 @@ impl Visitor<'_> { parse_quote_spanned! {if_token.span=> #(#attrs)* { - let mut __scope = ::fayalite::module::if_(#cond); + let mut __scope = m.if_(#cond); let _: () = #then_branch; } } @@ -1243,6 +1157,8 @@ impl Visitor<'_> { eq_token, kind: HdlLetKindInstance { + m, + dot_token, instance, paren, module, @@ -1250,7 +1166,7 @@ impl Visitor<'_> { semi_token, } = hdl_let; self.require_normal_module(instance); - let mut expr = instance.to_token_stream(); + let mut expr = quote! {#m #dot_token #instance}; paren.surround(&mut expr, |expr| { let name_str = ImplicitName { name: &name, @@ -1275,9 +1191,11 @@ impl Visitor<'_> { } fn process_hdl_let_reg_builder(&mut self, hdl_let: HdlLet) -> Local { let name = &hdl_let.name; + let m = hdl_let.kind.m; + let dot = hdl_let.kind.dot_token; let reg_builder = hdl_let.kind.reg_builder; self.require_normal_module(reg_builder); - let mut expr = reg_builder.to_token_stream(); + let mut expr = quote! {#m #dot #reg_builder}; hdl_let.kind.reg_builder_paren.surround(&mut expr, |expr| { let name_str = ImplicitName { name, @@ -1326,10 +1244,12 @@ impl Visitor<'_> { } fn process_hdl_let_wire(&mut self, hdl_let: HdlLet) -> Local { let name = &hdl_let.name; + let m = hdl_let.kind.m; + let dot = hdl_let.kind.dot_token; let wire = hdl_let.kind.wire; self.require_normal_module(wire); let ty_expr = unwrap_or_static_type(hdl_let.kind.ty_expr.as_ref(), wire.span()); - let mut expr = wire.to_token_stream(); + let mut expr = quote! {#m #dot #wire}; hdl_let.kind.paren.surround(&mut expr, |expr| { let name_str = ImplicitName { name, @@ -1359,19 +1279,18 @@ impl Visitor<'_> { } fn process_hdl_let_memory(&mut self, hdl_let: HdlLet) -> Local { let name = &hdl_let.name; + let m = hdl_let.kind.m; + let dot = hdl_let.kind.dot_token; let memory_fn = hdl_let.kind.memory_fn; let memory_fn_name = memory_fn.name(); self.require_normal_module(memory_fn_name); - let mut expr = memory_fn_name.to_token_stream(); + let mut expr = quote! {#m #dot #memory_fn_name}; let (paren, arg) = match memory_fn { MemoryFn::Memory { memory, paren, ty_expr, - } => ( - paren, - unwrap_or_static_type(ty_expr.as_ref(), memory.span()), - ), + } => (paren, unwrap_or_static_type(ty_expr.as_ref(), memory.span())), MemoryFn::MemoryArray { memory_array, paren, @@ -1458,17 +1377,16 @@ impl Visitor<'_> { let value: BigInt = self .errors .ok(base10_digits.parse().map_err(|e| Error::new(span, e)))?; - let bytes = value.to_signed_bytes_le(); - let path = if signed { - known_items::SInt(span).path - } else { - known_items::UInt(span).path + let (negative, bytes) = match value.sign() { + Sign::Minus => (true, value.magnitude().to_bytes_le()), + Sign::NoSign => (false, vec![]), + Sign::Plus => (false, value.magnitude().to_bytes_le()), }; Some(parse_quote_spanned! {span=> - <#path<#width> as ::fayalite::int::BoolOrIntType>::le_bytes_to_expr_wrapping( + ::fayalite::int::make_int_literal::<#signed, #width>( + #negative, &[#(#bytes,)*], - #width, - ) + ).to_int_expr() }) } fn process_literal(&mut self, literal: ExprLit) -> Expr { @@ -1531,7 +1449,7 @@ fn empty_let() -> Local { } } -impl Fold for Visitor<'_> { +impl Fold for Visitor { fn fold_item(&mut self, item: Item) -> Item { // don't process item interiors item @@ -1603,6 +1521,8 @@ impl Fold for Visitor<'_> { Repeat => process_hdl_repeat, Struct => process_hdl_struct, Tuple => process_hdl_tuple, + Call => process_hdl_call, + Path => process_hdl_path, } } } @@ -1616,16 +1536,11 @@ impl Fold for Visitor<'_> { Some(None) => return fold_local(self, let_stmt), Some(Some(HdlAttr { .. })) => {} }; - let hdl_let = syn::parse2::>>(let_stmt.into_token_stream()); + let hdl_let = syn::parse2::(let_stmt.into_token_stream()); let Some(hdl_let) = self.errors.ok(hdl_let) else { return empty_let(); }; - let mut hdl_let = hdl_let.do_fold(self); - let Ok(hdl_let) = - TypesParser::run_with_errors(self.parsed_generics, &mut hdl_let, &mut self.errors) - else { - return empty_let(); - }; + let hdl_let = hdl_let.do_fold(self); self.process_hdl_let(hdl_let) } @@ -1648,14 +1563,12 @@ impl Fold for Visitor<'_> { pub(crate) fn transform_body( module_kind: ModuleKind, mut body: Box, - parsed_generics: &ParsedGenerics, ) -> syn::Result<(Box, Vec)> { let mut visitor = Visitor { module_kind, errors: Errors::new(), io: vec![], block_depth: 0, - parsed_generics, }; *body = syn::fold::fold_block(&mut visitor, *body); visitor.errors.finish()?; diff --git a/crates/fayalite-proc-macros-impl/src/module/transform_body/expand_aggregate_literals.rs b/crates/fayalite-proc-macros-impl/src/module/transform_body/expand_aggregate_literals.rs index 00ee706..bfa4a51 100644 --- a/crates/fayalite-proc-macros-impl/src/module/transform_body/expand_aggregate_literals.rs +++ b/crates/fayalite-proc-macros-impl/src/module/transform_body/expand_aggregate_literals.rs @@ -1,13 +1,336 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // See Notices.txt for copyright information -use crate::{module::transform_body::Visitor, HdlAttr}; -use quote::{format_ident, quote_spanned}; +use crate::{module::transform_body::Visitor, options, Errors, HdlAttr, PairsIterExt}; +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote_spanned, ToTokens, TokenStreamExt}; use syn::{ - parse::Nothing, parse_quote, parse_quote_spanned, spanned::Spanned, Expr, ExprArray, ExprPath, - ExprRepeat, ExprStruct, ExprTuple, FieldValue, TypePath, + parse::Nothing, + parse_quote, parse_quote_spanned, + punctuated::{Pair, Punctuated}, + spanned::Spanned, + token::{Brace, Paren}, + Attribute, Expr, ExprArray, ExprCall, ExprGroup, ExprPath, ExprRepeat, ExprStruct, ExprTuple, + FieldValue, Ident, Index, Member, Path, PathArguments, PathSegment, Token, TypePath, }; -impl Visitor<'_> { +options! { + #[options = AggregateLiteralOptions] + #[no_ident_fragment] + pub(crate) enum AggregateLiteralOption { + Struct(struct_), + Enum(enum_), + } +} + +#[derive(Clone, Debug)] +pub(crate) struct StructOrEnumPath { + pub(crate) ty: TypePath, + pub(crate) variant: Option<(TypePath, Ident)>, +} + +#[derive(Debug, Copy, Clone)] +pub(crate) struct SingleSegmentVariant { + pub(crate) name: &'static str, + pub(crate) make_type_path: fn(Span, &PathArguments) -> Path, +} + +impl StructOrEnumPath { + pub(crate) const SINGLE_SEGMENT_VARIANTS: &'static [SingleSegmentVariant] = { + fn make_option_type_path(span: Span, arguments: &PathArguments) -> Path { + let arguments = if arguments.is_none() { + quote_spanned! {span=> + <_> + } + } else { + arguments.to_token_stream() + }; + parse_quote_spanned! {span=> + ::fayalite::__std::option::Option #arguments + } + } + fn make_result_type_path(span: Span, arguments: &PathArguments) -> Path { + let arguments = if arguments.is_none() { + quote_spanned! {span=> + <_, _> + } + } else { + arguments.to_token_stream() + }; + parse_quote_spanned! {span=> + ::fayalite::__std::result::Result #arguments + } + } + &[ + SingleSegmentVariant { + name: "Some", + make_type_path: make_option_type_path, + }, + SingleSegmentVariant { + name: "None", + make_type_path: make_option_type_path, + }, + SingleSegmentVariant { + name: "Ok", + make_type_path: make_result_type_path, + }, + SingleSegmentVariant { + name: "Err", + make_type_path: make_result_type_path, + }, + ] + }; + pub(crate) fn new( + errors: &mut Errors, + path: TypePath, + options: &AggregateLiteralOptions, + ) -> Result { + let Path { + leading_colon, + segments, + } = &path.path; + let qself_position = path.qself.as_ref().map(|qself| qself.position).unwrap_or(0); + let variant_name = if qself_position < segments.len() { + Some(segments.last().unwrap().ident.clone()) + } else { + None + }; + let enum_type = 'guess_enum_type: { + if options.enum_.is_some() { + if let Some((struct_,)) = options.struct_ { + errors.error( + struct_, + "can't specify both #[hdl(enum)] and #[hdl(struct)]", + ); + } + break 'guess_enum_type Some(None); + } + if options.struct_.is_some() { + break 'guess_enum_type None; + } + if path.qself.is_none() && leading_colon.is_none() && segments.len() == 1 { + let PathSegment { ident, arguments } = &segments[0]; + for &SingleSegmentVariant { + name, + make_type_path, + } in Self::SINGLE_SEGMENT_VARIANTS + { + if ident == name { + break 'guess_enum_type Some(Some(TypePath { + qself: None, + path: make_type_path(ident.span(), arguments), + })); + } + } + } + if segments.len() == qself_position + 2 + && segments[qself_position + 1].arguments.is_none() + && (path.qself.is_some() + || segments[qself_position].ident.to_string().as_bytes()[0] + .is_ascii_uppercase()) + { + let mut ty = path.clone(); + ty.path.segments.pop(); + ty.path.segments.pop_punct(); + break 'guess_enum_type Some(Some(ty)); + } + None + }; + if let Some(enum_type) = enum_type { + let ty = if let Some(enum_type) = enum_type { + enum_type + } else { + if qself_position >= segments.len() { + errors.error(path, "#[hdl]: can't figure out enum's type"); + return Err(()); + } + let mut ty = path.clone(); + ty.path.segments.pop(); + ty.path.segments.pop_punct(); + ty + }; + let Some(variant_name) = variant_name else { + errors.error(path, "#[hdl]: can't figure out enum's variant name"); + return Err(()); + }; + Ok(Self { + ty, + variant: Some((path, variant_name)), + }) + } else { + Ok(Self { + ty: path, + variant: None, + }) + } + } +} + +#[derive(Copy, Clone, Debug)] +pub(crate) enum BraceOrParen { + Brace(Brace), + Paren(Paren), +} + +impl BraceOrParen { + pub(crate) fn surround(self, tokens: &mut TokenStream, f: impl FnOnce(&mut TokenStream)) { + match self { + BraceOrParen::Brace(v) => v.surround(tokens, f), + BraceOrParen::Paren(v) => v.surround(tokens, f), + } + } +} + +#[derive(Debug, Clone)] +pub(crate) struct StructOrEnumLiteralField { + pub(crate) attrs: Vec, + pub(crate) member: Member, + pub(crate) colon_token: Option, + pub(crate) expr: Expr, +} + +#[derive(Debug, Clone)] +pub(crate) struct StructOrEnumLiteral { + pub(crate) attrs: Vec, + pub(crate) path: TypePath, + pub(crate) brace_or_paren: BraceOrParen, + pub(crate) fields: Punctuated, + pub(crate) dot2_token: Option, + pub(crate) rest: Option>, +} + +impl StructOrEnumLiteral { + pub(crate) fn map_field_exprs(self, mut f: impl FnMut(Expr) -> Expr) -> Self { + self.map_fields(|mut field| { + field.expr = f(field.expr); + field + }) + } + pub(crate) fn map_fields( + self, + f: impl FnMut(StructOrEnumLiteralField) -> StructOrEnumLiteralField, + ) -> Self { + let Self { + attrs, + path, + brace_or_paren, + fields, + dot2_token, + rest, + } = self; + let fields = fields.into_pairs().map_pair_value(f).collect(); + Self { + attrs, + path, + brace_or_paren, + fields, + dot2_token, + rest, + } + } +} + +impl From for StructOrEnumLiteral { + fn from(value: ExprStruct) -> Self { + let ExprStruct { + attrs, + qself, + path, + brace_token, + fields, + dot2_token, + rest, + } = value; + Self { + attrs, + path: TypePath { qself, path }, + brace_or_paren: BraceOrParen::Brace(brace_token), + fields: fields + .into_pairs() + .map_pair_value( + |FieldValue { + attrs, + member, + colon_token, + expr, + }| StructOrEnumLiteralField { + attrs, + member, + colon_token, + expr, + }, + ) + .collect(), + dot2_token, + rest, + } + } +} + +fn expr_to_member(expr: &Expr) -> Option { + syn::parse2(expr.to_token_stream()).ok() +} + +impl ToTokens for StructOrEnumLiteral { + fn to_tokens(&self, tokens: &mut TokenStream) { + let Self { + attrs, + path, + brace_or_paren, + fields, + dot2_token, + rest, + } = self; + tokens.append_all(attrs); + path.to_tokens(tokens); + brace_or_paren.surround(tokens, |tokens| { + match brace_or_paren { + BraceOrParen::Brace(_) => { + for ( + StructOrEnumLiteralField { + attrs, + member, + mut colon_token, + expr, + }, + comma, + ) in fields.pairs().map(|v| v.into_tuple()) + { + tokens.append_all(attrs); + if Some(member) != expr_to_member(expr).as_ref() { + colon_token = Some(::default()); + } + member.to_tokens(tokens); + colon_token.to_tokens(tokens); + expr.to_tokens(tokens); + comma.to_tokens(tokens); + } + } + BraceOrParen::Paren(_) => { + for ( + StructOrEnumLiteralField { + attrs, + member: _, + colon_token: _, + expr, + }, + comma, + ) in fields.pairs().map(|v| v.into_tuple()) + { + tokens.append_all(attrs); + expr.to_tokens(tokens); + comma.to_tokens(tokens); + } + } + } + if let Some(rest) = rest { + dot2_token.unwrap_or_default().to_tokens(tokens); + rest.to_tokens(tokens); + } + }); + } +} + +impl Visitor { pub(crate) fn process_hdl_array( &mut self, hdl_attr: HdlAttr, @@ -33,61 +356,100 @@ impl Visitor<'_> { }; parse_quote! {::fayalite::expr::ToExpr::to_expr(&#expr_repeat)} } + pub(crate) fn process_struct_enum( + &mut self, + hdl_attr: HdlAttr, + mut literal: StructOrEnumLiteral, + ) -> Expr { + let span = hdl_attr.hdl.span; + if let Some(rest) = literal.rest.take() { + self.errors + .error(rest, "#[hdl] struct functional update syntax not supported"); + } + let mut next_var = 0usize; + let mut new_var = || -> Ident { + let retval = format_ident!("__v{}", next_var, span = span); + next_var += 1; + retval + }; + let infallible_var = new_var(); + let retval_var = new_var(); + let mut lets = vec![]; + let mut build_steps = vec![]; + let literal = literal.map_field_exprs(|expr| { + let field_var = new_var(); + lets.push(quote_spanned! {span=> + let #field_var = ::fayalite::expr::ToExpr::to_expr(&#expr); + }); + parse_quote! { #field_var } + }); + let Ok(StructOrEnumPath { ty, variant }) = + StructOrEnumPath::new(&mut self.errors, literal.path.clone(), &hdl_attr.body) + else { + return parse_quote_spanned! {span=> + {} + }; + }; + for StructOrEnumLiteralField { + attrs: _, + member, + colon_token: _, + expr, + } in literal.fields.iter() + { + let field_fn = format_ident!("field_{}", member); + build_steps.push(quote_spanned! {span=> + let #retval_var = #retval_var.#field_fn(#expr); + }); + } + let check_literal = literal.map_field_exprs(|expr| { + parse_quote_spanned! {span=> + ::fayalite::expr::value_from_expr_type(#expr, #infallible_var) + } + }); + let make_expr_fn = if let Some((_variant_path, variant_ident)) = &variant { + let variant_fn = format_ident!("variant_{}", variant_ident); + build_steps.push(quote_spanned! {span=> + let #retval_var = #retval_var.#variant_fn(); + }); + quote_spanned! {span=> + ::fayalite::expr::make_enum_expr + } + } else { + build_steps.push(quote_spanned! {span=> + let #retval_var = #retval_var.build(); + }); + quote_spanned! {span=> + ::fayalite::expr::make_bundle_expr + } + }; + let variant_or_type = + variant.map_or_else(|| ty.clone(), |(variant_path, _variant_ident)| variant_path); + parse_quote_spanned! {span=> + { + #(#lets)* + #make_expr_fn::<#ty>(|#infallible_var| { + let #retval_var = #check_literal; + #[allow(unreachable_code)] + match #retval_var { + #variant_or_type { .. } => #retval_var, + #[allow(unreachable_patterns)] + _ => match #infallible_var {}, + } + }, |#retval_var| { + #(#build_steps)* + #retval_var + }) + } + } + } pub(crate) fn process_hdl_struct( &mut self, - hdl_attr: HdlAttr, + hdl_attr: HdlAttr, expr_struct: ExprStruct, ) -> Expr { self.require_normal_module(&hdl_attr); - let name_span = expr_struct.path.segments.last().unwrap().ident.span(); - let builder_ident = format_ident!("__builder", span = name_span); - let empty_builder = if expr_struct.qself.is_some() - || expr_struct - .path - .segments - .iter() - .any(|seg| !seg.arguments.is_none()) - { - let ty = TypePath { - qself: expr_struct.qself, - path: expr_struct.path, - }; - let builder_ty = quote_spanned! {name_span=> - <#ty as ::fayalite::bundle::BundleType>::Builder - }; - quote_spanned! {name_span=> - <#builder_ty as ::fayalite::__std::default::Default>::default() - } - } else { - let path = ExprPath { - attrs: vec![], - qself: expr_struct.qself, - path: expr_struct.path, - }; - quote_spanned! {name_span=> - #path::__bundle_builder() - } - }; - let field_calls = Vec::from_iter(expr_struct.fields.iter().map( - |FieldValue { - attrs: _, - member, - colon_token: _, - expr, - }| { - let field_fn = format_ident!("field_{}", member); - quote_spanned! {member.span()=> - let #builder_ident = #builder_ident.#field_fn(#expr); - } - }, - )); - parse_quote_spanned! {name_span=> - { - let #builder_ident = #empty_builder; - #(#field_calls)* - ::fayalite::expr::ToExpr::to_expr(&#builder_ident) - } - } + self.process_struct_enum(hdl_attr, expr_struct.into()) } pub(crate) fn process_hdl_tuple( &mut self, @@ -99,4 +461,80 @@ impl Visitor<'_> { ::fayalite::expr::ToExpr::to_expr(&#expr_tuple) } } + pub(crate) fn process_hdl_path( + &mut self, + hdl_attr: HdlAttr, + expr_path: ExprPath, + ) -> Expr { + self.require_normal_module(hdl_attr); + parse_quote_spanned! {expr_path.span()=> + ::fayalite::expr::ToExpr::to_expr(&#expr_path) + } + } + pub(crate) fn process_hdl_call( + &mut self, + hdl_attr: HdlAttr, + expr_call: ExprCall, + ) -> Expr { + self.require_normal_module(&hdl_attr); + let ExprCall { + attrs: mut literal_attrs, + func, + paren_token, + args, + } = expr_call; + let mut path_expr = *func; + let path = loop { + break match path_expr { + Expr::Group(ExprGroup { + attrs, + group_token: _, + expr, + }) => { + literal_attrs.extend(attrs); + path_expr = *expr; + continue; + } + Expr::Path(ExprPath { attrs, qself, path }) => { + literal_attrs.extend(attrs); + TypePath { qself, path } + } + _ => { + self.errors.error(&path_expr, "missing tuple struct's name"); + return parse_quote_spanned! {path_expr.span()=> + {} + }; + } + }; + }; + let fields = args + .into_pairs() + .enumerate() + .map(|(index, p)| { + let (expr, comma) = p.into_tuple(); + let mut index = Index::from(index); + index.span = hdl_attr.hdl.span; + Pair::new( + StructOrEnumLiteralField { + attrs: vec![], + member: Member::Unnamed(index), + colon_token: None, + expr, + }, + comma, + ) + }) + .collect(); + self.process_struct_enum( + hdl_attr, + StructOrEnumLiteral { + attrs: literal_attrs, + path, + brace_or_paren: BraceOrParen::Paren(paren_token), + fields, + dot2_token: None, + rest: None, + }, + ) + } } diff --git a/crates/fayalite-proc-macros-impl/src/module/transform_body/expand_match.rs b/crates/fayalite-proc-macros-impl/src/module/transform_body/expand_match.rs index ae21a73..fe1a895 100644 --- a/crates/fayalite-proc-macros-impl/src/module/transform_body/expand_match.rs +++ b/crates/fayalite-proc-macros-impl/src/module/transform_body/expand_match.rs @@ -1,21 +1,24 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // See Notices.txt for copyright information use crate::{ - fold::{impl_fold, DoFold}, - module::transform_body::{with_debug_clone_and_fold, Visitor}, + fold::impl_fold, + module::transform_body::{ + expand_aggregate_literals::{AggregateLiteralOptions, StructOrEnumPath}, + with_debug_clone_and_fold, Visitor, + }, Errors, HdlAttr, PairsIterExt, }; use proc_macro2::{Span, TokenStream}; -use quote::{format_ident, quote_spanned, ToTokens, TokenStreamExt}; +use quote::{ToTokens, TokenStreamExt}; use syn::{ fold::{fold_arm, fold_expr_match, fold_pat, Fold}, parse::Nothing, parse_quote_spanned, - punctuated::Punctuated, + punctuated::{Pair, Punctuated}, spanned::Spanned, token::{Brace, Paren}, - Arm, Attribute, Expr, ExprMatch, FieldPat, Ident, Member, Pat, PatIdent, PatOr, PatParen, - PatPath, PatRest, PatStruct, PatTupleStruct, PatWild, Path, PathSegment, Token, TypePath, + Arm, Attribute, Expr, ExprMatch, FieldPat, Ident, Index, Member, Pat, PatIdent, PatOr, + PatParen, PatPath, PatRest, PatStruct, PatTupleStruct, PatWild, Path, Token, TypePath, }; with_debug_clone_and_fold! { @@ -78,7 +81,7 @@ impl ToTokens for MatchPatWild { with_debug_clone_and_fold! { struct MatchPatStructField<> { - field_name: Ident, + member: Member, colon_token: Option, pat: MatchPatSimple, } @@ -87,19 +90,12 @@ with_debug_clone_and_fold! { impl ToTokens for MatchPatStructField { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { - field_name, + member, colon_token, pat, } = self; - field_name.to_tokens(tokens); - if let (None, MatchPatSimple::Binding(MatchPatBinding { ident })) = (colon_token, pat) { - if field_name == ident { - return; - } - } - colon_token - .unwrap_or_else(|| Token![:](field_name.span())) - .to_tokens(tokens); + member.to_tokens(tokens); + colon_token.to_tokens(tokens); pat.to_tokens(tokens); } } @@ -112,16 +108,8 @@ impl MatchPatStructField { colon_token, pat, } = field_pat; - let field_name = if let Member::Named(field_name) = member { - field_name - } else { - state - .errors - .error(&member, "field name must not be a number"); - format_ident!("_{}", member) - }; Ok(Self { - field_name, + member, colon_token, pat: MatchPatSimple::parse(state, *pat)?, }) @@ -130,8 +118,7 @@ impl MatchPatStructField { with_debug_clone_and_fold! { struct MatchPatStruct<> { - match_span: Span, - path: Path, + resolved_path: Path, brace_token: Brace, fields: Punctuated, rest: Option, @@ -141,16 +128,12 @@ with_debug_clone_and_fold! { impl ToTokens for MatchPatStruct { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { - match_span, - path, + resolved_path, brace_token, fields, rest, } = self; - quote_spanned! {*match_span=> - __MatchTy::<#path> - } - .to_tokens(tokens); + resolved_path.to_tokens(tokens); brace_token.surround(tokens, |tokens| { fields.to_tokens(tokens); rest.to_tokens(tokens); @@ -158,35 +141,6 @@ impl ToTokens for MatchPatStruct { } } -with_debug_clone_and_fold! { - struct MatchPatEnumVariant<> { - match_span: Span, - variant_path: Path, - enum_path: Path, - variant_name: Ident, - field: Option<(Paren, MatchPatSimple)>, - } -} - -impl ToTokens for MatchPatEnumVariant { - fn to_tokens(&self, tokens: &mut TokenStream) { - let Self { - match_span, - variant_path: _, - enum_path, - variant_name, - field, - } = self; - quote_spanned! {*match_span=> - __MatchTy::<#enum_path>::#variant_name - } - .to_tokens(tokens); - if let Some((paren_token, field)) = field { - paren_token.surround(tokens, |tokens| field.to_tokens(tokens)); - } - } -} - #[derive(Debug, Clone)] enum MatchPatSimple { Paren(MatchPatParen), @@ -215,70 +169,21 @@ impl ToTokens for MatchPatSimple { } } -struct EnumPath { - variant_path: Path, - enum_path: Path, - variant_name: Ident, -} - -fn parse_enum_path(variant_path: TypePath) -> Result { - let TypePath { - qself: None, - path: variant_path, - } = variant_path - else { - return Err(variant_path); - }; - if variant_path.is_ident("HdlNone") || variant_path.is_ident("HdlSome") { - let ident = variant_path.get_ident().unwrap(); - return Ok(EnumPath { - enum_path: parse_quote_spanned! {ident.span()=> - ::fayalite::enum_::HdlOption::<_> - }, - variant_name: ident.clone(), - variant_path, - }); - } - if variant_path.segments.len() < 2 { - return Err(TypePath { - qself: None, - path: variant_path, - }); - } - let mut enum_path = variant_path.clone(); - let PathSegment { - ident: variant_name, - arguments, - } = enum_path.segments.pop().unwrap().into_value(); - if !arguments.is_none() { - return Err(TypePath { - qself: None, - path: variant_path, - }); - } - enum_path.segments.pop_punct(); - Ok(EnumPath { - variant_path, - enum_path, - variant_name, - }) -} - -fn parse_enum_ident(ident: Ident) -> Result { - parse_enum_path(TypePath { - qself: None, - path: ident.into(), - }) - .map_err(|p| p.path.segments.into_iter().next().unwrap().ident) +fn is_pat_ident_a_struct_or_enum_name(ident: &Ident) -> bool { + ident + .to_string() + .starts_with(|ch: char| ch.is_ascii_uppercase()) } trait ParseMatchPat: Sized { fn simple(v: MatchPatSimple) -> Self; fn or(v: MatchPatOr) -> Self; fn paren(v: MatchPatParen) -> Self; - fn struct_(state: &mut HdlMatchParseState<'_>, v: MatchPatStruct) -> Result; - fn enum_variant(state: &mut HdlMatchParseState<'_>, v: MatchPatEnumVariant) - -> Result; + fn struct_( + state: &mut HdlMatchParseState<'_>, + v: MatchPatStruct, + struct_error_spanned: &dyn ToTokens, + ) -> Result; fn parse(state: &mut HdlMatchParseState<'_>, pat: Pat) -> Result { match pat { Pat::Ident(PatIdent { @@ -303,24 +208,26 @@ trait ParseMatchPat: Sized { .errors .error(at_token, "@ not allowed in #[hdl] patterns"); } - match parse_enum_ident(ident) { - Ok(EnumPath { - variant_path, - enum_path, - variant_name, - }) => Self::enum_variant( + if is_pat_ident_a_struct_or_enum_name(&ident) { + let ident_span = ident.span(); + let resolved_path = state.resolve_enum_struct_path(TypePath { + qself: None, + path: ident.clone().into(), + })?; + Self::struct_( state, - MatchPatEnumVariant { - match_span: state.match_span, - variant_path, - enum_path, - variant_name, - field: None, + MatchPatStruct { + resolved_path, + brace_token: Brace(ident_span), + fields: Punctuated::new(), + rest: None, }, - ), - Err(ident) => Ok(Self::simple(MatchPatSimple::Binding(MatchPatBinding { + &ident, + ) + } else { + Ok(Self::simple(MatchPatSimple::Binding(MatchPatBinding { ident, - }))), + }))) } } Pat::Or(PatOr { @@ -347,22 +254,18 @@ trait ParseMatchPat: Sized { qself, path, }) => { - let EnumPath { - variant_path, - enum_path, - variant_name, - } = parse_enum_path(TypePath { qself, path }).map_err(|path| { - state.errors.error(path, "unsupported enum variant path"); - })?; - Self::enum_variant( + let path = TypePath { qself, path }; + let path_span = path.span(); + let resolved_path = state.resolve_enum_struct_path(path.clone())?; + Self::struct_( state, - MatchPatEnumVariant { - match_span: state.match_span, - variant_path, - enum_path, - variant_name, - field: None, + MatchPatStruct { + resolved_path, + brace_token: Brace(path_span), + fields: Punctuated::new(), + rest: None, }, + &path, ) } Pat::Struct(PatStruct { @@ -379,17 +282,12 @@ trait ParseMatchPat: Sized { MatchPatStructField::parse(state, field_pat).ok() }) .collect(); - if qself.is_some() { - state - .errors - .error(TypePath { qself, path }, "unsupported struct path"); - return Err(()); - } + let path = TypePath { qself, path }; + let resolved_path = state.resolve_enum_struct_path(path.clone())?; Self::struct_( state, MatchPatStruct { - match_span: state.match_span, - path, + resolved_path, brace_token, fields, rest: rest.map( @@ -399,6 +297,7 @@ trait ParseMatchPat: Sized { }| dot2_token, ), }, + &path, ) } Pat::TupleStruct(PatTupleStruct { @@ -408,45 +307,45 @@ trait ParseMatchPat: Sized { paren_token, mut elems, }) => { - let EnumPath { - variant_path, - enum_path, - variant_name, - } = parse_enum_path(TypePath { qself, path }).map_err(|path| { - state.errors.error(path, "unsupported enum variant path"); - })?; - if elems.is_empty() { - let mut tokens = TokenStream::new(); - paren_token.surround(&mut tokens, |_| {}); - state.errors.error( - tokens, - "field-less enum variants must not be matched using parenthesis", - ); - } - if elems.len() != 1 { - state.errors.error( - variant_path, - "enum variant pattern must have exactly one field", - ); - return Err(()); - } - let field = elems.pop().unwrap().into_value(); - let field = if let Pat::Rest(rest) = field { - MatchPatSimple::Wild(MatchPatWild { - underscore_token: Token![_](rest.dot2_token.span()), - }) + let rest = if let Some(&Pat::Rest(PatRest { + attrs: _, + dot2_token, + })) = elems.last() + { + elems.pop(); + Some(dot2_token) } else { - MatchPatSimple::parse(state, field)? + None }; - Self::enum_variant( + let fields = elems + .into_pairs() + .enumerate() + .filter_map(|(index, pair)| { + let (pat, punct) = pair.into_tuple(); + let pat = MatchPatSimple::parse(state, pat).ok()?; + let mut index = Index::from(index); + index.span = state.span; + let field = MatchPatStructField { + member: index.into(), + colon_token: Some(Token![:](state.span)), + pat, + }; + Some(Pair::new(field, punct)) + }) + .collect(); + let path = TypePath { qself, path }; + let resolved_path = state.resolve_enum_struct_path(path.clone())?; + Self::struct_( state, - MatchPatEnumVariant { - match_span: state.match_span, - variant_path, - enum_path, - variant_name, - field: Some((paren_token, field)), + MatchPatStruct { + resolved_path, + brace_token: Brace { + span: paren_token.span, + }, + fields, + rest, }, + &path, ) } Pat::Rest(_) => { @@ -488,21 +387,14 @@ impl ParseMatchPat for MatchPatSimple { Self::Paren(v) } - fn struct_(state: &mut HdlMatchParseState<'_>, v: MatchPatStruct) -> Result { - state.errors.error( - v.path, - "matching structs is not yet implemented inside structs/enums in #[hdl] patterns", - ); - Err(()) - } - - fn enum_variant( + fn struct_( state: &mut HdlMatchParseState<'_>, - v: MatchPatEnumVariant, + _v: MatchPatStruct, + struct_error_spanned: &dyn ToTokens, ) -> Result { state.errors.error( - v.variant_path, - "matching enum variants is not yet implemented inside structs/enums in #[hdl] patterns", + struct_error_spanned, + "not yet implemented inside structs/enums in #[hdl] patterns", ); Err(()) } @@ -514,7 +406,6 @@ enum MatchPat { Or(MatchPatOr), Paren(MatchPatParen), Struct(MatchPatStruct), - EnumVariant(MatchPatEnumVariant), } impl_fold! { @@ -523,7 +414,6 @@ impl_fold! { Or(MatchPatOr), Paren(MatchPatParen), Struct(MatchPatStruct), - EnumVariant(MatchPatEnumVariant), } } @@ -540,15 +430,12 @@ impl ParseMatchPat for MatchPat { Self::Paren(v) } - fn struct_(_state: &mut HdlMatchParseState<'_>, v: MatchPatStruct) -> Result { - Ok(Self::Struct(v)) - } - - fn enum_variant( + fn struct_( _state: &mut HdlMatchParseState<'_>, - v: MatchPatEnumVariant, + v: MatchPatStruct, + _struct_error_spanned: &dyn ToTokens, ) -> Result { - Ok(Self::EnumVariant(v)) + Ok(Self::Struct(v)) } } @@ -559,7 +446,6 @@ impl ToTokens for MatchPat { Self::Or(v) => v.to_tokens(tokens), Self::Paren(v) => v.to_tokens(tokens), Self::Struct(v) => v.to_tokens(tokens), - Self::EnumVariant(v) => v.to_tokens(tokens), } } } @@ -625,96 +511,23 @@ impl Fold for RewriteAsCheckMatch { i.colon_token = Some(Token![:](i.member.span())); i } - fn fold_pat(&mut self, pat: Pat) -> Pat { - match pat { - Pat::Ident(mut pat_ident) => match parse_enum_ident(pat_ident.ident) { - Ok(EnumPath { - variant_path: _, - enum_path, - variant_name, - }) => parse_quote_spanned! {self.span=> - __MatchTy::<#enum_path>::#variant_name {} - }, - Err(ident) => { - pat_ident.ident = ident; - Pat::Ident(self.fold_pat_ident(pat_ident)) - } - }, - Pat::Path(PatPath { - attrs: _, - qself, - path, - }) => match parse_enum_path(TypePath { qself, path }) { - Ok(EnumPath { - variant_path: _, - enum_path, - variant_name, - }) => parse_quote_spanned! {self.span=> - __MatchTy::<#enum_path>::#variant_name {} - }, - Err(type_path) => parse_quote_spanned! {self.span=> - __MatchTy::<#type_path> {} - }, - }, - Pat::Struct(PatStruct { - attrs: _, - qself, - path, - brace_token, - fields, - rest, - }) => { - let type_path = TypePath { qself, path }; - let path = parse_quote_spanned! {self.span=> - __MatchTy::<#type_path> - }; - let fields = fields.do_fold(self); - Pat::Struct(PatStruct { - attrs: vec![], - qself: None, - path, - brace_token, - fields, - rest, - }) - } - Pat::TupleStruct(PatTupleStruct { + fn fold_pat(&mut self, i: Pat) -> Pat { + match i { + Pat::Ident(PatIdent { attrs, - qself, - path, - paren_token, - elems, - }) => match parse_enum_path(TypePath { qself, path }) { - Ok(EnumPath { - variant_path: _, - enum_path, - variant_name, - }) => { - let path = parse_quote_spanned! {self.span=> - __MatchTy::<#enum_path>::#variant_name - }; - let elems = Punctuated::from_iter( - elems.into_pairs().map_pair_value(|p| fold_pat(self, p)), - ); - Pat::TupleStruct(PatTupleStruct { - attrs, - qself: None, - path, - paren_token, - elems, - }) + by_ref, + mutability, + ident, + subpat: None, + }) if is_pat_ident_a_struct_or_enum_name(&ident) => { + parse_quote_spanned! {ident.span()=> + #(#attrs)* + #by_ref + #mutability + #ident {} } - Err(TypePath { qself, path }) => { - Pat::TupleStruct(self.fold_pat_tuple_struct(PatTupleStruct { - attrs, - qself, - path, - paren_token, - elems, - })) - } - }, - _ => fold_pat(self, pat), + } + _ => fold_pat(self, i), } } fn fold_pat_ident(&mut self, mut i: PatIdent) -> PatIdent { @@ -742,11 +555,27 @@ impl Fold for RewriteAsCheckMatch { } struct HdlMatchParseState<'a> { - match_span: Span, errors: &'a mut Errors, + span: Span, } -impl Visitor<'_> { +impl HdlMatchParseState<'_> { + fn resolve_enum_struct_path(&mut self, path: TypePath) -> Result { + let StructOrEnumPath { ty, variant } = + StructOrEnumPath::new(self.errors, path, &AggregateLiteralOptions::default())?; + Ok(if let Some((_variant_path, variant_name)) = variant { + parse_quote_spanned! {self.span=> + __MatchTy::<#ty>::#variant_name + } + } else { + parse_quote_spanned! {self.span=> + __MatchTy::<#ty> + } + }) + } +} + +impl Visitor { pub(crate) fn process_hdl_match( &mut self, _hdl_attr: HdlAttr, @@ -763,22 +592,23 @@ impl Visitor<'_> { } = expr_match; self.require_normal_module(match_token); let mut state = HdlMatchParseState { - match_span: span, errors: &mut self.errors, + span, }; let arms = Vec::from_iter( arms.into_iter() .filter_map(|arm| MatchArm::parse(&mut state, arm).ok()), ); - let expr = quote_spanned! {span=> + parse_quote_spanned! {span=> { - type __MatchTy = ::MatchVariant; + type __MatchTy = + <::Type as ::fayalite::ty::Type>::MatchVariant; let __match_expr = ::fayalite::expr::ToExpr::to_expr(&(#expr)); ::fayalite::expr::check_match_expr(__match_expr, |__match_value, __infallible| { #[allow(unused_variables)] #check_match }); - for __match_variant in ::fayalite::module::match_(__match_expr) { + for __match_variant in m.match_(__match_expr) { let (__match_variant, __scope) = ::fayalite::ty::MatchVariantAndInactiveScope::match_activate_scope( __match_variant, @@ -788,7 +618,6 @@ impl Visitor<'_> { } } } - }; - syn::parse2(expr).unwrap() + } } } diff --git a/crates/fayalite-proc-macros-impl/src/value_derive_common.rs b/crates/fayalite-proc-macros-impl/src/value_derive_common.rs new file mode 100644 index 0000000..9f495ff --- /dev/null +++ b/crates/fayalite-proc-macros-impl/src/value_derive_common.rs @@ -0,0 +1,761 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// See Notices.txt for copyright information +use crate::{fold::impl_fold, kw, Errors, HdlAttr}; +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote, quote_spanned, ToTokens}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use syn::{ + fold::{fold_generics, Fold}, + parse::{Parse, ParseStream}, + parse_quote, parse_quote_spanned, + punctuated::Punctuated, + spanned::Spanned, + token::{Brace, Paren, Where}, + Block, ConstParam, Expr, Field, Fields, FieldsNamed, FieldsUnnamed, GenericParam, Generics, + Ident, Index, ItemImpl, Lifetime, LifetimeParam, Member, Path, Token, Type, TypeParam, + TypePath, Visibility, WhereClause, WherePredicate, +}; + +#[derive(Clone, Debug)] +pub(crate) struct Bounds(pub(crate) Punctuated); + +impl_fold! { + struct Bounds<>(Punctuated); +} + +impl Parse for Bounds { + fn parse(input: ParseStream) -> syn::Result { + Ok(Bounds(Punctuated::parse_terminated(input)?)) + } +} + +impl From> for Bounds { + fn from(value: Option) -> Self { + Self(value.map_or_else(Punctuated::new, |v| v.predicates)) + } +} + +impl ToTokens for Bounds { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.0.to_tokens(tokens) + } +} + +#[derive(Debug, Clone)] +pub(crate) struct ParsedField { + pub(crate) options: HdlAttr, + pub(crate) vis: Visibility, + pub(crate) name: Member, + pub(crate) ty: Type, +} + +impl ParsedField { + pub(crate) fn var_name(&self) -> Ident { + format_ident!("__v_{}", self.name) + } +} + +pub(crate) fn get_field_name( + index: usize, + name: Option, + ty_span: impl FnOnce() -> Span, +) -> Member { + match name { + Some(name) => Member::Named(name), + None => Member::Unnamed(Index { + index: index as _, + span: ty_span(), + }), + } +} + +pub(crate) fn get_field_names(fields: &Fields) -> impl Iterator + '_ { + fields + .iter() + .enumerate() + .map(|(index, field)| get_field_name(index, field.ident.clone(), || field.ty.span())) +} + +impl ParsedField { + pub(crate) fn parse_fields( + errors: &mut Errors, + fields: &mut Fields, + in_enum: bool, + ) -> (FieldsKind, Vec>) { + let mut unit_fields = Punctuated::new(); + let (fields_kind, fields) = match fields { + Fields::Named(fields) => (FieldsKind::Named(fields.brace_token), &mut fields.named), + Fields::Unnamed(fields) => { + (FieldsKind::Unnamed(fields.paren_token), &mut fields.unnamed) + } + Fields::Unit => (FieldsKind::Unit, &mut unit_fields), + }; + let fields = fields + .iter_mut() + .enumerate() + .map(|(index, field)| { + let options = errors + .unwrap_or_default(HdlAttr::parse_and_take_attr(&mut field.attrs)) + .unwrap_or_default(); + let name = get_field_name(index, field.ident.clone(), || field.ty.span()); + if in_enum && !matches!(field.vis, Visibility::Inherited) { + errors.error(&field.vis, "field visibility not allowed in enums"); + } + ParsedField { + options, + vis: field.vis.clone(), + name, + ty: field.ty.clone(), + } + }) + .collect(); + (fields_kind, fields) + } +} + +#[derive(Copy, Clone, Debug)] +pub(crate) enum FieldsKind { + Unit, + Named(Brace), + Unnamed(Paren), +} + +impl FieldsKind { + pub(crate) fn into_fields_named( + brace_token: Brace, + fields: impl IntoIterator, + ) -> Fields { + Fields::Named(FieldsNamed { + brace_token, + named: Punctuated::from_iter(fields), + }) + } + pub(crate) fn into_fields_unnamed( + paren_token: Paren, + fields: impl IntoIterator, + ) -> Fields { + Fields::Unnamed(FieldsUnnamed { + paren_token, + unnamed: Punctuated::from_iter(fields), + }) + } + pub(crate) fn into_fields(self, fields: impl IntoIterator) -> Fields { + match self { + FieldsKind::Unit => { + let mut fields = fields.into_iter().peekable(); + let Some(first_field) = fields.peek() else { + return Fields::Unit; + }; + if first_field.ident.is_some() { + Self::into_fields_named(Default::default(), fields) + } else { + Self::into_fields_unnamed(Default::default(), fields) + } + } + FieldsKind::Named(brace_token) => Self::into_fields_named(brace_token, fields), + FieldsKind::Unnamed(paren_token) => Self::into_fields_unnamed(paren_token, fields), + } + } +} + +pub(crate) fn get_target(target: &Option<(kw::target, Paren, Path)>, item_ident: &Ident) -> Path { + match target { + Some((_, _, target)) => target.clone(), + None => item_ident.clone().into(), + } +} + +pub(crate) struct ValueDeriveGenerics { + pub(crate) generics: Generics, + pub(crate) static_type_generics: Generics, +} + +impl ValueDeriveGenerics { + pub(crate) fn get(mut generics: Generics, where_: &Option<(Where, Paren, Bounds)>) -> Self { + let mut static_type_generics = generics.clone(); + if let Some((_, _, bounds)) = where_ { + generics + .make_where_clause() + .predicates + .extend(bounds.0.iter().cloned()); + static_type_generics + .where_clause + .clone_from(&generics.where_clause); + } else { + let type_params = Vec::from_iter(generics.type_params().map(|v| v.ident.clone())); + let predicates = &mut generics.make_where_clause().predicates; + let static_type_predicates = &mut static_type_generics.make_where_clause().predicates; + for type_param in type_params { + predicates.push(parse_quote! {#type_param: ::fayalite::ty::Value>}); + static_type_predicates + .push(parse_quote! {#type_param: ::fayalite::ty::StaticValue}); + } + } + Self { + generics, + static_type_generics, + } + } +} + +pub(crate) fn derive_clone_hash_eq_partialeq_for_struct( + the_struct_ident: &Ident, + generics: &Generics, + field_names: &[Name], +) -> TokenStream { + let (impl_generics, type_generics, where_clause) = generics.split_for_impl(); + quote! { + #[automatically_derived] + impl #impl_generics ::fayalite::__std::clone::Clone for #the_struct_ident #type_generics + #where_clause + { + fn clone(&self) -> Self { + Self { + #(#field_names: ::fayalite::__std::clone::Clone::clone(&self.#field_names),)* + } + } + } + + #[automatically_derived] + impl #impl_generics ::fayalite::__std::hash::Hash for #the_struct_ident #type_generics + #where_clause + { + #[allow(unused_variables)] + fn hash<__H: ::fayalite::__std::hash::Hasher>(&self, hasher: &mut __H) { + #(::fayalite::__std::hash::Hash::hash(&self.#field_names, hasher);)* + } + } + + #[automatically_derived] + impl #impl_generics ::fayalite::__std::cmp::Eq for #the_struct_ident #type_generics + #where_clause + { + } + + #[automatically_derived] + impl #impl_generics ::fayalite::__std::cmp::PartialEq for #the_struct_ident #type_generics + #where_clause + { + #[allow(unused_variables)] + #[allow(clippy::nonminimal_bool)] + fn eq(&self, other: &Self) -> ::fayalite::__std::primitive::bool { + true #(&& ::fayalite::__std::cmp::PartialEq::eq( + &self.#field_names, + &other.#field_names, + ))* + } + } + } +} + +pub(crate) fn append_field(fields: &mut Fields, mut field: Field) -> Member { + let ident = field.ident.clone().expect("ident is supplied"); + match fields { + Fields::Named(FieldsNamed { named, .. }) => { + named.push(field); + Member::Named(ident) + } + Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => { + field.ident = None; + field.colon_token = None; + let index = unnamed.len(); + unnamed.push(field); + Member::Unnamed(index.into()) + } + Fields::Unit => { + *fields = Fields::Named(FieldsNamed { + brace_token: Default::default(), + named: Punctuated::from_iter([field]), + }); + Member::Named(ident) + } + } +} + +#[derive(Clone, Debug)] +pub(crate) struct BuilderField { + pub(crate) names: HashSet, + pub(crate) mapped_value: Expr, + pub(crate) mapped_type: Type, + pub(crate) where_clause: Option, + pub(crate) builder_field_name: Ident, + pub(crate) type_param: Ident, +} + +#[derive(Debug)] +pub(crate) struct Builder { + struct_name: Ident, + vis: Visibility, + fields: BTreeMap, +} + +#[derive(Debug)] +pub(crate) struct BuilderWithFields { + struct_name: Ident, + vis: Visibility, + phantom_type_param: Ident, + phantom_type_field: Ident, + fields: Vec<(String, BuilderField)>, +} + +impl Builder { + pub(crate) fn new(struct_name: Ident, vis: Visibility) -> Self { + Self { + struct_name, + vis, + fields: BTreeMap::new(), + } + } + pub(crate) fn insert_field( + &mut self, + name: Member, + map_value: impl FnOnce(&Ident) -> Expr, + map_type: impl FnOnce(&Ident) -> Type, + where_clause: impl FnOnce(&Ident) -> Option, + ) { + self.fields + .entry(name.to_token_stream().to_string()) + .or_insert_with_key(|name| { + let builder_field_name = + format_ident!("field_{}", name, span = self.struct_name.span()); + let type_param = format_ident!("__T_{}", name, span = self.struct_name.span()); + BuilderField { + names: HashSet::new(), + mapped_value: map_value(&builder_field_name), + mapped_type: map_type(&type_param), + where_clause: where_clause(&type_param), + builder_field_name, + type_param, + } + }) + .names + .insert(name); + } + pub(crate) fn finish_filling_in_fields(self) -> BuilderWithFields { + let Self { + struct_name, + vis, + fields, + } = self; + let fields = Vec::from_iter(fields); + BuilderWithFields { + phantom_type_param: Ident::new("__Phantom", struct_name.span()), + phantom_type_field: Ident::new("__phantom", struct_name.span()), + struct_name, + vis, + fields, + } + } +} + +impl BuilderWithFields { + pub(crate) fn get_field(&self, name: &Member) -> Option<(usize, &BuilderField)> { + let index = self + .fields + .binary_search_by_key(&&*name.to_token_stream().to_string(), |v| &*v.0) + .ok()?; + Some((index, &self.fields[index].1)) + } + pub(crate) fn ty( + &self, + specified_fields: impl IntoIterator, + phantom_type: Option<&Type>, + other_fields_are_any_type: bool, + ) -> TypePath { + let Self { + struct_name, + vis: _, + phantom_type_param, + phantom_type_field: _, + fields, + } = self; + let span = struct_name.span(); + let mut arguments = + Vec::from_iter(fields.iter().map(|(_, BuilderField { type_param, .. })| { + if other_fields_are_any_type { + parse_quote_spanned! {span=> + #type_param + } + } else { + parse_quote_spanned! {span=> + () + } + } + })); + for (name, ty) in specified_fields { + let Some((index, _)) = self.get_field(&name) else { + panic!("field not found: {}", name.to_token_stream()); + }; + arguments[index] = ty; + } + let phantom_type_param = phantom_type.is_none().then_some(phantom_type_param); + parse_quote_spanned! {span=> + #struct_name::<#phantom_type_param #phantom_type #(, #arguments)*> + } + } + pub(crate) fn append_generics( + &self, + specified_fields: impl IntoIterator, + has_phantom_type_param: bool, + other_fields_are_any_type: bool, + generics: &mut Generics, + ) { + let Self { + struct_name: _, + vis: _, + phantom_type_param, + phantom_type_field: _, + fields, + } = self; + if has_phantom_type_param { + generics.params.push(GenericParam::from(TypeParam::from( + phantom_type_param.clone(), + ))); + } + if !other_fields_are_any_type { + return; + } + let mut type_params = Vec::from_iter( + fields + .iter() + .map(|(_, BuilderField { type_param, .. })| Some(type_param)), + ); + for name in specified_fields { + let Some((index, _)) = self.get_field(&name) else { + panic!("field not found: {}", name.to_token_stream()); + }; + type_params[index] = None; + } + generics.params.extend( + type_params + .into_iter() + .filter_map(|v| Some(GenericParam::from(TypeParam::from(v?.clone())))), + ); + } + pub(crate) fn make_build_method( + &self, + build_fn_name: &Ident, + specified_fields: impl IntoIterator, + generics: &Generics, + phantom_type: &Type, + return_ty: &Type, + mut body: Block, + ) -> ItemImpl { + let Self { + struct_name, + vis, + phantom_type_param: _, + phantom_type_field, + fields, + } = self; + let span = struct_name.span(); + let field_names = Vec::from_iter(fields.iter().map(|v| &v.1.builder_field_name)); + let (impl_generics, _type_generics, where_clause) = generics.split_for_impl(); + let empty_arg = parse_quote_spanned! {span=> + () + }; + let mut ty_arguments = vec![empty_arg; fields.len()]; + let empty_field_pat = quote_spanned! {span=> + : _ + }; + let mut field_pats = vec![Some(empty_field_pat); fields.len()]; + for (name, ty) in specified_fields { + let Some((index, _)) = self.get_field(&name) else { + panic!("field not found: {}", name.to_token_stream()); + }; + ty_arguments[index] = ty; + field_pats[index] = None; + } + body.stmts.insert( + 0, + parse_quote_spanned! {span=> + let Self { + #(#field_names #field_pats,)* + #phantom_type_field: _, + } = self; + }, + ); + parse_quote_spanned! {span=> + #[automatically_derived] + impl #impl_generics #struct_name<#phantom_type #(, #ty_arguments)*> + #where_clause + { + #[allow(non_snake_case, dead_code)] + #vis fn #build_fn_name(self) -> #return_ty + #body + } + } + } +} + +impl ToTokens for BuilderWithFields { + fn to_tokens(&self, tokens: &mut TokenStream) { + let Self { + struct_name, + vis, + phantom_type_param, + phantom_type_field, + fields, + } = self; + let span = struct_name.span(); + let mut any_generics = Generics::default(); + self.append_generics([], true, true, &mut any_generics); + let empty_ty = self.ty([], None, false); + let field_names = Vec::from_iter(fields.iter().map(|v| &v.1.builder_field_name)); + let field_type_params = Vec::from_iter(fields.iter().map(|v| &v.1.type_param)); + quote_spanned! {span=> + #[allow(non_camel_case_types)] + #[non_exhaustive] + #vis struct #struct_name #any_generics { + #(#field_names: #field_type_params,)* + #phantom_type_field: ::fayalite::__std::marker::PhantomData<#phantom_type_param>, + } + + #[automatically_derived] + impl<#phantom_type_param> #empty_ty { + fn new() -> Self { + Self { + #(#field_names: (),)* + #phantom_type_field: ::fayalite::__std::marker::PhantomData, + } + } + } + } + .to_tokens(tokens); + for (field_index, (_, field)) in self.fields.iter().enumerate() { + let initial_fields = &fields[..field_index]; + let final_fields = &fields[field_index..][1..]; + let initial_type_params = + Vec::from_iter(initial_fields.iter().map(|v| &v.1.type_param)); + let final_type_params = Vec::from_iter(final_fields.iter().map(|v| &v.1.type_param)); + let initial_field_names = + Vec::from_iter(initial_fields.iter().map(|v| &v.1.builder_field_name)); + let final_field_names = + Vec::from_iter(final_fields.iter().map(|v| &v.1.builder_field_name)); + let BuilderField { + names: _, + mapped_value, + mapped_type, + where_clause, + builder_field_name, + type_param, + } = field; + quote_spanned! {span=> + #[automatically_derived] + #[allow(non_camel_case_types, dead_code)] + impl<#phantom_type_param #(, #initial_type_params)* #(, #final_type_params)*> + #struct_name< + #phantom_type_param, + #(#initial_type_params,)* + (), #(#final_type_params,)* + > + { + #vis fn #builder_field_name<#type_param>( + self, + #builder_field_name: #type_param, + ) -> #struct_name< + #phantom_type_param, + #(#initial_type_params,)* + #mapped_type, + #(#final_type_params,)* + > + #where_clause + { + let Self { + #(#initial_field_names,)* + #builder_field_name: (), + #(#final_field_names,)* + #phantom_type_field: _, + } = self; + let #builder_field_name = #mapped_value; + #struct_name { + #(#field_names,)* + #phantom_type_field: ::fayalite::__std::marker::PhantomData, + } + } + } + } + .to_tokens(tokens); + } + } +} + +pub(crate) struct MapIdents { + pub(crate) map: HashMap, +} + +impl Fold for &MapIdents { + fn fold_ident(&mut self, i: Ident) -> Ident { + self.map.get(&i).cloned().unwrap_or(i) + } +} + +pub(crate) struct DupGenerics { + pub(crate) combined: Generics, + pub(crate) maps: M, +} + +pub(crate) fn merge_punctuated( + target: &mut Punctuated, + source: Punctuated, + make_punct: impl FnOnce() -> P, +) { + if source.is_empty() { + return; + } + if target.is_empty() { + *target = source; + return; + } + if !target.trailing_punct() { + target.push_punct(make_punct()); + } + target.extend(source.into_pairs()); +} + +pub(crate) fn merge_generics(target: &mut Generics, source: Generics) { + let Generics { + lt_token, + params, + gt_token, + where_clause, + } = source; + let span = lt_token.map(|v| v.span).unwrap_or_else(|| params.span()); + target.lt_token = target.lt_token.or(lt_token); + merge_punctuated(&mut target.params, params, || Token![,](span)); + target.gt_token = target.gt_token.or(gt_token); + if let Some(where_clause) = where_clause { + if let Some(target_where_clause) = &mut target.where_clause { + let WhereClause { + where_token, + predicates, + } = where_clause; + let span = where_token.span; + target_where_clause.where_token = where_token; + merge_punctuated(&mut target_where_clause.predicates, predicates, || { + Token![,](span) + }); + } else { + target.where_clause = Some(where_clause); + } + } +} + +impl DupGenerics> { + pub(crate) fn new_dyn(generics: &Generics, count: usize) -> Self { + let mut maps = Vec::from_iter((0..count).map(|_| MapIdents { + map: HashMap::new(), + })); + for param in &generics.params { + let (GenericParam::Lifetime(LifetimeParam { + lifetime: Lifetime { ident, .. }, + .. + }) + | GenericParam::Type(TypeParam { ident, .. }) + | GenericParam::Const(ConstParam { ident, .. })) = param; + for (i, map_idents) in maps.iter_mut().enumerate() { + map_idents + .map + .insert(ident.clone(), format_ident!("__{}_{}", ident, i)); + } + } + let mut combined = Generics::default(); + for map_idents in maps.iter() { + merge_generics( + &mut combined, + fold_generics(&mut { map_idents }, generics.clone()), + ); + } + Self { combined, maps } + } +} + +impl DupGenerics<[MapIdents; COUNT]> { + pub(crate) fn new(generics: &Generics) -> Self { + let DupGenerics { combined, maps } = DupGenerics::new_dyn(generics, COUNT); + Self { + combined, + maps: maps.try_into().ok().unwrap(), + } + } +} + +pub(crate) fn add_where_predicate( + target: &mut Generics, + span: Span, + where_predicate: WherePredicate, +) { + let WhereClause { + where_token: _, + predicates, + } = target.where_clause.get_or_insert_with(|| WhereClause { + where_token: Token![where](span), + predicates: Punctuated::new(), + }); + if !predicates.empty_or_trailing() { + predicates.push_punct(Token![,](span)); + } + predicates.push_value(where_predicate); +} + +pub(crate) fn make_connect_impl( + connect_inexact: Option<(crate::kw::connect_inexact,)>, + generics: &Generics, + ty_ident: &Ident, + field_types: impl IntoIterator, +) -> TokenStream { + let span = ty_ident.span(); + let impl_generics; + let combined_generics; + let where_clause; + let lhs_generics; + let lhs_type_generics; + let rhs_generics; + let rhs_type_generics; + if connect_inexact.is_some() { + let DupGenerics { + mut combined, + maps: [lhs_map, rhs_map], + } = DupGenerics::new(generics); + for field_type in field_types { + let lhs_type = (&lhs_map).fold_type(field_type.clone()); + let rhs_type = (&rhs_map).fold_type(field_type); + add_where_predicate( + &mut combined, + span, + parse_quote_spanned! {span=> + #lhs_type: ::fayalite::ty::Connect<#rhs_type> + }, + ); + } + combined_generics = combined; + (impl_generics, _, where_clause) = combined_generics.split_for_impl(); + lhs_generics = (&lhs_map).fold_generics(generics.clone()); + (_, lhs_type_generics, _) = lhs_generics.split_for_impl(); + rhs_generics = (&rhs_map).fold_generics(generics.clone()); + (_, rhs_type_generics, _) = rhs_generics.split_for_impl(); + } else { + let mut generics = generics.clone(); + for field_type in field_types { + add_where_predicate( + &mut generics, + span, + parse_quote_spanned! {span=> + #field_type: ::fayalite::ty::Connect<#field_type> + }, + ); + } + combined_generics = generics; + (impl_generics, lhs_type_generics, where_clause) = combined_generics.split_for_impl(); + rhs_type_generics = lhs_type_generics.clone(); + } + quote_spanned! {span=> + #[automatically_derived] + #[allow(non_camel_case_types)] + impl #impl_generics ::fayalite::ty::Connect<#ty_ident #rhs_type_generics> + for #ty_ident #lhs_type_generics + #where_clause + { + } + } +} diff --git a/crates/fayalite-proc-macros-impl/src/value_derive_enum.rs b/crates/fayalite-proc-macros-impl/src/value_derive_enum.rs new file mode 100644 index 0000000..87f53c1 --- /dev/null +++ b/crates/fayalite-proc-macros-impl/src/value_derive_enum.rs @@ -0,0 +1,969 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// See Notices.txt for copyright information +use crate::{ + value_derive_common::{ + append_field, derive_clone_hash_eq_partialeq_for_struct, get_field_names, get_target, + make_connect_impl, Bounds, Builder, FieldsKind, ParsedField, ValueDeriveGenerics, + }, + value_derive_struct::{self, ParsedStruct, ParsedStructNames, StructOptions}, + Errors, HdlAttr, +}; +use proc_macro2::TokenStream; +use quote::{format_ident, quote, quote_spanned, ToTokens}; +use syn::{ + parse_quote, parse_quote_spanned, punctuated::Punctuated, spanned::Spanned, token::Brace, + Field, FieldMutability, Fields, FieldsNamed, Generics, Ident, Index, ItemEnum, ItemStruct, + Member, Path, Token, Type, Variant, Visibility, +}; + +crate::options! { + #[options = EnumOptions] + enum EnumOption { + OutlineGenerated(outline_generated), + ConnectInexact(connect_inexact), + Bounds(where_, Bounds), + Target(target, Path), + } +} + +crate::options! { + #[options = VariantOptions] + enum VariantOption {} +} + +crate::options! { + #[options = FieldOptions] + enum FieldOption {} +} + +enum VariantValue { + None, + Direct { + value_type: Type, + }, + Struct { + value_struct: ItemStruct, + parsed_struct: ParsedStruct, + }, +} + +impl VariantValue { + fn is_none(&self) -> bool { + matches!(self, Self::None) + } + fn value_ty(&self) -> Option { + match self { + VariantValue::None => None, + VariantValue::Direct { value_type } => Some(value_type.clone()), + VariantValue::Struct { value_struct, .. } => { + let (_, type_generics, _) = value_struct.generics.split_for_impl(); + let ident = &value_struct.ident; + Some(parse_quote! { #ident #type_generics }) + } + } + } +} + +struct ParsedVariant { + options: HdlAttr, + ident: Ident, + fields_kind: FieldsKind, + fields: Vec>, + value: VariantValue, +} + +impl ParsedVariant { + fn parse( + errors: &mut Errors, + variant: Variant, + enum_options: &EnumOptions, + enum_vis: &Visibility, + enum_ident: &Ident, + enum_generics: &Generics, + ) -> Self { + let target = get_target(&enum_options.target, enum_ident); + let Variant { + mut attrs, + ident, + fields, + discriminant, + } = variant; + if let Some((eq, _)) = discriminant { + errors.error(eq, "#[derive(Value)]: discriminants not allowed"); + } + let variant_options = errors + .unwrap_or_default(HdlAttr::parse_and_take_attr(&mut attrs)) + .unwrap_or_default(); + let (fields_kind, parsed_fields) = + ParsedField::parse_fields(errors, &mut fields.clone(), true); + let value = match (&fields_kind, &*parsed_fields) { + (FieldsKind::Unit, _) => VariantValue::None, + ( + FieldsKind::Unnamed(_), + [ParsedField { + options, + vis: _, + name: Member::Unnamed(Index { index: 0, span: _ }), + ty, + }], + ) => { + let FieldOptions {} = options.body; + VariantValue::Direct { + value_type: ty.clone(), + } + } + _ => { + let variant_value_struct_ident = + format_ident!("__{}__{}", enum_ident, ident, span = ident.span()); + let variant_type_struct_ident = + format_ident!("__{}__{}__Type", enum_ident, ident, span = ident.span()); + let mut value_struct_fields = fields.clone(); + let (_, type_generics, _) = enum_generics.split_for_impl(); + append_field( + &mut value_struct_fields, + Field { + attrs: vec![HdlAttr::from(value_derive_struct::FieldOptions { + flip: None, + skip: Some(Default::default()), + }) + .to_attr()], + vis: enum_vis.clone(), + mutability: FieldMutability::None, + ident: Some(Ident::new("__phantom", ident.span())), + colon_token: None, + ty: parse_quote_spanned! {ident.span()=> + ::fayalite::__std::marker::PhantomData<#target #type_generics> + }, + }, + ); + let (value_struct_fields_kind, value_struct_parsed_fields) = + ParsedField::parse_fields(errors, &mut value_struct_fields, false); + let value_struct = ItemStruct { + attrs: vec![parse_quote! { #[allow(non_camel_case_types)] }], + vis: enum_vis.clone(), + struct_token: Token![struct](ident.span()), + ident: variant_value_struct_ident.clone(), + generics: enum_generics.clone(), + fields: value_struct_fields, + semi_token: None, + }; + VariantValue::Struct { + value_struct, + parsed_struct: ParsedStruct { + options: StructOptions { + outline_generated: None, + static_: Some(Default::default()), + where_: Some(( + Default::default(), + Default::default(), + ValueDeriveGenerics::get( + enum_generics.clone(), + &enum_options.where_, + ) + .static_type_generics + .where_clause + .into(), + )), + target: None, + connect_inexact: enum_options.connect_inexact, + } + .into(), + vis: enum_vis.clone(), + struct_token: Default::default(), + generics: enum_generics.clone(), + fields_kind: value_struct_fields_kind, + fields: value_struct_parsed_fields, + semi_token: None, // it will fill in the semicolon if needed + skip_check_fields: true, + names: ParsedStructNames { + ident: variant_value_struct_ident.clone(), + type_struct_debug_ident: Some(format!("{enum_ident}::{ident}::Type")), + type_struct_ident: variant_type_struct_ident, + match_variant_ident: None, + builder_struct_ident: None, + mask_match_variant_ident: None, + mask_type_ident: None, + mask_type_debug_ident: Some(format!( + "AsMask<{enum_ident}::{ident}>::Type" + )), + mask_value_ident: None, + mask_value_debug_ident: Some(format!("AsMask<{enum_ident}::{ident}>")), + mask_builder_struct_ident: None, + }, + }, + } + } + }; + ParsedVariant { + options: variant_options, + ident, + fields_kind, + fields: parsed_fields, + value, + } + } +} + +struct ParsedEnum { + options: HdlAttr, + vis: Visibility, + enum_token: Token![enum], + ident: Ident, + generics: Generics, + brace_token: Brace, + variants: Vec, +} + +impl ParsedEnum { + fn parse(item: ItemEnum) -> syn::Result { + let ItemEnum { + mut attrs, + vis, + enum_token, + ident, + generics, + brace_token, + variants, + } = item; + let mut errors = Errors::new(); + let enum_options = errors + .unwrap_or_default(HdlAttr::parse_and_take_attr(&mut attrs)) + .unwrap_or_default(); + let variants = variants + .into_iter() + .map(|variant| { + ParsedVariant::parse( + &mut errors, + variant, + &enum_options.body, + &vis, + &ident, + &generics, + ) + }) + .collect(); + errors.finish()?; + Ok(ParsedEnum { + options: enum_options, + vis, + enum_token, + ident, + generics, + brace_token, + variants, + }) + } +} + +impl ToTokens for ParsedEnum { + fn to_tokens(&self, tokens: &mut TokenStream) { + let Self { + options, + vis, + enum_token, + ident: enum_ident, + generics: enum_generics, + brace_token, + variants, + } = self; + let EnumOptions { + outline_generated: _, + connect_inexact, + where_, + target, + } = &options.body; + let target = get_target(target, enum_ident); + let ValueDeriveGenerics { + generics: _, + static_type_generics, + } = ValueDeriveGenerics::get(enum_generics.clone(), where_); + let (static_type_impl_generics, static_type_type_generics, static_type_where_clause) = + static_type_generics.split_for_impl(); + let type_struct_ident = format_ident!("__{}__Type", enum_ident); + let mut field_checks = vec![]; + let mut make_type_struct_variant_type = |variant: &ParsedVariant| { + let VariantOptions {} = variant.options.body; + let (value_struct, parsed_struct) = match &variant.value { + VariantValue::None => { + return None; + } + VariantValue::Direct { value_type } => { + field_checks.push(quote_spanned! {value_type.span()=> + __check_field::<#value_type>(); + }); + return Some(parse_quote! { <#value_type as ::fayalite::expr::ToExpr>::Type }); + } + VariantValue::Struct { + value_struct, + parsed_struct, + } => (value_struct, parsed_struct), + }; + value_struct.to_tokens(tokens); + parsed_struct.to_tokens(tokens); + let mut field_names = Vec::from_iter(get_field_names(&value_struct.fields)); + derive_clone_hash_eq_partialeq_for_struct( + &value_struct.ident, + &static_type_generics, + &field_names, + ) + .to_tokens(tokens); + field_names = Vec::from_iter( + field_names + .into_iter() + .zip(parsed_struct.fields.iter()) + .filter_map(|(member, field)| { + field.options.body.skip.is_none().then_some(member) + }), + ); + let field_name_strs = + Vec::from_iter(field_names.iter().map(|v| v.to_token_stream().to_string())); + let debug_ident = format!("{enum_ident}::{}", variant.ident); + let debug_body = match variant.fields_kind { + FieldsKind::Unit => quote! { + f.debug_struct(#debug_ident).finish() + }, + FieldsKind::Named(_) => quote! { + f.debug_struct(#debug_ident) + #(.field(#field_name_strs, &self.#field_names))* + .finish() + }, + FieldsKind::Unnamed(_) => quote! { + f.debug_tuple(#debug_ident)#(.field(&self.#field_names))*.finish() + }, + }; + let value_struct_ident = &value_struct.ident; + quote! { + #[automatically_derived] + impl #static_type_impl_generics ::fayalite::__std::fmt::Debug + for #value_struct_ident #static_type_type_generics + #static_type_where_clause + { + fn fmt( + &self, + f: &mut ::fayalite::__std::fmt::Formatter<'_>, + ) -> ::fayalite::__std::fmt::Result { + #debug_body + } + } + } + .to_tokens(tokens); + Some(parse_quote! { + < + #value_struct_ident #static_type_type_generics + as ::fayalite::expr::ToExpr + >::Type + }) + }; + let type_struct_variants = Punctuated::from_iter(variants.iter().filter_map(|variant| { + let VariantOptions {} = variant.options.body; + Some(Field { + attrs: vec![], + vis: vis.clone(), + mutability: FieldMutability::None, + ident: Some(variant.ident.clone()), + colon_token: None, // it will fill in the colon if needed + ty: make_type_struct_variant_type(variant)?, + }) + })); + let type_struct = ItemStruct { + attrs: vec![ + parse_quote! {#[allow(non_camel_case_types)]}, + parse_quote! {#[allow(non_snake_case)]}, + ], + vis: vis.clone(), + struct_token: Token![struct](enum_token.span), + ident: type_struct_ident, + generics: static_type_generics.clone(), + fields: Fields::Named(FieldsNamed { + brace_token: *brace_token, + named: type_struct_variants, + }), + semi_token: None, + }; + let type_struct_ident = &type_struct.ident; + let type_struct_debug_ident = format!("{enum_ident}::Type"); + type_struct.to_tokens(tokens); + let non_empty_variant_names = Vec::from_iter( + variants + .iter() + .filter(|v| !v.value.is_none()) + .map(|v| v.ident.clone()), + ); + let non_empty_variant_name_strs = + Vec::from_iter(non_empty_variant_names.iter().map(|v| v.to_string())); + let debug_type_body = quote! { + f.debug_struct(#type_struct_debug_ident) + #(.field(#non_empty_variant_name_strs, &self.#non_empty_variant_names))* + .finish() + }; + derive_clone_hash_eq_partialeq_for_struct( + type_struct_ident, + &static_type_generics, + &non_empty_variant_names, + ) + .to_tokens(tokens); + let variant_names = Vec::from_iter(variants.iter().map(|v| &v.ident)); + let variant_name_strs = Vec::from_iter(variant_names.iter().map(|v| v.to_string())); + let (variant_field_pats, variant_to_canonical_values): (Vec<_>, Vec<_>) = variants + .iter() + .map(|v| { + let field_names: Vec<_> = v.fields.iter().map(|field| &field.name).collect(); + let var_names: Vec<_> = v.fields.iter().map(|field| field.var_name()).collect(); + let field_pats = quote! { + #(#field_names: #var_names,)* + }; + let to_canonical_value = match &v.value { + VariantValue::None => quote! { ::fayalite::__std::option::Option::None }, + VariantValue::Direct { .. } => { + debug_assert_eq!(var_names.len(), 1); + quote! { + ::fayalite::__std::option::Option::Some( + ::fayalite::ty::DynValueTrait::to_canonical_dyn(#(#var_names)*), + ) + } + } + VariantValue::Struct { + value_struct, + parsed_struct, + } => { + let value_struct_ident = &value_struct.ident; + let phantom_field_name = &parsed_struct + .fields + .last() + .expect("missing phantom field") + .name; + let type_generics = static_type_type_generics.as_turbofish(); + quote! { + ::fayalite::__std::option::Option::Some( + ::fayalite::ty::DynValueTrait::to_canonical_dyn( + &#value_struct_ident #type_generics { + #(#field_names: + ::fayalite::__std::clone::Clone::clone(#var_names),)* + #phantom_field_name: ::fayalite::__std::marker::PhantomData, + }, + ), + ) + } + } + }; + (field_pats, to_canonical_value) + }) + .unzip(); + let mut match_enum_variants = Punctuated::new(); + let mut match_enum_debug_arms = vec![]; + let mut match_enum_arms = vec![]; + let mut variant_vars = vec![]; + let mut from_canonical_type_variant_lets = vec![]; + let mut non_empty_variant_vars = vec![]; + let mut enum_type_variants = vec![]; + let mut enum_type_variants_hint = vec![]; + let match_enum_ident = format_ident!("__{}__MatchEnum", enum_ident); + let mut builder = Builder::new(format_ident!("__{}__Builder", enum_ident), vis.clone()); + for variant in variants.iter() { + for field in variant.fields.iter() { + builder.insert_field( + field.name.clone(), + |v| { + parse_quote_spanned! {v.span()=> + ::fayalite::expr::ToExpr::to_expr(&#v) + } + }, + |t| { + parse_quote_spanned! {t.span()=> + ::fayalite::expr::Expr<< + <#t as ::fayalite::expr::ToExpr>::Type + as ::fayalite::ty::Type + >::Value> + } + }, + |t| { + parse_quote_spanned! {t.span()=> + where + #t: ::fayalite::expr::ToExpr, + } + }, + ); + } + } + let builder = builder.finish_filling_in_fields(); + builder.to_tokens(tokens); + for (variant_index, variant) in variants.iter().enumerate() { + let variant_var = format_ident!("__v_{}", variant.ident); + let variant_name = &variant.ident; + let variant_name_str = variant.ident.to_string(); + match_enum_variants.push(Variant { + attrs: vec![], + ident: variant.ident.clone(), + fields: variant.fields_kind.into_fields(variant.fields.iter().map( + |ParsedField { + options, + vis, + name, + ty, + }| { + let FieldOptions {} = options.body; + Field { + attrs: vec![], + vis: vis.clone(), + mutability: FieldMutability::None, + ident: if let Member::Named(name) = name { + Some(name.clone()) + } else { + None + }, + colon_token: None, + ty: parse_quote! { ::fayalite::expr::Expr<#ty> }, + } + }, + )), + discriminant: None, + }); + let match_enum_field_names = Vec::from_iter(variant.fields.iter().map( + |ParsedField { + options, + vis: _, + name, + ty: _, + }| { + let FieldOptions {} = options.body; + name + }, + )); + let match_enum_field_name_strs = Vec::from_iter(variant.fields.iter().map( + |ParsedField { + options, + vis: _, + name, + ty: _, + }| { + let FieldOptions {} = options.body; + name.to_token_stream().to_string() + }, + )); + let match_enum_debug_vars = Vec::from_iter(variant.fields.iter().map( + |ParsedField { + options, + vis: _, + name, + ty: _, + }| { + let FieldOptions {} = options.body; + format_ident!("__v_{}", name) + }, + )); + match_enum_debug_arms.push(match variant.fields_kind { + FieldsKind::Unit | FieldsKind::Named(_) => quote! { + Self::#variant_name { + #(#match_enum_field_names: ref #match_enum_debug_vars,)* + } => f.debug_struct(#variant_name_str) + #(.field(#match_enum_field_name_strs, #match_enum_debug_vars))* + .finish(), + }, + FieldsKind::Unnamed(_) => quote! { + Self::#variant_name( + #(ref #match_enum_debug_vars,)* + ) => f.debug_tuple(#variant_name_str) + #(.field(#match_enum_debug_vars))* + .finish(), + }, + }); + if let Some(value_ty) = variant.value.value_ty() { + from_canonical_type_variant_lets.push(quote! { + let #variant_var = + #variant_var.from_canonical_type_helper_has_value(#variant_name_str); + }); + non_empty_variant_vars.push(variant_var.clone()); + enum_type_variants.push(quote! { + ::fayalite::enum_::VariantType { + name: ::fayalite::intern::Intern::intern(#variant_name_str), + ty: ::fayalite::__std::option::Option::Some( + ::fayalite::ty::DynType::canonical_dyn(&self.#variant_name), + ), + } + }); + enum_type_variants_hint.push(quote! { + ::fayalite::enum_::VariantType { + name: ::fayalite::intern::Intern::intern(#variant_name_str), + ty: ::fayalite::__std::option::Option::Some( + ::fayalite::bundle::TypeHint::< + <#value_ty as ::fayalite::expr::ToExpr>::Type, + >::intern_dyn(), + ), + } + }); + } else { + from_canonical_type_variant_lets.push(quote! { + #variant_var.from_canonical_type_helper_no_value(#variant_name_str); + }); + enum_type_variants.push(quote! { + ::fayalite::enum_::VariantType { + name: ::fayalite::intern::Intern::intern(#variant_name_str), + ty: ::fayalite::__std::option::Option::None, + } + }); + enum_type_variants_hint.push(quote! { + ::fayalite::enum_::VariantType { + name: ::fayalite::intern::Intern::intern(#variant_name_str), + ty: ::fayalite::__std::option::Option::None, + } + }); + } + variant_vars.push(variant_var); + match_enum_arms.push(match &variant.value { + VariantValue::None => quote! { + #variant_index => #match_enum_ident::#variant_name, + }, + VariantValue::Direct { value_type } => quote! { + #variant_index => #match_enum_ident::#variant_name { + #(#match_enum_field_names)*: ::fayalite::expr::ToExpr::to_expr( + &__variant_access.downcast_unchecked::< + <#value_type as ::fayalite::expr::ToExpr>::Type>(), + ), + }, + }, + VariantValue::Struct { + value_struct: ItemStruct { ident, .. }, + .. + } => quote! { + #variant_index => { + let __variant_access = ::fayalite::expr::ToExpr::to_expr( + &__variant_access.downcast_unchecked::<< + #ident #static_type_type_generics + as ::fayalite::expr::ToExpr + >::Type>(), + ); + #match_enum_ident::#variant_name { + #(#match_enum_field_names: + (*__variant_access).#match_enum_field_names,)* + } + }, + }, + }); + let builder_field_and_types = Vec::from_iter(variant.fields.iter().map( + |ParsedField { + options, + vis: _, + name, + ty, + }| { + let FieldOptions {} = options.body; + (name, ty) + }, + )); + let builder_field_vars = Vec::from_iter( + builder_field_and_types + .iter() + .map(|(name, _)| &builder.get_field(name).unwrap().1.builder_field_name), + ); + let build_body = match &variant.value { + VariantValue::None => parse_quote! { + { + ::fayalite::expr::ToExpr::to_expr( + &::fayalite::expr::ops::EnumLiteral::< + #type_struct_ident #static_type_type_generics + >::new_unchecked( + ::fayalite::__std::option::Option::None, + #variant_index, + ::fayalite::ty::StaticType::static_type(), + ), + ) + } + }, + VariantValue::Direct { value_type: _ } => parse_quote! { + { + ::fayalite::expr::ToExpr::to_expr( + &::fayalite::expr::ops::EnumLiteral::< + #type_struct_ident #static_type_type_generics + >::new_unchecked( + ::fayalite::__std::option::Option::Some( + #(#builder_field_vars)*.to_canonical_dyn(), + ), + #variant_index, + ::fayalite::ty::StaticType::static_type(), + ), + ) + } + }, + VariantValue::Struct { + parsed_struct: + ParsedStruct { + names: + ParsedStructNames { + type_struct_ident: field_type_struct_ident, + .. + }, + .. + }, + .. + } => parse_quote! { + { + let __builder = < + #field_type_struct_ident #static_type_type_generics + as ::fayalite::bundle::BundleType + >::builder(); + #(let __builder = __builder.#builder_field_vars(#builder_field_vars);)* + ::fayalite::expr::ToExpr::to_expr( + &::fayalite::expr::ops::EnumLiteral::< + #type_struct_ident #static_type_type_generics + >::new_unchecked( + ::fayalite::__std::option::Option::Some( + __builder.build().to_canonical_dyn(), + ), + #variant_index, + ::fayalite::ty::StaticType::static_type(), + ), + ) + } + }, + }; + builder + .make_build_method( + &format_ident!("variant_{}", variant_name), + variant.fields.iter().map( + |ParsedField { + options, + vis: _, + name, + ty, + }| { + let FieldOptions {} = options.body; + (name.clone(), parse_quote! { ::fayalite::expr::Expr<#ty> }) + }, + ), + &static_type_generics, + &parse_quote! {#type_struct_ident #static_type_type_generics}, + &parse_quote! { ::fayalite::expr::Expr<#target #static_type_type_generics> }, + build_body, + ) + .to_tokens(tokens); + } + let match_enum = ItemEnum { + attrs: vec![parse_quote! {#[allow(non_camel_case_types)]}], + vis: vis.clone(), + enum_token: *enum_token, + ident: match_enum_ident, + generics: static_type_generics.clone(), + brace_token: *brace_token, + variants: match_enum_variants, + }; + let match_enum_ident = &match_enum.ident; + match_enum.to_tokens(tokens); + make_connect_impl( + *connect_inexact, + &static_type_generics, + type_struct_ident, + variants.iter().flat_map(|variant| { + variant.fields.iter().map(|field| { + let ty = &field.ty; + parse_quote_spanned! {field.name.span()=> + <#ty as ::fayalite::expr::ToExpr>::Type + } + }) + }), + ) + .to_tokens(tokens); + let variant_count = variants.len(); + let empty_builder_ty = builder.ty([], Some(&parse_quote! { Self }), false); + quote! { + #[automatically_derived] + impl #static_type_impl_generics ::fayalite::__std::fmt::Debug + for #match_enum_ident #static_type_type_generics + #static_type_where_clause + { + fn fmt( + &self, + f: &mut ::fayalite::__std::fmt::Formatter<'_>, + ) -> ::fayalite::__std::fmt::Result { + match *self { + #(#match_enum_debug_arms)* + } + } + } + + #[automatically_derived] + impl #static_type_impl_generics ::fayalite::ty::StaticType + for #type_struct_ident #static_type_type_generics + #static_type_where_clause + { + fn static_type() -> Self { + Self { + #(#non_empty_variant_names: ::fayalite::ty::StaticType::static_type(),)* + } + } + } + + fn __check_field() + where + ::Type: ::fayalite::ty::Type, + {} + fn __check_fields #static_type_impl_generics(_: #target #static_type_type_generics) + #static_type_where_clause + { + #(#field_checks)* + } + + #[automatically_derived] + impl #static_type_impl_generics ::fayalite::__std::fmt::Debug + for #type_struct_ident #static_type_type_generics + #static_type_where_clause + { + fn fmt( + &self, + f: &mut ::fayalite::__std::fmt::Formatter<'_>, + ) -> ::fayalite::__std::fmt::Result { + #debug_type_body + } + } + + #[automatically_derived] + impl #static_type_impl_generics ::fayalite::ty::Type + for #type_struct_ident #static_type_type_generics + #static_type_where_clause + { + type CanonicalType = ::fayalite::enum_::DynEnumType; + type Value = #target #static_type_type_generics; + type CanonicalValue = ::fayalite::enum_::DynEnum; + type MaskType = ::fayalite::int::UIntType<1>; + type MaskValue = ::fayalite::int::UInt<1>; + type MatchVariant = #match_enum_ident #static_type_type_generics; + type MatchActiveScope = ::fayalite::module::Scope; + type MatchVariantAndInactiveScope = + ::fayalite::enum_::EnumMatchVariantAndInactiveScope; + type MatchVariantsIter = ::fayalite::enum_::EnumMatchVariantsIter; + fn match_variants( + this: ::fayalite::expr::Expr<::Value>, + module_builder: &mut ::fayalite::module::ModuleBuilder< + IO, + ::fayalite::module::NormalModule, + >, + source_location: ::fayalite::source_location::SourceLocation, + ) -> ::MatchVariantsIter + where + ::Type: + ::fayalite::bundle::BundleType, + { + module_builder.enum_match_variants_helper(this, source_location) + } + fn mask_type(&self) -> ::MaskType { + ::fayalite::int::UIntType::new() + } + fn canonical(&self) -> ::CanonicalType { + let variants = ::fayalite::enum_::EnumType::variants(self); + ::fayalite::enum_::DynEnumType::new(variants) + } + fn source_location(&self) -> ::fayalite::source_location::SourceLocation { + ::fayalite::source_location::SourceLocation::caller() + } + fn type_enum(&self) -> ::fayalite::ty::TypeEnum { + ::fayalite::ty::TypeEnum::EnumType(::fayalite::ty::Type::canonical(self)) + } + #[allow(non_snake_case)] + fn from_canonical_type(t: ::CanonicalType) -> Self { + let [#(#variant_vars),*] = *::fayalite::enum_::EnumType::variants(&t) else { + ::fayalite::__std::panic!("wrong number of variants"); + }; + #(#from_canonical_type_variant_lets)* + Self { + #(#non_empty_variant_names: #non_empty_variant_vars,)* + } + } + } + + #[automatically_derived] + #[allow(clippy::init_numbered_fields)] + impl #static_type_impl_generics ::fayalite::enum_::EnumType + for #type_struct_ident #static_type_type_generics + #static_type_where_clause + { + type Builder = #empty_builder_ty; + fn match_activate_scope( + v: ::MatchVariantAndInactiveScope, + ) -> ( + ::MatchVariant, + ::MatchActiveScope, + ) { + let (__variant_access, __scope) = v.activate(); + ( + match ::fayalite::expr::ops::VariantAccess::variant_index( + &*__variant_access, + ) { + #(#match_enum_arms)* + #variant_count.. => ::fayalite::__std::panic!("invalid variant index"), + }, + __scope, + ) + } + fn builder() -> ::Builder { + #empty_builder_ty::new() + } + fn variants(&self) -> ::fayalite::intern::Interned<[::fayalite::enum_::VariantType< + ::fayalite::intern::Interned, + >]> { + ::fayalite::intern::Intern::intern(&[#(#enum_type_variants,)*][..]) + } + fn variants_hint() -> ::fayalite::enum_::VariantsHint { + ::fayalite::enum_::VariantsHint::new([#(#enum_type_variants_hint,)*], false) + } + } + + #[automatically_derived] + impl #static_type_impl_generics ::fayalite::expr::ToExpr + for #target #static_type_type_generics + #static_type_where_clause + { + type Type = #type_struct_ident #static_type_type_generics; + fn ty(&self) -> ::Type { + ::fayalite::ty::StaticType::static_type() + } + fn to_expr(&self) -> ::fayalite::expr::Expr { + ::fayalite::expr::Expr::from_value(self) + } + } + + #[automatically_derived] + impl #static_type_impl_generics ::fayalite::ty::Value + for #target #static_type_type_generics + #static_type_where_clause + { + fn to_canonical(&self) -> < + ::Type + as ::fayalite::ty::Type + >::CanonicalValue + { + let __ty = ::fayalite::ty::Type::canonical(&::fayalite::expr::ToExpr::ty(self)); + match self { + #(Self::#variant_names { #variant_field_pats } => { + ::fayalite::enum_::DynEnum::new_by_name( + __ty, + ::fayalite::intern::Intern::intern(#variant_name_strs), + #variant_to_canonical_values, + ) + })* + } + } + } + + #[automatically_derived] + impl #static_type_impl_generics ::fayalite::enum_::EnumValue + for #target #static_type_type_generics + #static_type_where_clause + { + } + } + .to_tokens(tokens); + } +} + +pub(crate) fn value_derive_enum(item: ItemEnum) -> syn::Result { + let item = ParsedEnum::parse(item)?; + let outline_generated = item.options.body.outline_generated; + let mut contents = quote! { + const _: () = { + #item + }; + }; + if outline_generated.is_some() { + contents = crate::outline_generated(contents, "value-enum-"); + } + Ok(contents) +} diff --git a/crates/fayalite-proc-macros-impl/src/value_derive_struct.rs b/crates/fayalite-proc-macros-impl/src/value_derive_struct.rs new file mode 100644 index 0000000..a0b303a --- /dev/null +++ b/crates/fayalite-proc-macros-impl/src/value_derive_struct.rs @@ -0,0 +1,765 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// See Notices.txt for copyright information +use crate::{ + value_derive_common::{ + append_field, derive_clone_hash_eq_partialeq_for_struct, get_target, make_connect_impl, + Bounds, Builder, FieldsKind, ParsedField, ValueDeriveGenerics, + }, + Errors, HdlAttr, +}; +use proc_macro2::TokenStream; +use quote::{format_ident, quote, quote_spanned, ToTokens}; +use syn::{ + parse_quote, parse_quote_spanned, spanned::Spanned, FieldMutability, Generics, Ident, + ItemStruct, Member, Path, Token, Visibility, +}; + +crate::options! { + #[options = StructOptions] + pub(crate) enum StructOption { + OutlineGenerated(outline_generated), + Static(static_), + ConnectInexact(connect_inexact), + Bounds(where_, Bounds), + Target(target, Path), + } +} + +crate::options! { + #[options = FieldOptions] + pub(crate) enum FieldOption { + Flip(flip), + Skip(skip), + } +} + +pub(crate) struct ParsedStructNames { + pub(crate) ident: Ident, + pub(crate) type_struct_debug_ident: S, + pub(crate) type_struct_ident: Ident, + pub(crate) match_variant_ident: I, + pub(crate) builder_struct_ident: I, + pub(crate) mask_match_variant_ident: I, + pub(crate) mask_type_ident: I, + pub(crate) mask_type_debug_ident: S, + pub(crate) mask_value_ident: I, + pub(crate) mask_value_debug_ident: S, + pub(crate) mask_builder_struct_ident: I, +} + +pub(crate) struct ParsedStruct { + pub(crate) options: HdlAttr, + pub(crate) vis: Visibility, + pub(crate) struct_token: Token![struct], + pub(crate) generics: Generics, + pub(crate) fields_kind: FieldsKind, + pub(crate) fields: Vec>, + pub(crate) semi_token: Option, + pub(crate) skip_check_fields: bool, + pub(crate) names: ParsedStructNames, Option>, +} + +impl ParsedStruct { + pub(crate) fn parse(item: &mut ItemStruct) -> syn::Result { + let ItemStruct { + attrs, + vis, + struct_token, + ident, + generics, + fields, + semi_token, + } = item; + let mut errors = Errors::new(); + let struct_options = errors + .unwrap_or_default(HdlAttr::parse_and_take_attr(attrs)) + .unwrap_or_default(); + let (fields_kind, fields) = ParsedField::parse_fields(&mut errors, fields, false); + errors.finish()?; + Ok(ParsedStruct { + options: struct_options, + vis: vis.clone(), + struct_token: *struct_token, + generics: generics.clone(), + fields_kind, + fields, + semi_token: *semi_token, + skip_check_fields: false, + names: ParsedStructNames { + ident: ident.clone(), + type_struct_debug_ident: None, + type_struct_ident: format_ident!("__{}__Type", ident), + match_variant_ident: None, + builder_struct_ident: None, + mask_match_variant_ident: None, + mask_type_ident: None, + mask_type_debug_ident: None, + mask_value_ident: None, + mask_value_debug_ident: None, + mask_builder_struct_ident: None, + }, + }) + } + pub(crate) fn write_body( + &self, + target: Path, + names: ParsedStructNames<&Ident, &String>, + is_for_mask: bool, + tokens: &mut TokenStream, + ) { + let Self { + options, + vis, + struct_token, + generics, + fields_kind, + fields, + semi_token, + skip_check_fields, + names: _, + } = self; + let skip_check_fields = *skip_check_fields || is_for_mask; + let ParsedStructNames { + ident: struct_ident, + type_struct_debug_ident, + type_struct_ident, + match_variant_ident, + builder_struct_ident, + mask_match_variant_ident: _, + mask_type_ident, + mask_type_debug_ident: _, + mask_value_ident, + mask_value_debug_ident, + mask_builder_struct_ident: _, + } = names; + let StructOptions { + outline_generated: _, + where_, + target: _, + static_, + connect_inexact, + } = &options.body; + let ValueDeriveGenerics { + generics, + static_type_generics, + } = ValueDeriveGenerics::get(generics.clone(), where_); + let (impl_generics, type_generics, where_clause) = generics.split_for_impl(); + let unskipped_fields = fields + .iter() + .filter(|field| field.options.body.skip.is_none()); + let _field_names = Vec::from_iter(fields.iter().map(|field| field.name.clone())); + let unskipped_field_names = + Vec::from_iter(unskipped_fields.clone().map(|field| field.name.clone())); + let unskipped_field_name_strs = Vec::from_iter( + unskipped_field_names + .iter() + .map(|field_name| field_name.to_token_stream().to_string()), + ); + let unskipped_field_vars = Vec::from_iter( + unskipped_field_names + .iter() + .map(|field_name| format_ident!("__v_{}", field_name)), + ); + let unskipped_field_flips = Vec::from_iter( + unskipped_fields + .clone() + .map(|field| field.options.body.flip.is_some()), + ); + let mut any_fields_skipped = false; + let type_fields = Vec::from_iter(fields.iter().filter_map(|field| { + let ParsedField { + options, + vis, + name, + ty, + } = field; + let FieldOptions { flip: _, skip } = &options.body; + if skip.is_some() { + any_fields_skipped = true; + return None; + } + let ty = if is_for_mask { + parse_quote! { ::fayalite::ty::AsMask<#ty> } + } else { + ty.to_token_stream() + }; + Some(syn::Field { + attrs: vec![], + vis: vis.clone(), + mutability: FieldMutability::None, + ident: match name.clone() { + Member::Named(name) => Some(name), + Member::Unnamed(_) => None, + }, + colon_token: None, + ty: parse_quote! { <#ty as ::fayalite::expr::ToExpr>::Type }, + }) + })); + let field_types = Vec::from_iter(type_fields.iter().map(|field| field.ty.clone())); + let match_variant_fields = Vec::from_iter(fields.iter().zip(&type_fields).map( + |(parsed_field, type_field)| { + let field_ty = &parsed_field.ty; + syn::Field { + ty: parse_quote! { ::fayalite::expr::Expr<#field_ty> }, + ..type_field.clone() + } + }, + )); + + let mask_value_fields = Vec::from_iter(fields.iter().zip(&type_fields).map( + |(parsed_field, type_field)| { + let field_ty = &parsed_field.ty; + syn::Field { + ty: parse_quote! { ::fayalite::ty::AsMask<#field_ty> }, + ..type_field.clone() + } + }, + )); + + let mut type_struct_fields = fields_kind.into_fields(type_fields); + let mut match_variant_fields = fields_kind.into_fields(match_variant_fields); + let mut mask_value_fields = fields_kind.into_fields(mask_value_fields); + let phantom_data_field_name = any_fields_skipped.then(|| { + let phantom_data_field_name = Ident::new("__phantom_data", type_struct_ident.span()); + let member = append_field( + &mut type_struct_fields, + syn::Field { + attrs: vec![], + vis: vis.clone(), + mutability: FieldMutability::None, + ident: Some(phantom_data_field_name.clone()), + colon_token: None, + ty: parse_quote_spanned! {type_struct_ident.span()=> + ::fayalite::__std::marker::PhantomData<#struct_ident #type_generics> + }, + }, + ); + append_field( + &mut match_variant_fields, + syn::Field { + attrs: vec![], + vis: Visibility::Inherited, + mutability: FieldMutability::None, + ident: Some(phantom_data_field_name.clone()), + colon_token: None, + ty: parse_quote_spanned! {type_struct_ident.span()=> + ::fayalite::__std::marker::PhantomData<#struct_ident #type_generics> + }, + }, + ); + append_field( + &mut mask_value_fields, + syn::Field { + attrs: vec![], + vis: Visibility::Inherited, + mutability: FieldMutability::None, + ident: Some(phantom_data_field_name), + colon_token: None, + ty: parse_quote_spanned! {type_struct_ident.span()=> + ::fayalite::__std::marker::PhantomData<#struct_ident #type_generics> + }, + }, + ); + member + }); + let phantom_data_field_name_slice = phantom_data_field_name.as_slice(); + let type_struct = ItemStruct { + attrs: vec![parse_quote! {#[allow(non_camel_case_types)]}], + vis: vis.clone(), + struct_token: *struct_token, + ident: type_struct_ident.clone(), + generics: generics.clone(), + fields: type_struct_fields, + semi_token: *semi_token, + }; + type_struct.to_tokens(tokens); + let match_variant_struct = ItemStruct { + attrs: vec![parse_quote! {#[allow(non_camel_case_types)]}], + vis: vis.clone(), + struct_token: *struct_token, + ident: match_variant_ident.clone(), + generics: generics.clone(), + fields: match_variant_fields, + semi_token: *semi_token, + }; + match_variant_struct.to_tokens(tokens); + let mask_type_body = if is_for_mask { + quote! { + ::fayalite::__std::clone::Clone::clone(self) + } + } else { + let mask_value_struct = ItemStruct { + attrs: vec![parse_quote! {#[allow(non_camel_case_types)]}], + vis: vis.clone(), + struct_token: *struct_token, + ident: mask_value_ident.clone(), + generics: generics.clone(), + fields: mask_value_fields, + semi_token: *semi_token, + }; + mask_value_struct.to_tokens(tokens); + let debug_mask_value_body = match fields_kind { + FieldsKind::Unit => quote! { + f.debug_struct(#mask_value_debug_ident).finish() + }, + FieldsKind::Named(_) => quote! { + f.debug_struct(#mask_value_debug_ident) + #(.field(#unskipped_field_name_strs, &self.#unskipped_field_names))* + .finish() + }, + FieldsKind::Unnamed(_) => quote! { + f.debug_tuple(#mask_value_debug_ident) + #(.field(&self.#unskipped_field_names))* + .finish() + }, + }; + quote! { + #[automatically_derived] + impl #impl_generics ::fayalite::__std::fmt::Debug + for #mask_value_ident #type_generics + #where_clause + { + fn fmt( + &self, + f: &mut ::fayalite::__std::fmt::Formatter<'_>, + ) -> ::fayalite::__std::fmt::Result { + #debug_mask_value_body + } + } + } + .to_tokens(tokens); + quote! { + #mask_type_ident { + #(#unskipped_field_names: + ::fayalite::ty::Type::mask_type(&self.#unskipped_field_names),)* + #(#phantom_data_field_name_slice: ::fayalite::__std::marker::PhantomData,)* + } + } + }; + let debug_type_body = match fields_kind { + FieldsKind::Unit => quote! { + f.debug_struct(#type_struct_debug_ident).finish() + }, + FieldsKind::Named(_) => quote! { + f.debug_struct(#type_struct_debug_ident) + #(.field(#unskipped_field_name_strs, &self.#unskipped_field_names))* + .finish() + }, + FieldsKind::Unnamed(_) => quote! { + f.debug_tuple(#type_struct_debug_ident) + #(.field(&self.#unskipped_field_names))* + .finish() + }, + }; + for the_struct_ident in [&type_struct_ident, match_variant_ident] + .into_iter() + .chain(is_for_mask.then_some(mask_value_ident)) + { + derive_clone_hash_eq_partialeq_for_struct( + the_struct_ident, + &generics, + &Vec::from_iter( + unskipped_field_names + .iter() + .cloned() + .chain(phantom_data_field_name.clone()), + ), + ) + .to_tokens(tokens); + } + let check_v = format_ident!("__v"); + let field_checks = Vec::from_iter(fields.iter().map(|ParsedField { ty, name, .. }| { + quote_spanned! {ty.span()=> + __check_field(#check_v.#name); + } + })); + if static_.is_some() { + let (impl_generics, type_generics, where_clause) = + static_type_generics.split_for_impl(); + quote! { + #[automatically_derived] + impl #impl_generics ::fayalite::ty::StaticType for #type_struct_ident #type_generics + #where_clause + { + fn static_type() -> Self { + Self { + #(#unskipped_field_names: ::fayalite::ty::StaticType::static_type(),)* + #(#phantom_data_field_name_slice: + ::fayalite::__std::marker::PhantomData,)* + } + } + } + } + .to_tokens(tokens); + } + if !skip_check_fields { + quote! { + fn __check_field(_v: T) + where + ::Type: ::fayalite::ty::Type, + {} + fn __check_fields #impl_generics(#check_v: #target #type_generics) + #where_clause + { + #(#field_checks)* + } + } + .to_tokens(tokens); + } + let mut builder = Builder::new(builder_struct_ident.clone(), vis.clone()); + for field in unskipped_fields.clone() { + builder.insert_field( + field.name.clone(), + |v| { + parse_quote_spanned! {v.span()=> + ::fayalite::expr::ToExpr::to_expr(&#v) + } + }, + |t| { + parse_quote_spanned! {t.span()=> + ::fayalite::expr::Expr<< + <#t as ::fayalite::expr::ToExpr>::Type + as ::fayalite::ty::Type + >::Value> + } + }, + |t| { + parse_quote_spanned! {t.span()=> + where + #t: ::fayalite::expr::ToExpr, + } + }, + ); + } + let builder = builder.finish_filling_in_fields(); + builder.to_tokens(tokens); + let build_type_fields = + Vec::from_iter(unskipped_fields.clone().map(|ParsedField { name, .. }| { + let builder_field_name = &builder.get_field(name).unwrap().1.builder_field_name; + quote_spanned! {struct_ident.span()=> + #name: ::fayalite::expr::ToExpr::ty(&#builder_field_name) + } + })); + let build_expr_fields = + Vec::from_iter(unskipped_fields.clone().map(|ParsedField { name, .. }| { + let builder_field_name = &builder.get_field(name).unwrap().1.builder_field_name; + quote_spanned! {struct_ident.span()=> + #builder_field_name.to_canonical_dyn() + } + })); + let build_specified_fields = unskipped_fields.clone().map( + |ParsedField { + options: _, + vis: _, + name, + ty, + }| { + let ty = if is_for_mask { + parse_quote_spanned! {name.span()=> + ::fayalite::expr::Expr<::fayalite::ty::AsMask<#ty>> + } + } else { + parse_quote_spanned! {name.span()=> + ::fayalite::expr::Expr<#ty> + } + }; + (name.clone(), ty) + }, + ); + let build_body = parse_quote_spanned! {struct_ident.span()=> + { + ::fayalite::expr::ToExpr::to_expr( + &::fayalite::expr::ops::BundleLiteral::new_unchecked( + ::fayalite::intern::Intern::intern(&[#( + #build_expr_fields, + )*][..]), + #type_struct_ident { + #(#build_type_fields,)* + #(#phantom_data_field_name_slice: + ::fayalite::__std::marker::PhantomData,)* + }, + ), + ) + } + }; + builder + .make_build_method( + &Ident::new("build", struct_ident.span()), + build_specified_fields, + &generics, + &parse_quote_spanned! {struct_ident.span()=> + #type_struct_ident #type_generics + }, + &parse_quote_spanned! {struct_ident.span()=> + ::fayalite::expr::Expr<#target #type_generics> + }, + build_body, + ) + .to_tokens(tokens); + make_connect_impl( + *connect_inexact, + &generics, + &type_struct_ident, + unskipped_fields.clone().map(|field| { + let ty = &field.ty; + parse_quote_spanned! {field.name.span()=> + <#ty as ::fayalite::expr::ToExpr>::Type + } + }), + ) + .to_tokens(tokens); + let empty_builder_ty = builder.ty([], Some(&parse_quote! { Self }), false); + quote! { + #[automatically_derived] + impl #impl_generics ::fayalite::__std::fmt::Debug for #type_struct_ident #type_generics + #where_clause + { + fn fmt( + &self, + f: &mut ::fayalite::__std::fmt::Formatter<'_>, + ) -> ::fayalite::__std::fmt::Result { + #debug_type_body + } + } + + #[automatically_derived] + impl #impl_generics ::fayalite::ty::Type for #type_struct_ident #type_generics + #where_clause + { + type CanonicalType = ::fayalite::bundle::DynBundleType; + type Value = #target #type_generics; + type CanonicalValue = ::fayalite::bundle::DynBundle; + type MaskType = #mask_type_ident #type_generics; + type MaskValue = #mask_value_ident #type_generics; + type MatchVariant = #match_variant_ident #type_generics; + type MatchActiveScope = (); + type MatchVariantAndInactiveScope = ::fayalite::ty::MatchVariantWithoutScope< + #match_variant_ident #type_generics, + >; + type MatchVariantsIter = ::fayalite::__std::iter::Once< + ::MatchVariantAndInactiveScope, + >; + #[allow(unused_variables)] + fn match_variants( + this: ::fayalite::expr::Expr<::Value>, + module_builder: &mut ::fayalite::module::ModuleBuilder< + IO, + ::fayalite::module::NormalModule, + >, + source_location: ::fayalite::source_location::SourceLocation, + ) -> ::MatchVariantsIter + where + ::Type: + ::fayalite::bundle::BundleType, + { + ::fayalite::__std::iter::once(::fayalite::ty::MatchVariantWithoutScope( + #match_variant_ident { + #(#unskipped_field_names: this.field(#unskipped_field_name_strs),)* + #(#phantom_data_field_name_slice: + ::fayalite::__std::marker::PhantomData,)* + }, + )) + } + fn mask_type(&self) -> ::MaskType { + #mask_type_body + } + fn canonical(&self) -> ::CanonicalType { + let fields = ::fayalite::bundle::BundleType::fields(self); + ::fayalite::bundle::DynBundleType::new(fields) + } + fn source_location(&self) -> ::fayalite::source_location::SourceLocation { + ::fayalite::source_location::SourceLocation::caller() + } + fn type_enum(&self) -> ::fayalite::ty::TypeEnum { + ::fayalite::ty::TypeEnum::BundleType(::fayalite::ty::Type::canonical(self)) + } + fn from_canonical_type(t: ::CanonicalType) -> Self { + let [#(#unskipped_field_vars),*] = *::fayalite::bundle::BundleType::fields(&t) + else { + ::fayalite::__std::panic!("wrong number of fields"); + }; + Self { + #(#unskipped_field_names: #unskipped_field_vars.from_canonical_type_helper( + #unskipped_field_name_strs, + #unskipped_field_flips, + ),)* + #(#phantom_data_field_name_slice: ::fayalite::__std::marker::PhantomData,)* + } + } + } + + #[automatically_derived] + impl #impl_generics ::fayalite::ty::TypeWithDeref for #type_struct_ident #type_generics + #where_clause + { + #[allow(unused_variables)] + fn expr_deref(this: &::fayalite::expr::Expr<::Value>) + -> &::MatchVariant + { + ::fayalite::intern::Interned::<_>::into_inner( + ::fayalite::intern::Intern::intern_sized(#match_variant_ident { + #(#unskipped_field_names: this.field(#unskipped_field_name_strs),)* + #(#phantom_data_field_name_slice: + ::fayalite::__std::marker::PhantomData,)* + }), + ) + } + } + + #[automatically_derived] + impl #impl_generics ::fayalite::bundle::BundleType for #type_struct_ident #type_generics + #where_clause + { + type Builder = #empty_builder_ty; + fn builder() -> ::Builder { + #empty_builder_ty::new() + } + fn fields(&self) -> ::fayalite::intern::Interned< + [::fayalite::bundle::FieldType<::fayalite::intern::Interned< + dyn ::fayalite::ty::DynCanonicalType, + >>], + > + { + ::fayalite::intern::Intern::intern(&[#( + ::fayalite::bundle::FieldType { + name: ::fayalite::intern::Intern::intern(#unskipped_field_name_strs), + flipped: #unskipped_field_flips, + ty: ::fayalite::ty::DynType::canonical_dyn( + &self.#unskipped_field_names, + ), + }, + )*][..]) + } + fn fields_hint() -> ::fayalite::bundle::FieldsHint { + ::fayalite::bundle::FieldsHint::new([#( + ::fayalite::bundle::FieldType { + name: ::fayalite::intern::Intern::intern(#unskipped_field_name_strs), + flipped: #unskipped_field_flips, + ty: ::fayalite::bundle::TypeHint::<#field_types>::intern_dyn(), + }, + )*], false) + } + } + + #[automatically_derived] + impl #impl_generics ::fayalite::expr::ToExpr for #target #type_generics + #where_clause + { + type Type = #type_struct_ident #type_generics; + fn ty(&self) -> ::Type { + #type_struct_ident { + #(#unskipped_field_names: ::fayalite::expr::ToExpr::ty( + &self.#unskipped_field_names, + ),)* + #(#phantom_data_field_name_slice: ::fayalite::__std::marker::PhantomData,)* + } + } + fn to_expr(&self) -> ::fayalite::expr::Expr { + ::fayalite::expr::Expr::from_value(self) + } + } + + #[automatically_derived] + impl #impl_generics ::fayalite::ty::Value for #target #type_generics + #where_clause + { + fn to_canonical(&self) -> < + ::Type + as ::fayalite::ty::Type + >::CanonicalValue + { + let ty = ::fayalite::ty::Type::canonical(&::fayalite::expr::ToExpr::ty(self)); + ::fayalite::bundle::DynBundle::new(ty, ::fayalite::__std::sync::Arc::new([ + #(::fayalite::ty::DynValueTrait::to_canonical_dyn( + &self.#unskipped_field_names, + ),)* + ])) + } + } + + #[automatically_derived] + impl #impl_generics ::fayalite::bundle::BundleValue for #target #type_generics + #where_clause + { + } + } + .to_tokens(tokens); + } +} + +impl ToTokens for ParsedStruct { + fn to_tokens(&self, tokens: &mut TokenStream) { + let ParsedStructNames { + ident: struct_ident, + type_struct_debug_ident, + type_struct_ident, + match_variant_ident, + builder_struct_ident, + mask_match_variant_ident, + mask_type_ident, + mask_type_debug_ident, + mask_value_ident, + mask_value_debug_ident, + mask_builder_struct_ident, + } = &self.names; + macro_rules! unwrap_or_set { + ($(let $var:ident =? $fallback_value:expr;)*) => { + $(let $var = $var.clone().unwrap_or_else(|| $fallback_value);)* + }; + } + unwrap_or_set! { + let type_struct_debug_ident =? format!("{struct_ident}::Type"); + let match_variant_ident =? format_ident!("__{}__MatchVariant", struct_ident); + let builder_struct_ident =? format_ident!("__{}__Builder", struct_ident); + let mask_match_variant_ident =? format_ident!("__AsMask__{}__MatchVariant", struct_ident); + let mask_type_ident =? format_ident!("__AsMask__{}__Type", struct_ident); + let mask_type_debug_ident =? format!("AsMask<{struct_ident}>::Type"); + let mask_value_ident =? format_ident!("__AsMask__{}", struct_ident); + let mask_value_debug_ident =? format!("AsMask<{struct_ident}>"); + let mask_builder_struct_ident =? format_ident!("__AsMask__{}__Builder", struct_ident); + } + let target = get_target(&self.options.body.target, struct_ident); + let names = ParsedStructNames { + ident: struct_ident.clone(), + type_struct_debug_ident: &type_struct_debug_ident, + type_struct_ident: type_struct_ident.clone(), + match_variant_ident: &match_variant_ident, + builder_struct_ident: &builder_struct_ident, + mask_match_variant_ident: &mask_match_variant_ident, + mask_type_ident: &mask_type_ident, + mask_type_debug_ident: &mask_type_debug_ident, + mask_value_ident: &mask_value_ident, + mask_value_debug_ident: &mask_value_debug_ident, + mask_builder_struct_ident: &mask_builder_struct_ident, + }; + self.write_body(target, names, false, tokens); + let mask_names = ParsedStructNames { + ident: mask_value_ident.clone(), + type_struct_debug_ident: &mask_type_debug_ident, + type_struct_ident: mask_type_ident.clone(), + match_variant_ident: &mask_match_variant_ident, + builder_struct_ident: &mask_builder_struct_ident, + mask_match_variant_ident: &mask_match_variant_ident, + mask_type_ident: &mask_type_ident, + mask_type_debug_ident: &mask_type_debug_ident, + mask_value_ident: &mask_value_ident, + mask_value_debug_ident: &mask_value_debug_ident, + mask_builder_struct_ident: &mask_builder_struct_ident, + }; + self.write_body(mask_value_ident.clone().into(), mask_names, true, tokens); + } +} + +pub(crate) fn value_derive_struct(mut item: ItemStruct) -> syn::Result { + let item = ParsedStruct::parse(&mut item)?; + let outline_generated = item.options.body.outline_generated; + let mut contents = quote! { + const _: () = { + #item + }; + }; + if outline_generated.is_some() { + contents = crate::outline_generated(contents, "value-struct-"); + } + Ok(contents) +} diff --git a/crates/fayalite-proc-macros/src/lib.rs b/crates/fayalite-proc-macros/src/lib.rs index 73dad09..7d0c65d 100644 --- a/crates/fayalite-proc-macros/src/lib.rs +++ b/crates/fayalite-proc-macros/src/lib.rs @@ -2,7 +2,7 @@ // See Notices.txt for copyright information //! proc macros for `fayalite` //! -//! see `fayalite::hdl_module` and `fayalite::hdl` for docs +//! see `fayalite::hdl_module` and `fayalite::ty::Value` for docs // intentionally not documented here, see `fayalite::hdl_module` for docs #[proc_macro_attribute] @@ -10,19 +10,16 @@ pub fn hdl_module( attr: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> proc_macro::TokenStream { - match fayalite_proc_macros_impl::hdl_module(attr.into(), item.into()) { + match fayalite_proc_macros_impl::module(attr.into(), item.into()) { Ok(retval) => retval.into(), Err(err) => err.into_compile_error().into(), } } -// intentionally not documented here, see `fayalite::hdl` for docs -#[proc_macro_attribute] -pub fn hdl( - attr: proc_macro::TokenStream, - item: proc_macro::TokenStream, -) -> proc_macro::TokenStream { - match fayalite_proc_macros_impl::hdl_attr(attr.into(), item.into()) { +// intentionally not documented here, see `fayalite::ty::Value` for docs +#[proc_macro_derive(Value, attributes(hdl))] +pub fn value_derive(item: proc_macro::TokenStream) -> proc_macro::TokenStream { + match fayalite_proc_macros_impl::value_derive(item.into()) { Ok(retval) => retval.into(), Err(err) => err.into_compile_error().into(), } diff --git a/crates/fayalite/build.rs b/crates/fayalite/build.rs index 24d8f31..429e527 100644 --- a/crates/fayalite/build.rs +++ b/crates/fayalite/build.rs @@ -4,7 +4,6 @@ use fayalite_visit_gen::parse_and_generate; use std::{env, fs, path::Path}; fn main() { - println!("cargo::rustc-check-cfg=cfg(todo)"); let path = "visit_types.json"; println!("cargo::rerun-if-changed={path}"); println!("cargo::rerun-if-changed=build.rs"); diff --git a/crates/fayalite/examples/blinky.rs b/crates/fayalite/examples/blinky.rs index 588ca9a..fcc0c5d 100644 --- a/crates/fayalite/examples/blinky.rs +++ b/crates/fayalite/examples/blinky.rs @@ -1,5 +1,11 @@ use clap::Parser; -use fayalite::{cli, prelude::*}; +use fayalite::{ + cli, + clock::{Clock, ClockDomain}, + hdl_module, + int::{DynUInt, DynUIntType, IntCmp, IntTypeTrait, UInt}, + reset::{SyncReset, ToReset}, +}; #[hdl_module] fn blinky(clock_frequency: u64) { @@ -13,21 +19,21 @@ fn blinky(clock_frequency: u64) { rst: rst.to_reset(), }; let max_value = clock_frequency / 2 - 1; - let int_ty = UInt::range_inclusive(0..=max_value); + let int_ty = DynUIntType::range_inclusive(0..=max_value); #[hdl] - let counter: UInt = reg_builder().clock_domain(cd).reset(0u8.cast_to(int_ty)); + let counter: DynUInt = m.reg_builder().clock_domain(cd).reset(int_ty.literal(0)); #[hdl] - let output_reg: Bool = reg_builder().clock_domain(cd).reset(false); + let output_reg: UInt<1> = m.reg_builder().clock_domain(cd).reset_default(); #[hdl] if counter.cmp_eq(max_value) { - connect_any(counter, 0u8); - connect(output_reg, !output_reg); + m.connect_any(counter, 0u8); + m.connect(output_reg, !output_reg); } else { - connect_any(counter, counter + 1_hdl_u1); + m.connect_any(counter, counter + 1_hdl_u1); } #[hdl] - let led: Bool = m.output(); - connect(led, output_reg); + let led: UInt<1> = m.output(); + m.connect(led, output_reg); } #[derive(Parser)] diff --git a/crates/fayalite/src/_docs.rs b/crates/fayalite/src/_docs.rs index 4d254a7..f7020f9 100644 --- a/crates/fayalite/src/_docs.rs +++ b/crates/fayalite/src/_docs.rs @@ -10,7 +10,7 @@ //! function to add inputs/outputs and other components to that module. //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt}; //! # //! #[hdl_module] //! pub fn example_module() { @@ -18,7 +18,7 @@ //! let an_input: UInt<10> = m.input(); // create an input that is a 10-bit unsigned integer //! #[hdl] //! let some_output: UInt<10> = m.output(); -//! connect(some_output, an_input); // assigns the value of `an_input` to `some_output` +//! m.connect(some_output, an_input); // assigns the value of `an_input` to `some_output` //! } //! ``` diff --git a/crates/fayalite/src/_docs/modules/extern_module.rs b/crates/fayalite/src/_docs/modules/extern_module.rs index bf2034b..353cbe4 100644 --- a/crates/fayalite/src/_docs/modules/extern_module.rs +++ b/crates/fayalite/src/_docs/modules/extern_module.rs @@ -11,6 +11,8 @@ //! * [`parameter_raw_verilog()`][`ModuleBuilder::parameter_raw_verilog`] //! * [`parameter()`][`ModuleBuilder::parameter`] //! +//! These use the [`ExternModule`][`crate::module::ExternModule`] tag type. +//! //! [inputs/outputs]: crate::_docs::modules::module_bodies::hdl_let_statements::inputs_outputs #[allow(unused)] diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_array_expressions.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_array_expressions.rs index c4bbfa4..aabb791 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_array_expressions.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_array_expressions.rs @@ -1,24 +1,24 @@ //! # `#[hdl]` Array Expressions //! -//! `#[hdl]` can be used on Array Expressions to construct an [`Array<[T; N]>`][type@Array] expression: +//! `#[hdl]` can be used on Array Expressions to construct an [`Array<[T; N]>`][Array] expression: //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt, array::Array}; //! # #[hdl_module] //! # fn module() { //! #[hdl] //! let v: UInt<8> = m.input(); //! #[hdl] -//! let w: Array, 4> = wire(); -//! connect( +//! let w: Array<[UInt<8>; 4]> = m.wire(); +//! m.connect( //! w, //! #[hdl] -//! [4_hdl_u8, v, 3_hdl_u8, (v + 7_hdl_u8).cast_to_static()] // you can make an array like this +//! [4_hdl_u8, v, 3_hdl_u8, (v + 7_hdl_u8).cast()] // you can make an array like this //! ); -//! connect( +//! m.connect( //! w, //! #[hdl] -//! [(v + 1_hdl_u8).cast_to_static(); 4] // or you can make an array repeat like this +//! [(v + 1_hdl_u8).cast(); 4] // or you can make an array repeat like this //! ); //! # } //! ``` diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_if_statements.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_if_statements.rs index 46bb568..ffc446c 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_if_statements.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_if_statements.rs @@ -3,7 +3,8 @@ //! `#[hdl] if` statements behave similarly to Rust `if` statements, except they end up as muxes //! and stuff in the final hardware instead of being run when the fayalite module is being created. //! -//! The condition of an `#[hdl] if` statement must have type [`Expr`][Bool]. +//! The condition of an `#[hdl] if` statement must have type [`UInt<1>`] or [`DynUInt`] with +//! `width() == 1` or be an [expression][Expr] of one of those types. //! //! `#[hdl] if` statements' bodies must evaluate to type `()` for now. //! @@ -13,4 +14,7 @@ //! [match]: super::hdl_match_statements #[allow(unused)] -use crate::int::Bool; +use crate::{ + expr::Expr, + int::{DynUInt, UInt}, +}; diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/inputs_outputs.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/inputs_outputs.rs index bfd7521..965d176 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/inputs_outputs.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/inputs_outputs.rs @@ -6,14 +6,14 @@ //! so you should read it. //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt, expr::Expr, array::Array}; //! # #[hdl_module] //! # fn module() { //! #[hdl] //! let my_input: UInt<10> = m.input(); //! let _: Expr> = my_input; // my_input has type Expr> //! #[hdl] -//! let my_output: Array, 3> = m.output(); +//! let my_output: Array<[UInt<10>; 3]> = m.output(); //! # } //! ``` //! diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/instances.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/instances.rs index 2776754..ab82a14 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/instances.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/instances.rs @@ -4,15 +4,15 @@ //! you can create them like so: //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt, array::Array}; //! # #[hdl_module] //! # fn module() { //! #[hdl] -//! let my_instance = instance(some_module()); +//! let my_instance = m.instance(some_module()); //! // now you can use `my_instance`'s inputs/outputs like so: //! #[hdl] //! let v: UInt<3> = m.input(); -//! connect(my_instance.a, v); +//! m.connect(my_instance.a, v); //! #[hdl_module] //! fn some_module() { //! #[hdl] diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/memories.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/memories.rs index e491eef..0f82e4f 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/memories.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/memories.rs @@ -7,12 +7,12 @@ //! //! There are several different ways to create a memory: //! -//! ## using [`memory()`] +//! ## using [`ModuleBuilder::memory()`] //! //! This way you have to set the [`depth`][`MemBuilder::depth`] separately. //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt, clock::ClockDomain}; //! # #[hdl_module] //! # fn module() { //! // first, we need some IO @@ -25,45 +25,45 @@ //! //! // now create the memory //! #[hdl] -//! let mut my_memory = memory(); +//! let mut my_memory = m.memory(); //! my_memory.depth(256); // the memory has 256 elements //! //! let read_port = my_memory.new_read_port(); //! //! // connect up the read port -//! connect_any(read_port.addr, read_addr); -//! connect(read_port.en, true); -//! connect(read_port.clk, cd.clk); -//! connect(read_data, read_port.data); +//! m.connect_any(read_port.addr, read_addr); +//! m.connect(read_port.en, 1_hdl_u1); +//! m.connect(read_port.clk, cd.clk); +//! m.connect(read_data, read_port.data); //! //! // we need more IO for the write port //! #[hdl] //! let write_addr: UInt<8> = m.input(); //! #[hdl] -//! let do_write: Bool = m.input(); +//! let do_write: UInt<1> = m.input(); //! #[hdl] //! let write_data: UInt<8> = m.input(); //! //! let write_port = my_memory.new_write_port(); //! -//! connect_any(write_port.addr, write_addr); -//! connect(write_port.en, do_write); -//! connect(write_port.clk, cd.clk); -//! connect(write_port.data, write_port.data); -//! connect(write_port.mask, true); +//! m.connect_any(write_port.addr, write_addr); +//! m.connect(write_port.en, do_write); +//! m.connect(write_port.clk, cd.clk); +//! m.connect(write_port.data, write_port.data); +//! m.connect(write_port.mask, 1_hdl_u1); //! # } //! ``` //! -//! ## using [`memory_array()`] +//! ## using [`ModuleBuilder::memory_array()`] //! //! this allows you to specify the memory's underlying array type directly. //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt, memory::MemBuilder}; //! # #[hdl_module] //! # fn module() { //! #[hdl] -//! let mut my_memory: MemBuilder, ConstUsize<256>> = memory_array(); +//! let mut my_memory: MemBuilder<[UInt<8>; 256]> = m.memory_array(); //! //! let read_port = my_memory.new_read_port(); //! // ... @@ -72,22 +72,25 @@ //! # } //! ``` //! -//! ## using [`memory_with_init()`] +//! ## using [`ModuleBuilder::memory_with_init()`] //! //! This allows you to deduce the memory's array type from the data used to initialize the memory. //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt}; //! # #[hdl_module] //! # fn module() { //! # #[hdl] //! # let read_addr: UInt<2> = m.input(); //! #[hdl] -//! let mut my_memory = memory_with_init([0x12_hdl_u8, 0x34_hdl_u8, 0x56_hdl_u8, 0x78_hdl_u8]); +//! let mut my_memory = m.memory_with_init( +//! #[hdl] +//! [0x12_hdl_u8, 0x34_hdl_u8, 0x56_hdl_u8, 0x78_hdl_u8], +//! ); //! //! let read_port = my_memory.new_read_port(); //! // note that `read_addr` is `UInt<2>` since the memory only has 4 elements -//! connect_any(read_port.addr, read_addr); +//! m.connect_any(read_port.addr, read_addr); //! // ... //! let write_port = my_memory.new_write_port(); //! // ... @@ -95,4 +98,4 @@ //! ``` #[allow(unused)] -use crate::prelude::*; +use crate::{memory::MemBuilder, module::ModuleBuilder}; diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/registers.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/registers.rs index 28db27f..68dfaed 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/registers.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/registers.rs @@ -8,19 +8,19 @@ //! Registers follow [connection semantics], which are unlike assignments in software, so you should read it. //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt, array::Array, clock::ClockDomain}; //! # #[hdl_module] //! # fn module() { //! # #[hdl] -//! # let v: Bool = m.input(); +//! # let v: UInt<1> = m.input(); //! #[hdl] //! let cd: ClockDomain = m.input(); //! #[hdl] -//! let my_register: UInt<8> = reg_builder().clock_domain(cd).reset(8_hdl_u8); +//! let my_register: UInt<8> = m.reg_builder().clock_domain(cd).reset(8_hdl_u8); //! #[hdl] //! if v { //! // my_register is only changed when both `v` is set and `cd`'s clock edge occurs. -//! connect(my_register, 0x45_hdl_u8); +//! m.connect(my_register, 0x45_hdl_u8); //! } //! # } //! ``` diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/wires.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/wires.rs index b22e0fd..532ea21 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/wires.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_let_statements/wires.rs @@ -2,26 +2,26 @@ //! //! Wires are kinda like variables, but unlike registers, //! they have no memory (they're combinatorial). -//! You must [connect] to all wires, so they have a defined value. +//! You must [connect][`ModuleBuilder::connect`] to all wires, so they have a defined value. //! //! Wires create a Rust variable with type [`Expr`] where `T` is the type of the wire. //! //! Wires follow [connection semantics], which are unlike assignments in software, so you should read it. //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt, array::Array, clock::ClockDomain}; //! # #[hdl_module] //! # fn module() { //! # #[hdl] -//! # let v: Bool = m.input(); +//! # let v: UInt<1> = m.input(); //! #[hdl] -//! let my_wire: UInt<8> = wire(); +//! let my_wire: UInt<8> = m.wire(); //! #[hdl] //! if v { -//! connect(my_wire, 0x45_hdl_u8); +//! m.connect(my_wire, 0x45_hdl_u8); //! } else { //! // wires must be connected to under all conditions -//! connect(my_wire, 0x23_hdl_u8); +//! m.connect(my_wire, 0x23_hdl_u8); //! } //! # } //! ``` @@ -29,4 +29,4 @@ //! [connection semantics]: crate::_docs::semantics::connection_semantics #[allow(unused)] -use crate::prelude::*; +use crate::{expr::Expr, module::ModuleBuilder}; diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_literals.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_literals.rs index a6c9b58..d6b1fe4 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_literals.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_literals.rs @@ -2,7 +2,8 @@ //! //! You can have integer literals with an arbitrary number of bits like so: //! -//! `_hdl`-suffixed literals have type [`Expr>`] or [`Expr>`]. +//! `_hdl`-suffixed literals have type [`Expr>`] or [`Expr>`] +//! ... which are basically just [`UInt`] or [`SInt`] converted to an expression. //! //! ``` //! # #[fayalite::hdl_module] diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_match_statements.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_match_statements.rs index c0d4ea6..4f4116e 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_match_statements.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_match_statements.rs @@ -6,4 +6,4 @@ //! `#[hdl] match` statements' bodies must evaluate to type `()` for now. //! //! `#[hdl] match` statements can only match one level of struct/enum pattern for now, -//! e.g. you can match with the pattern `HdlSome(v)`, but not `HdlSome(HdlSome(_))`. +//! e.g. you can match with the pattern `Some(v)`, but not `Some(Some(_))`. diff --git a/crates/fayalite/src/_docs/modules/module_bodies/hdl_struct_variant_expressions.rs b/crates/fayalite/src/_docs/modules/module_bodies/hdl_struct_variant_expressions.rs index 9d63895..314e283 100644 --- a/crates/fayalite/src/_docs/modules/module_bodies/hdl_struct_variant_expressions.rs +++ b/crates/fayalite/src/_docs/modules/module_bodies/hdl_struct_variant_expressions.rs @@ -2,24 +2,27 @@ //! //! Note: Structs are also known as [Bundles] when used in Fayalite, the Bundle name comes from [FIRRTL]. //! -//! [Bundles]: crate::bundle::BundleType +//! [Bundles]: crate::bundle::BundleValue //! [FIRRTL]: https://github.com/chipsalliance/firrtl-spec //! -//! `#[hdl]` can be used on Struct Expressions to construct a value of that -//! struct's type. They can also be used on tuples. +//! `#[hdl]` can be used on Struct/Variant Expressions to construct a value of that +//! struct/variant's type. They can also be used on tuples. //! //! ``` -//! # use fayalite::prelude::*; -//! #[hdl] +//! # use fayalite::{hdl_module, int::UInt, array::Array, ty::Value}; +//! #[derive(Value, Clone, PartialEq, Eq, Hash, Debug)] +//! #[hdl(static)] //! pub struct MyStruct { //! pub a: UInt<8>, //! pub b: UInt<16>, //! } //! -//! #[hdl] +//! #[derive(Value, Clone, PartialEq, Eq, Hash, Debug)] //! pub enum MyEnum { //! A, -//! B(UInt<32>), +//! B { +//! v: UInt<32>, +//! }, //! } //! //! # #[hdl_module] @@ -27,8 +30,8 @@ //! #[hdl] //! let v: UInt<8> = m.input(); //! #[hdl] -//! let my_struct: MyStruct = wire(); -//! connect( +//! let my_struct: MyStruct = m.wire(); +//! m.connect( //! my_struct, //! #[hdl] //! MyStruct { @@ -37,14 +40,15 @@ //! }, //! ); //! #[hdl] -//! let my_enum: MyEnum = wire(); -//! connect( +//! let my_enum: MyEnum = m.wire(); +//! m.connect( //! my_enum, -//! MyEnum.B(12345678_hdl_u32), +//! #[hdl] +//! MyEnum::B { v: 12345678_hdl_u32 }, //! ); //! #[hdl] -//! let some_tuple: (UInt<4>, UInt<12>) = wire(); -//! connect( +//! let some_tuple: (UInt<4>, UInt<12>) = m.wire(); +//! m.connect( //! some_tuple, //! #[hdl] //! (12_hdl_u4, 3421_hdl_u12), @@ -53,4 +57,4 @@ //! ``` #[allow(unused)] -use crate::prelude::*; +use crate::array::Array; diff --git a/crates/fayalite/src/_docs/modules/normal_module.rs b/crates/fayalite/src/_docs/modules/normal_module.rs index f84678e..7fb6c09 100644 --- a/crates/fayalite/src/_docs/modules/normal_module.rs +++ b/crates/fayalite/src/_docs/modules/normal_module.rs @@ -1,4 +1,6 @@ //! # Normal Modules //! +//! These use the [`NormalModule`][`crate::module::NormalModule`] tag type. +//! //! See also: [Extern Modules][`super::extern_module`] //! See also: [Module Bodies][`super::module_bodies`] diff --git a/crates/fayalite/src/_docs/semantics/connection_semantics.rs b/crates/fayalite/src/_docs/semantics/connection_semantics.rs index 41155bf..7c77ff3 100644 --- a/crates/fayalite/src/_docs/semantics/connection_semantics.rs +++ b/crates/fayalite/src/_docs/semantics/connection_semantics.rs @@ -20,60 +20,62 @@ //! Connection Semantics Example: //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt}; //! # #[hdl_module] //! # fn module() { //! #[hdl] -//! let a: UInt<8> = wire(); +//! let a: UInt<8> = m.wire(); //! #[hdl] //! let b: UInt<8> = m.output(); //! //! // doesn't actually affect anything, since `a` is completely overwritten later -//! connect(a, 5_hdl_u8); +//! m.connect(a, 5_hdl_u8); //! //! // here `a` has value `7` since the last connection assigns //! // `7` to `a`, so `b` has value `7` too. -//! connect(b, a); +//! m.connect(b, a); //! //! // this is the last `connect` to `a`, so this `connect` determines `a`'s value -//! connect(a, 7_hdl_u8); +//! m.connect(a, 7_hdl_u8); //! # } //! ``` //! //! # Conditional Connection Semantics //! //! ``` -//! # use fayalite::prelude::*; +//! # use fayalite::{hdl_module, int::UInt}; //! # #[hdl_module] //! # fn module() { //! #[hdl] -//! let cond: Bool = m.input(); +//! let cond: UInt<1> = m.input(); //! #[hdl] -//! let a: UInt<8> = wire(); +//! let a: UInt<8> = m.wire(); //! #[hdl] //! let b: UInt<8> = m.output(); //! //! // this is the last `connect` to `a` when `cond` is `0` -//! connect(a, 5_hdl_u8); +//! m.connect(a, 5_hdl_u8); //! //! // here `a` has value `7` if `cond` is `1` since the last connection assigns //! // `7` to `a`, so `b` has value `7` too, otherwise `a` (and therefore `b`) //! // have value `5` since then the connection assigning `7` is in a //! // conditional block where the condition doesn't hold. -//! connect(b, a); +//! m.connect(b, a); //! //! #[hdl] //! if cond { //! // this is the last `connect` to `a` when `cond` is `1` -//! connect(a, 7_hdl_u8); +//! m.connect(a, 7_hdl_u8); //! } //! # } //! ``` //! //! [conditional block]: self#conditional-connection-semantics +//! [`connect()`]: ModuleBuilder::connect +//! [`connect_any()`]: ModuleBuilder::connect_any //! [wire]: crate::_docs::modules::module_bodies::hdl_let_statements::wires //! [if]: crate::_docs::modules::module_bodies::hdl_if_statements //! [FIRRTL]: https://github.com/chipsalliance/firrtl-spec #[allow(unused)] -use crate::prelude::*; +use crate::module::ModuleBuilder; diff --git a/crates/fayalite/src/annotations.rs b/crates/fayalite/src/annotations.rs index 8e645c3..5e2ba95 100644 --- a/crates/fayalite/src/annotations.rs +++ b/crates/fayalite/src/annotations.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // See Notices.txt for copyright information use crate::{ - expr::target::Target, + expr::Target, intern::{Intern, Interned}, }; use serde::{Deserialize, Serialize}; diff --git a/crates/fayalite/src/array.rs b/crates/fayalite/src/array.rs index d543322..3763cae 100644 --- a/crates/fayalite/src/array.rs +++ b/crates/fayalite/src/array.rs @@ -1,220 +1,671 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // See Notices.txt for copyright information - use crate::{ - expr::{ops::ArrayIndex, Expr, ToExpr}, - int::{DynSize, KnownSize, Size, SizeType, DYN_SIZE}, - intern::{Intern, Interned, LazyInterned}, - module::transform::visit::{Fold, Folder, Visit, Visitor}, + bundle::{BundleType, BundleValue}, + expr::{ + ops::{ArrayIndex, ArrayLiteral, ExprIndex}, + Expr, ToExpr, + }, + intern::{Intern, Interned, InternedCompare, Memoize}, + module::{ + transform::visit::{Fold, Folder, Visit, Visitor}, + ModuleBuilder, NormalModule, + }, source_location::SourceLocation, ty::{ - CanonicalType, MatchVariantWithoutScope, StaticType, Type, TypeProperties, TypeWithDeref, + CanonicalType, CanonicalTypeKind, CanonicalValue, Connect, DynCanonicalType, + DynCanonicalValue, DynType, DynValueTrait, MatchVariantWithoutScope, StaticType, + StaticValue, Type, TypeEnum, Value, ValueEnum, }, - util::ConstUsize, + util::{ConstBool, GenericConstBool, MakeMutSlice}, +}; +use bitvec::{slice::BitSlice, vec::BitVec}; +use std::{ + any::Any, + borrow::{Borrow, BorrowMut}, + fmt, + hash::Hash, + marker::PhantomData, + ops::IndexMut, + sync::Arc, }; -use std::ops::Index; -#[derive(Copy, Clone, PartialEq, Eq, Hash)] -pub struct ArrayType { - element: LazyInterned, - len: Len::SizeType, - type_properties: TypeProperties, +mod sealed { + pub trait Sealed {} } -impl std::fmt::Debug for ArrayType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "Array<{:?}, {}>", self.element, self.len()) +pub trait ValueArrayOrSlice: + sealed::Sealed + + BorrowMut<[::Element]> + + AsRef<[::Element]> + + AsMut<[::Element]> + + Hash + + fmt::Debug + + Eq + + Send + + Sync + + 'static + + IndexMut::Element> + + ToOwned + + InternedCompare +{ + type Element: Value::ElementType>; + type ElementType: Type::Element>; + type LenType: 'static + Copy + Ord + fmt::Debug + Hash + Send + Sync; + type Match: 'static + + Clone + + Eq + + fmt::Debug + + Hash + + Send + + Sync + + BorrowMut<[Expr]>; + type MaskVA: ValueArrayOrSlice< + Element = ::MaskValue, + ElementType = ::MaskType, + LenType = Self::LenType, + MaskVA = Self::MaskVA, + > + ?Sized; + type IsStaticLen: GenericConstBool; + const FIXED_LEN_TYPE: Option; + fn make_match(array: Expr>) -> Self::Match; + fn len_from_len_type(v: Self::LenType) -> usize; + #[allow(clippy::result_unit_err)] + fn try_len_type_from_len(v: usize) -> Result; + fn len_type(&self) -> Self::LenType; + fn len(&self) -> usize; + fn is_empty(&self) -> bool; + fn iter(&self) -> std::slice::Iter { + Borrow::<[_]>::borrow(self).iter() + } + fn clone_to_arc(&self) -> Arc; + fn arc_make_mut(v: &mut Arc) -> &mut Self; + fn arc_to_arc_slice(self: Arc) -> Arc<[Self::Element]>; +} + +impl sealed::Sealed for [T] {} + +impl ValueArrayOrSlice for [V] +where + V::Type: Type, +{ + type Element = V; + type ElementType = V::Type; + type LenType = usize; + type Match = Box<[Expr]>; + type MaskVA = [::MaskValue]; + type IsStaticLen = ConstBool; + const FIXED_LEN_TYPE: Option = None; + + fn make_match(array: Expr>) -> Self::Match { + (0..array.canonical_type().len()) + .map(|index| ArrayIndex::::new_unchecked(array.canonical(), index).to_expr()) + .collect() + } + + fn len_from_len_type(v: Self::LenType) -> usize { + v + } + + fn try_len_type_from_len(v: usize) -> Result { + Ok(v) + } + + fn len_type(&self) -> Self::LenType { + self.len() + } + + fn len(&self) -> usize { + <[_]>::len(self) + } + + fn is_empty(&self) -> bool { + <[_]>::is_empty(self) + } + + fn clone_to_arc(&self) -> Arc { + Arc::from(self) + } + + fn arc_make_mut(v: &mut Arc) -> &mut Self { + MakeMutSlice::make_mut_slice(v) + } + + fn arc_to_arc_slice(self: Arc) -> Arc<[Self::Element]> { + self } } -pub type Array = ArrayType>; +impl sealed::Sealed for [T; N] {} -#[allow(non_upper_case_globals)] -pub const Array: ArrayWithoutGenerics = ArrayWithoutGenerics; -#[allow(non_upper_case_globals)] -pub const ArrayType: ArrayWithoutGenerics = ArrayWithoutGenerics; +impl ValueArrayOrSlice for [V; N] +where + V::Type: Type, +{ + type Element = V; + type ElementType = V::Type; + type LenType = (); + type Match = [Expr; N]; + type MaskVA = [::MaskValue; N]; + type IsStaticLen = ConstBool; + const FIXED_LEN_TYPE: Option = Some(()); -impl ArrayType { - const fn make_type_properties(element: TypeProperties, len: usize) -> TypeProperties { - let TypeProperties { - is_passive, - is_storable, - is_castable_from_bits, - bit_width, - } = element; - let Some(bit_width) = bit_width.checked_mul(len) else { - panic!("array too big"); - }; - TypeProperties { - is_passive, - is_storable, - is_castable_from_bits, - bit_width, + fn make_match(array: Expr>) -> Self::Match { + std::array::from_fn(|index| { + ArrayIndex::::new_unchecked(array.canonical(), index).to_expr() + }) + } + + fn len_from_len_type(_v: Self::LenType) -> usize { + N + } + + fn try_len_type_from_len(v: usize) -> Result { + if v == N { + Ok(()) + } else { + Err(()) } } - pub fn new(element: T, len: Len::SizeType) -> Self { - let type_properties = - Self::make_type_properties(element.canonical().type_properties(), Len::as_usize(len)); + + fn len_type(&self) -> Self::LenType {} + + fn len(&self) -> usize { + N + } + + fn is_empty(&self) -> bool { + N == 0 + } + + fn clone_to_arc(&self) -> Arc { + Arc::new(self.clone()) + } + + fn arc_make_mut(v: &mut Arc) -> &mut Self { + Arc::make_mut(v) + } + + fn arc_to_arc_slice(self: Arc) -> Arc<[Self::Element]> { + self + } +} + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct ArrayType { + element: VA::ElementType, + len: VA::LenType, + bit_width: usize, +} + +pub trait ArrayTypeTrait: + Type< + CanonicalType = ArrayType<[DynCanonicalValue]>, + Value = Array<::ValueArrayOrSlice>, + CanonicalValue = Array<[DynCanonicalValue]>, + MaskType = ArrayType< + <::ValueArrayOrSlice as ValueArrayOrSlice>::MaskVA, + >, + > + From::ValueArrayOrSlice>> + + Into::ValueArrayOrSlice>> + + BorrowMut::ValueArrayOrSlice>> + + sealed::Sealed + + Connect +{ + type ValueArrayOrSlice: ValueArrayOrSlice + + ?Sized; + type Element: Value; + type ElementType: Type; +} + +impl sealed::Sealed for ArrayType {} + +impl ArrayTypeTrait for ArrayType { + type ValueArrayOrSlice = VA; + type Element = VA::Element; + type ElementType = VA::ElementType; +} + +impl Clone for ArrayType { + fn clone(&self) -> Self { Self { - element: LazyInterned::Interned(element.intern_sized()), - len, - type_properties, + element: self.element.clone(), + len: self.len, + bit_width: self.bit_width, } } - pub fn element(&self) -> T { - *self.element +} + +impl Copy for ArrayType where VA::ElementType: Copy {} + +impl ArrayType { + pub fn element(&self) -> &VA::ElementType { + &self.element } - pub fn len(self) -> usize { - Len::as_usize(self.len) + pub fn len(&self) -> usize { + VA::len_from_len_type(self.len) } - pub fn is_empty(self) -> bool { + pub fn is_empty(&self) -> bool { self.len() == 0 } - pub fn type_properties(self) -> TypeProperties { - self.type_properties + pub fn bit_width(&self) -> usize { + self.bit_width } - pub fn as_dyn_array(self) -> Array { - Array::new_dyn(self.element().canonical(), self.len()) + pub fn into_slice_type(self) -> ArrayType<[VA::Element]> { + ArrayType { + len: self.len(), + element: self.element, + bit_width: self.bit_width, + } } - pub fn can_connect(self, rhs: ArrayType) -> bool { - self.len() == rhs.len() - && self - .element() - .canonical() - .can_connect(rhs.element().canonical()) + #[track_caller] + pub fn new_with_len(element: VA::ElementType, len: usize) -> Self { + Self::new_with_len_type( + element, + VA::try_len_type_from_len(len).expect("length should match"), + ) + } + #[track_caller] + pub fn new_with_len_type(element: VA::ElementType, len: VA::LenType) -> Self { + let Some(bit_width) = VA::len_from_len_type(len).checked_mul(element.bit_width()) else { + panic!("array is too big: bit-width overflowed"); + }; + ArrayType { + element, + len, + bit_width, + } } } -impl ArrayType { - pub fn new_static(element: T) -> Self { - Self::new(element, Len::SizeType::default()) - } -} - -impl StaticType for ArrayType { - const TYPE: Self = Self { - element: LazyInterned::new_lazy(&|| T::TYPE.intern_sized()), - len: Len::SIZE, - type_properties: Self::TYPE_PROPERTIES, - }; - const MASK_TYPE: Self::MaskType = ArrayType:: { - element: LazyInterned::new_lazy(&|| T::MASK_TYPE.intern_sized()), - len: Len::SIZE, - type_properties: Self::MASK_TYPE_PROPERTIES, - }; - const TYPE_PROPERTIES: TypeProperties = - Self::make_type_properties(T::TYPE_PROPERTIES, Len::VALUE); - const MASK_TYPE_PROPERTIES: TypeProperties = - Self::make_type_properties(T::MASK_TYPE_PROPERTIES, Len::VALUE); -} - -impl Array { - pub fn new_dyn(element: T, len: usize) -> Self { - Self::new(element, len) - } -} - -impl, Len: Size, State: Folder + ?Sized> Fold for ArrayType { +impl Fold for ArrayType +where + VA::ElementType: Fold, +{ fn fold(self, state: &mut State) -> Result { state.fold_array_type(self) } - - fn default_fold(self, state: &mut State) -> Result::Error> { - Ok(ArrayType::new(self.element().fold(state)?, self.len)) + fn default_fold(self, state: &mut State) -> Result { + Ok(Self::new_with_len_type(self.element.fold(state)?, self.len)) } } -impl, Len: Size, State: Visitor + ?Sized> Visit - for ArrayType +impl Visit for ArrayType +where + VA::ElementType: Visit, { fn visit(&self, state: &mut State) -> Result<(), State::Error> { state.visit_array_type(self) } - fn default_visit(&self, state: &mut State) -> Result<(), State::Error> { - self.element().visit(state) + self.element.visit(state) } } -impl Type for ArrayType { - type BaseType = Array; - type MaskType = ArrayType; - type MatchVariant = Len::ArrayMatch; +impl>, const N: usize> ArrayType<[V; N]> { + pub fn new_array(element: V::Type) -> Self { + ArrayType::new_with_len_type(element, ()) + } +} + +impl StaticType for ArrayType<[V; N]> { + fn static_type() -> Self { + Self::new_array(StaticType::static_type()) + } +} + +impl>> ArrayType<[V]> { + pub fn new_slice(element: V::Type, len: usize) -> Self { + ArrayType::new_with_len_type(element, len) + } +} + +impl Type for ArrayType { + type CanonicalType = ArrayType<[DynCanonicalValue]>; + type Value = Array; + type CanonicalValue = Array<[DynCanonicalValue]>; + type MaskType = ArrayType; + type MaskValue = Array; + type MatchVariant = VA::Match; type MatchActiveScope = (); - type MatchVariantAndInactiveScope = MatchVariantWithoutScope>; + type MatchVariantAndInactiveScope = MatchVariantWithoutScope; type MatchVariantsIter = std::iter::Once; - fn match_variants( - this: Expr, + fn match_variants( + this: Expr, + module_builder: &mut ModuleBuilder, source_location: SourceLocation, - ) -> Self::MatchVariantsIter { - let base = Expr::as_dyn_array(this); - let base_ty = Expr::ty(base); + ) -> Self::MatchVariantsIter + where + IO::Type: BundleType, + { + let _ = module_builder; let _ = source_location; - let retval = Vec::from_iter((0..base_ty.len()).map(|i| ArrayIndex::new(base, i).to_expr())); - std::iter::once(MatchVariantWithoutScope( - Len::ArrayMatch::::try_from(retval) - .ok() - .expect("unreachable"), - )) + std::iter::once(MatchVariantWithoutScope(VA::make_match(this))) } fn mask_type(&self) -> Self::MaskType { - ArrayType::new(self.element().mask_type(), self.len) + #[derive(Clone, Hash, Eq, PartialEq)] + struct ArrayMaskTypeMemoize(PhantomData); + impl Copy for ArrayMaskTypeMemoize {} + impl Memoize for ArrayMaskTypeMemoize { + type Input = ArrayType; + type InputOwned = ArrayType; + type Output = as Type>::MaskType; + + fn inner(self, input: &Self::Input) -> Self::Output { + ArrayType::new_with_len_type(input.element.mask_type(), input.len) + } + } + ArrayMaskTypeMemoize::(PhantomData).get(self) } - fn canonical(&self) -> CanonicalType { - CanonicalType::Array(Array::new_dyn(self.element().canonical(), self.len())) + fn canonical(&self) -> Self::CanonicalType { + ArrayType { + element: self.element.canonical_dyn(), + len: self.len(), + bit_width: self.bit_width, + } } - #[track_caller] - fn from_canonical(canonical_type: CanonicalType) -> Self { - let CanonicalType::Array(array) = canonical_type else { - panic!("expected array"); - }; - Self::new( - T::from_canonical(array.element()), - Len::from_usize(array.len()), - ) - } - fn source_location() -> SourceLocation { + fn source_location(&self) -> SourceLocation { SourceLocation::builtin() } -} -impl TypeWithDeref for ArrayType { - fn expr_deref(this: &Expr) -> &Self::MatchVariant { - let base = Expr::as_dyn_array(*this); - let base_ty = Expr::ty(base); - let retval = Vec::from_iter((0..base_ty.len()).map(|i| ArrayIndex::new(base, i).to_expr())); - Interned::<_>::into_inner(Intern::intern_sized( - Len::ArrayMatch::::try_from(retval) - .ok() - .expect("unreachable"), - )) + fn type_enum(&self) -> TypeEnum { + TypeEnum::ArrayType(self.canonical()) + } + + fn from_canonical_type(t: Self::CanonicalType) -> Self { + Self { + element: VA::ElementType::from_dyn_canonical_type(t.element), + len: VA::try_len_type_from_len(t.len).expect("length should match"), + bit_width: t.bit_width, + } + } + + fn as_dyn_canonical_type_impl(this: &Self) -> Option<&dyn DynCanonicalType> { + Some(::downcast_ref::>( + this, + )?) } } -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)] -pub struct ArrayWithoutGenerics; +impl Connect> + for ArrayType +{ +} -impl Index for ArrayWithoutGenerics { - type Output = ArrayWithoutLen; +impl CanonicalType for ArrayType<[DynCanonicalValue]> { + const CANONICAL_TYPE_KIND: CanonicalTypeKind = CanonicalTypeKind::ArrayType; +} - fn index(&self, element: T) -> &Self::Output { - Interned::<_>::into_inner(Intern::intern_sized(ArrayWithoutLen { element })) +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct Array { + element_ty: VA::ElementType, + value: Arc, +} + +impl Clone for Array { + fn clone(&self) -> Self { + Self { + element_ty: self.element_ty.clone(), + value: self.value.clone(), + } } } -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct ArrayWithoutLen { - element: T, -} +impl ToExpr for Array { + type Type = ArrayType; -impl Index for ArrayWithoutLen { - type Output = ArrayType; + fn ty(&self) -> Self::Type { + ArrayType::new_with_len_type(self.element_ty.clone(), self.value.len_type()) + } - fn index(&self, len: L) -> &Self::Output { - Interned::<_>::into_inner(Intern::intern_sized(ArrayType::new(self.element, len))) + fn to_expr(&self) -> Expr<::Value> { + Expr::from_value(self) + } +} + +impl Value for Array { + fn to_canonical(&self) -> ::CanonicalValue { + Array { + element_ty: self.element_ty.canonical_dyn(), + value: AsRef::<[_]>::as_ref(&*self.value) + .iter() + .map(|v| v.to_canonical_dyn()) + .collect(), + } + } + fn to_bits_impl(this: &Self) -> Interned { + #[derive(Hash, Eq, PartialEq)] + struct ArrayToBitsMemoize(PhantomData); + impl Clone for ArrayToBitsMemoize { + fn clone(&self) -> Self { + *self + } + } + impl Copy for ArrayToBitsMemoize {} + impl Memoize for ArrayToBitsMemoize { + type Input = Array; + type InputOwned = Array; + type Output = Interned; + + fn inner(self, input: &Self::Input) -> Self::Output { + let mut bits = BitVec::with_capacity(input.ty().bit_width()); + for element in AsRef::<[_]>::as_ref(&*input.value).iter() { + bits.extend_from_bitslice(&element.to_bits()); + } + Intern::intern_owned(bits) + } + } + ArrayToBitsMemoize::(PhantomData).get(this) + } +} + +impl CanonicalValue for Array<[DynCanonicalValue]> { + fn value_enum_impl(this: &Self) -> ValueEnum { + ValueEnum::Array(this.clone()) + } + fn to_bits_impl(this: &Self) -> Interned { + Value::to_bits_impl(this) + } +} + +impl Array { + pub fn element_ty(&self) -> &VA::ElementType { + &self.element_ty + } + pub fn len(&self) -> usize { + VA::len_from_len_type(self.value.len_type()) + } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + pub fn value(&self) -> &Arc { + &self.value + } + pub fn set_element(&mut self, index: usize, element: VA::Element) { + assert_eq!(self.element_ty, element.ty()); + VA::arc_make_mut(&mut self.value)[index] = element; + } + pub fn new(element_ty: VA::ElementType, value: Arc) -> Self { + for element in value.iter() { + assert_eq!(element_ty, element.ty()); + } + Self { element_ty, value } + } + pub fn into_slice(self) -> Array<[VA::Element]> { + Array { + element_ty: self.element_ty, + value: self.value.arc_to_arc_slice(), + } + } +} + +impl>> From for Array +where + VA::Element: StaticValue, +{ + fn from(value: T) -> Self { + Self::new(StaticType::static_type(), value.into()) + } +} + +impl, T: StaticType> ToExpr for [E] { + type Type = ArrayType<[T::Value]>; + + fn ty(&self) -> Self::Type { + ArrayType::new_with_len_type(StaticType::static_type(), self.len()) + } + + fn to_expr(&self) -> Expr<::Value> { + let elements = Intern::intern_owned(Vec::from_iter( + self.iter().map(|v| v.to_expr().to_canonical_dyn()), + )); + ArrayLiteral::new_unchecked(elements, self.ty()).to_expr() + } +} + +impl, T: StaticType> ToExpr for Vec { + type Type = ArrayType<[T::Value]>; + + fn ty(&self) -> Self::Type { + <[E]>::ty(self) + } + + fn to_expr(&self) -> Expr<::Value> { + <[E]>::to_expr(self) + } +} + +impl, T: StaticType, const N: usize> ToExpr for [E; N] { + type Type = ArrayType<[T::Value; N]>; + + fn ty(&self) -> Self::Type { + ArrayType::new_with_len_type(StaticType::static_type(), ()) + } + + fn to_expr(&self) -> Expr<::Value> { + let elements = Intern::intern_owned(Vec::from_iter( + self.iter().map(|v| v.to_expr().to_canonical_dyn()), + )); + ArrayLiteral::new_unchecked(elements, self.ty()).to_expr() + } +} + +#[derive(Clone, Debug)] +pub struct ArrayIntoIter { + array: Arc, + indexes: std::ops::Range, +} + +impl Iterator for ArrayIntoIter { + type Item = VA::Element; + + fn next(&mut self) -> Option { + Some(self.array[self.indexes.next()?].clone()) + } + + fn size_hint(&self) -> (usize, Option) { + self.indexes.size_hint() + } +} + +impl std::iter::FusedIterator for ArrayIntoIter {} + +impl ExactSizeIterator for ArrayIntoIter {} + +impl DoubleEndedIterator for ArrayIntoIter { + fn next_back(&mut self) -> Option { + Some(self.array[self.indexes.next_back()?].clone()) + } +} + +impl Array { + pub fn iter(&self) -> std::slice::Iter<'_, VA::Element> { + self.value.iter() + } +} + +impl<'a, VA: ValueArrayOrSlice> IntoIterator for &'a Array { + type Item = &'a VA::Element; + type IntoIter = std::slice::Iter<'a, VA::Element>; + + fn into_iter(self) -> Self::IntoIter { + self.value.iter() + } +} + +impl IntoIterator for Array { + type Item = VA::Element; + type IntoIter = ArrayIntoIter; + + fn into_iter(self) -> Self::IntoIter { + ArrayIntoIter { + indexes: 0..self.len(), + array: self.value, + } + } +} + +#[derive(Clone, Debug)] +pub struct ArrayExprIter { + array: Expr>, + indexes: std::ops::Range, +} + +impl Iterator for ArrayExprIter { + type Item = Expr; + + fn next(&mut self) -> Option { + Some(ExprIndex::expr_index(self.array, self.indexes.next()?)) + } + + fn size_hint(&self) -> (usize, Option) { + self.indexes.size_hint() + } +} + +impl std::iter::FusedIterator for ArrayExprIter {} + +impl ExactSizeIterator for ArrayExprIter {} + +impl DoubleEndedIterator for ArrayExprIter { + fn next_back(&mut self) -> Option { + Some(ExprIndex::expr_index(self.array, self.indexes.next_back()?)) + } +} + +impl IntoIterator for Expr> { + type Item = Expr; + type IntoIter = ArrayExprIter; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl IntoIterator for &'_ Expr> { + type Item = Expr; + type IntoIter = ArrayExprIter; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl Expr> { + pub fn len(self) -> usize { + self.canonical_type().len() + } + pub fn is_empty(self) -> bool { + self.canonical_type().is_empty() + } + pub fn iter(self) -> ArrayExprIter { + ArrayExprIter { + indexes: 0..self.len(), + array: self, + } } } diff --git a/crates/fayalite/src/bundle.rs b/crates/fayalite/src/bundle.rs index 95c87f9..2d43031 100644 --- a/crates/fayalite/src/bundle.rs +++ b/crates/fayalite/src/bundle.rs @@ -1,44 +1,48 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // See Notices.txt for copyright information - use crate::{ expr::{ops::BundleLiteral, Expr, ToExpr}, - intern::{Intern, Interned}, + intern::{ + Intern, Interned, InternedCompare, Memoize, PtrEqWithTypeId, SupportsPtrEqWithTypeId, + }, + module::{ModuleBuilder, NormalModule}, source_location::SourceLocation, ty::{ - impl_match_variant_as_self, CanonicalType, MatchVariantWithoutScope, StaticType, Type, - TypeProperties, TypeWithDeref, + CanonicalType, CanonicalTypeKind, CanonicalValue, Connect, DynCanonicalType, + DynCanonicalValue, DynType, MatchVariantWithoutScope, StaticType, Type, TypeEnum, + TypeWithDeref, Value, ValueEnum, }, }; +use bitvec::{slice::BitSlice, vec::BitVec}; use hashbrown::HashMap; -use std::{fmt, marker::PhantomData}; +use std::{ + fmt, + hash::{Hash, Hasher}, + marker::PhantomData, + sync::Arc, +}; #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] -pub struct BundleField { +pub struct FieldType { pub name: Interned, pub flipped: bool, - pub ty: CanonicalType, + pub ty: T, } -impl BundleField { - pub fn fmt_debug_in_struct(self, field_offset: usize) -> FmtDebugInStruct { - FmtDebugInStruct { - field: self, - field_offset, - } - } -} - -#[derive(Copy, Clone)] -pub struct FmtDebugInStruct { - field: BundleField, +pub struct FmtDebugInStruct<'a, T> { + field: &'a FieldType, field_offset: usize, } -impl fmt::Debug for FmtDebugInStruct { +impl fmt::Debug for FmtDebugInStruct<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { - field: BundleField { name, flipped, ty }, + field: + &FieldType { + name, + flipped, + ref ty, + }, field_offset, } = *self; if flipped { @@ -52,35 +56,94 @@ impl fmt::Debug for FmtDebugInStruct { } } -impl fmt::Display for FmtDebugInStruct { +impl fmt::Display for FmtDebugInStruct<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(self, f) } } +impl FieldType { + pub fn map_ty U>(self, f: F) -> FieldType { + let Self { name, flipped, ty } = self; + FieldType { + name, + flipped, + ty: f(ty), + } + } + pub fn as_ref_ty(&self) -> FieldType<&T> { + FieldType { + name: self.name, + flipped: self.flipped, + ty: &self.ty, + } + } + pub fn fmt_debug_in_struct(&self, field_offset: usize) -> FmtDebugInStruct<'_, T> { + FmtDebugInStruct { + field: self, + field_offset, + } + } +} + +impl FieldType { + pub fn canonical(&self) -> FieldType { + FieldType { + name: self.name, + flipped: self.flipped, + ty: self.ty.canonical(), + } + } + pub fn to_dyn(&self) -> FieldType> { + FieldType { + name: self.name, + flipped: self.flipped, + ty: self.ty.to_dyn(), + } + } + pub fn canonical_dyn(&self) -> FieldType> { + FieldType { + name: self.name, + flipped: self.flipped, + ty: self.ty.canonical_dyn(), + } + } +} + +impl FieldType> { + pub fn from_canonical_type_helper( + self, + expected_name: &str, + expected_flipped: bool, + ) -> T { + assert_eq!(&*self.name, expected_name, "field name doesn't match"); + assert_eq!( + self.flipped, expected_flipped, + "field {expected_name} orientation (flipped or not) doesn't match" + ); + let ty = &*self.ty; + if let Ok(ty) = ::downcast(ty) { + return T::from_canonical_type(ty); + } + let type_name = std::any::type_name::(); + panic!("field {expected_name} type doesn't match, expected: {type_name:?}, got: {ty:?}"); + } +} + #[derive(Clone, Eq)] -struct BundleImpl { - fields: Interned<[BundleField]>, +struct DynBundleTypeImpl { + fields: Interned<[FieldType>]>, name_indexes: HashMap, usize>, field_offsets: Interned<[usize]>, - type_properties: TypeProperties, + is_passive: bool, + is_storable: bool, + is_castable_from_bits: bool, + bit_width: usize, } -impl std::hash::Hash for BundleImpl { - fn hash(&self, state: &mut H) { - self.fields.hash(state); - } -} - -impl PartialEq for BundleImpl { - fn eq(&self, other: &Self) -> bool { - self.fields == other.fields - } -} - -impl std::fmt::Debug for BundleImpl { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("Bundle ")?; +impl fmt::Debug for DynBundleTypeImpl { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "DynBundleType ")?; f.debug_set() .entries( self.fields @@ -92,349 +155,652 @@ impl std::fmt::Debug for BundleImpl { } } -#[derive(Copy, Clone, PartialEq, Eq, Hash)] -pub struct Bundle(Interned); +impl PartialEq for DynBundleTypeImpl { + fn eq(&self, other: &Self) -> bool { + self.fields == other.fields + } +} -impl std::fmt::Debug for Bundle { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl Hash for DynBundleTypeImpl { + fn hash(&self, state: &mut H) { + self.fields.hash(state); + } +} + +#[derive(Copy, Clone, Hash, PartialEq, Eq)] +pub struct DynBundleType(Interned); + +impl fmt::Debug for DynBundleType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } -#[derive(Clone)] -pub struct BundleTypePropertiesBuilder(TypeProperties); - -impl BundleTypePropertiesBuilder { - #[must_use] - pub const fn new() -> Self { - Self(TypeProperties { - is_passive: true, - is_storable: true, - is_castable_from_bits: true, - bit_width: 0, - }) - } - pub const fn clone(&self) -> Self { - Self(self.0) - } - #[must_use] - pub const fn field(self, flipped: bool, field_props: TypeProperties) -> Self { - let Some(bit_width) = self.0.bit_width.checked_add(field_props.bit_width) else { - panic!("bundle is too big: bit-width overflowed"); - }; - if flipped { - Self(TypeProperties { - is_passive: false, - is_storable: false, - is_castable_from_bits: false, - bit_width, - }) - } else { - Self(TypeProperties { - is_passive: self.0.is_passive & field_props.is_passive, - is_storable: self.0.is_storable & field_props.is_storable, - is_castable_from_bits: self.0.is_castable_from_bits - & field_props.is_castable_from_bits, - bit_width, - }) - } - } - pub const fn finish(self) -> TypeProperties { - self.0 - } -} - -impl Bundle { - #[track_caller] - pub fn new(fields: Interned<[BundleField]>) -> Self { +impl DynBundleType { + pub fn new(fields: Interned<[FieldType>]>) -> Self { + let is_passive = fields + .iter() + .all(|field| !field.flipped && field.ty.is_passive()); + let is_storable = fields + .iter() + .all(|field| !field.flipped && field.ty.is_storable()); + let is_castable_from_bits = fields + .iter() + .all(|field| !field.flipped && field.ty.is_castable_from_bits()); let mut name_indexes = HashMap::with_capacity(fields.len()); let mut field_offsets = Vec::with_capacity(fields.len()); - let mut type_props_builder = BundleTypePropertiesBuilder::new(); - for (index, &BundleField { name, flipped, ty }) in fields.iter().enumerate() { + let mut bit_width = 0usize; + for (index, &FieldType { name, ty, .. }) in fields.iter().enumerate() { if let Some(old_index) = name_indexes.insert(name, index) { panic!("duplicate field name {name:?}: at both index {old_index} and {index}"); } - field_offsets.push(type_props_builder.0.bit_width); - type_props_builder = type_props_builder.field(flipped, ty.type_properties()); + field_offsets.push(bit_width); + bit_width = bit_width + .checked_add(ty.bit_width()) + .unwrap_or_else(|| panic!("bundle is too big: bit-width overflowed")); } - Self(Intern::intern_sized(BundleImpl { - fields, - name_indexes, - field_offsets: Intern::intern_owned(field_offsets), - type_properties: type_props_builder.finish(), - })) + Self( + DynBundleTypeImpl { + fields, + name_indexes, + field_offsets: Intern::intern_owned(field_offsets), + is_passive, + is_storable, + is_castable_from_bits, + bit_width, + } + .intern_sized(), + ) + } + pub fn is_passive(self) -> bool { + self.0.is_passive + } + pub fn is_storable(self) -> bool { + self.0.is_storable + } + pub fn is_castable_from_bits(self) -> bool { + self.0.is_castable_from_bits + } + pub fn bit_width(self) -> usize { + self.0.bit_width } pub fn name_indexes(&self) -> &HashMap, usize> { &self.0.name_indexes } - pub fn field_by_name(&self, name: Interned) -> Option { + pub fn field_by_name( + &self, + name: Interned, + ) -> Option>> { Some(self.0.fields[*self.0.name_indexes.get(&name)?]) } pub fn field_offsets(self) -> Interned<[usize]> { self.0.field_offsets } - pub fn type_properties(self) -> TypeProperties { - self.0.type_properties +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct DynBundle { + ty: DynBundleType, + fields: Arc<[DynCanonicalValue]>, +} + +impl DynBundle { + pub fn new(ty: DynBundleType, fields: Arc<[DynCanonicalValue]>) -> Self { + assert_eq!( + ty.fields().len(), + fields.len(), + "field values don't match type" + ); + for (field_ty, field) in ty.fields().iter().zip(fields.iter()) { + assert_eq!(field_ty.ty, field.ty(), "field value doesn't match type"); + } + DynBundle { ty, fields } } - pub fn can_connect(self, rhs: Self) -> bool { - if self.0.fields.len() != rhs.0.fields.len() { - return false; - } - for ( - &BundleField { - name: lhs_name, - flipped: lhs_flipped, - ty: lhs_ty, - }, - &BundleField { - name: rhs_name, - flipped: rhs_flipped, - ty: rhs_ty, - }, - ) in self.0.fields.iter().zip(rhs.0.fields.iter()) - { - if lhs_name != rhs_name || lhs_flipped != rhs_flipped || !lhs_ty.can_connect(rhs_ty) { - return false; - } - } + pub fn fields(&self) -> &Arc<[DynCanonicalValue]> { + &self.fields + } +} + +pub trait TypeHintTrait: Send + Sync + fmt::Debug + SupportsPtrEqWithTypeId { + fn matches(&self, ty: &dyn DynType) -> Result<(), String>; +} + +impl InternedCompare for dyn TypeHintTrait { + type InternedCompareKey = PtrEqWithTypeId; + fn interned_compare_key_ref(this: &Self) -> Self::InternedCompareKey { + Self::get_ptr_eq_with_type_id(this) + } + fn interned_compare_key_weak(this: &std::sync::Weak) -> Self::InternedCompareKey { + Self::get_ptr_eq_with_type_id(&*this.upgrade().unwrap()) + } +} + +pub struct TypeHint(PhantomData); + +impl TypeHint { + pub fn intern_dyn() -> Interned { + Interned::cast_unchecked( + Self(PhantomData).intern_sized(), + |v| -> &dyn TypeHintTrait { v }, + ) + } +} + +impl fmt::Debug for TypeHint { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "TypeHint<{}>", std::any::type_name::()) + } +} + +impl Hash for TypeHint { + fn hash(&self, _state: &mut H) {} +} + +impl Eq for TypeHint {} + +impl PartialEq for TypeHint { + fn eq(&self, _other: &Self) -> bool { true } } -impl Type for Bundle { - type BaseType = Bundle; - type MaskType = Bundle; - impl_match_variant_as_self!(); - fn mask_type(&self) -> Self::MaskType { - Self::new(Interned::from_iter(self.0.fields.into_iter().map( - |BundleField { name, flipped, ty }| BundleField { - name, - flipped, - ty: ty.mask_type(), - }, - ))) +impl Clone for TypeHint { + fn clone(&self) -> Self { + *self } - fn canonical(&self) -> CanonicalType { - CanonicalType::Bundle(*self) +} + +impl Copy for TypeHint {} + +impl TypeHintTrait for TypeHint { + fn matches(&self, ty: &dyn DynType) -> Result<(), String> { + match ty.downcast::() { + Ok(_) => Ok(()), + Err(_) => Err(format!("can't cast {ty:?} to {self:?}")), + } } - #[track_caller] - fn from_canonical(canonical_type: CanonicalType) -> Self { - let CanonicalType::Bundle(bundle) = canonical_type else { - panic!("expected bundle"); +} + +#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] +pub struct FieldsHint { + pub known_fields: Interned<[FieldType>]>, + pub more_fields: bool, +} + +impl FieldsHint { + pub fn new( + known_fields: impl IntoIterator>>, + more_fields: bool, + ) -> Self { + let known_fields = Intern::intern_owned(Vec::from_iter(known_fields)); + Self { + known_fields, + more_fields, + } + } + pub fn check_field(self, index: usize, field: FieldType<&dyn DynType>) -> Result<(), String> { + let Some(&known_field) = self.known_fields.get(index) else { + return if self.more_fields { + Ok(()) + } else { + Err(format!( + "too many fields: name={:?} index={index}", + field.name + )) + }; }; - bundle + let FieldType { + name: known_name, + flipped: known_flipped, + ty: type_hint, + } = known_field; + let FieldType { name, flipped, ty } = field; + if name != known_name { + Err(format!( + "wrong field name {name:?}, expected {known_name:?}" + )) + } else if flipped != known_flipped { + Err(format!( + "wrong field direction: flipped={flipped:?}, expected flipped={known_flipped}" + )) + } else { + type_hint.matches(ty) + } } - fn source_location() -> SourceLocation { +} + +pub trait BundleType: + Type + TypeWithDeref + Connect +where + Self::Value: BundleValue + ToExpr, +{ + type Builder; + fn builder() -> Self::Builder; + fn fields(&self) -> Interned<[FieldType>]>; + fn fields_hint() -> FieldsHint; +} + +pub trait BundleValue: Value +where + ::Type: BundleType, +{ + fn to_bits_impl(this: &Self) -> Interned { + #[derive(Hash, Eq, PartialEq)] + struct ToBitsMemoize(PhantomData); + impl Clone for ToBitsMemoize { + fn clone(&self) -> Self { + *self + } + } + impl Copy for ToBitsMemoize {} + impl>> Memoize for ToBitsMemoize { + type Input = T; + type InputOwned = T; + type Output = Interned; + + fn inner(self, input: &Self::Input) -> Self::Output { + let input = input.to_canonical(); + let mut bits = BitVec::with_capacity(input.ty.bit_width()); + for field in input.fields.iter() { + bits.extend_from_bitslice(&field.to_bits()); + } + Intern::intern_owned(bits) + } + } + ToBitsMemoize::(PhantomData).get(this) + } +} + +pub struct DynBundleMatch; + +impl Type for DynBundleType { + type CanonicalType = DynBundleType; + type Value = DynBundle; + type CanonicalValue = DynBundle; + type MaskType = DynBundleType; + type MaskValue = DynBundle; + type MatchVariant = DynBundleMatch; + type MatchActiveScope = (); + type MatchVariantAndInactiveScope = MatchVariantWithoutScope; + type MatchVariantsIter = std::iter::Once; + + fn match_variants( + this: Expr, + module_builder: &mut ModuleBuilder, + source_location: SourceLocation, + ) -> Self::MatchVariantsIter + where + IO::Type: BundleType, + { + let _ = this; + let _ = module_builder; + let _ = source_location; + std::iter::once(MatchVariantWithoutScope(DynBundleMatch)) + } + + fn mask_type(&self) -> Self::MaskType { + #[derive(Copy, Clone, Eq, PartialEq, Hash)] + struct Impl; + + impl Memoize for Impl { + type Input = DynBundleType; + type InputOwned = DynBundleType; + type Output = DynBundleType; + + fn inner(self, input: &Self::Input) -> Self::Output { + DynBundleType::new(Intern::intern_owned(Vec::from_iter( + input + .fields() + .iter() + .map(|&FieldType { name, flipped, ty }| FieldType { + name, + flipped, + ty: ty.mask_type().canonical(), + }), + ))) + } + } + Impl.get(self) + } + + fn canonical(&self) -> Self::CanonicalType { + *self + } + + fn source_location(&self) -> SourceLocation { SourceLocation::builtin() } + + fn type_enum(&self) -> TypeEnum { + TypeEnum::BundleType(*self) + } + + fn from_canonical_type(t: Self::CanonicalType) -> Self { + t + } + + fn as_dyn_canonical_type_impl(this: &Self) -> Option<&dyn DynCanonicalType> { + Some(this) + } } -pub trait BundleType: Type { - type Builder: Default; - type FilledBuilder: ToExpr; - fn fields(&self) -> Interned<[BundleField]>; -} - -#[derive(Default)] pub struct NoBuilder; -pub struct Unfilled(PhantomData); - -impl Default for Unfilled { - fn default() -> Self { - Self(PhantomData) +impl TypeWithDeref for DynBundleType { + fn expr_deref(this: &Expr) -> &Self::MatchVariant { + let _ = this; + &DynBundleMatch } } -impl BundleType for Bundle { +impl Connect for DynBundleType {} + +impl BundleType for DynBundleType { type Builder = NoBuilder; - type FilledBuilder = Expr; - fn fields(&self) -> Interned<[BundleField]> { + + fn builder() -> Self::Builder { + NoBuilder + } + + fn fields(&self) -> Interned<[FieldType>]> { self.0.fields } + + fn fields_hint() -> FieldsHint { + FieldsHint { + known_fields: [][..].intern(), + more_fields: true, + } + } } -#[derive(Default)] -pub struct TupleBuilder(T); - -macro_rules! impl_tuple_builder_fields { - ( - @impl - { - } - [ - $({ - #[type_var($head_type_var:ident)] - #[field($head_field:ident)] - #[var($head_var:ident)] - })* - ] - { - #[type_var($cur_type_var:ident)] - #[field($cur_field:ident)] - #[var($cur_var:ident)] - } - [ - $({ - #[type_var($tail_type_var:ident)] - #[field($tail_field:ident)] - #[var($tail_var:ident)] - })* - ] - ) => { - impl< - $($head_type_var,)* - $cur_type_var: Type, - $($tail_type_var,)* - > TupleBuilder<( - $($head_type_var,)* - Unfilled<$cur_type_var>, - $($tail_type_var,)* - )> - { - pub fn $cur_field(self, $cur_var: impl ToExpr) -> TupleBuilder<( - $($head_type_var,)* - Expr<$cur_type_var>, - $($tail_type_var,)* - )> - { - let ($($head_var,)* _, $($tail_var,)*) = self.0; - TupleBuilder(($($head_var,)* $cur_var.to_expr(), $($tail_var,)*)) - } - } - }; - ($global:tt [$($head:tt)*] $cur:tt [$next:tt $($tail:tt)*]) => { - impl_tuple_builder_fields!(@impl $global [$($head)*] $cur [$next $($tail)*]); - impl_tuple_builder_fields!($global [$($head)* $cur] $next [$($tail)*]); - }; - ($global:tt [$($head:tt)*] $cur:tt []) => { - impl_tuple_builder_fields!(@impl $global [$($head)*] $cur []); - }; - ($global:tt [$cur:tt $($tail:tt)*]) => { - impl_tuple_builder_fields!($global [] $cur [$($tail)*]); - }; - ($global:tt []) => {}; +impl CanonicalType for DynBundleType { + const CANONICAL_TYPE_KIND: CanonicalTypeKind = CanonicalTypeKind::BundleType; } -macro_rules! impl_tuples { - ([$({#[num = $num:literal, field = $field:ident] $var:ident: $T:ident})*] []) => { - impl_tuple_builder_fields! { - {} - [$({ - #[type_var($T)] - #[field($field)] - #[var($var)] - })*] - } - impl<$($T: Type,)*> Type for ($($T,)*) { - type BaseType = Bundle; - type MaskType = ($($T::MaskType,)*); - type MatchVariant = ($(Expr<$T>,)*); - type MatchActiveScope = (); - type MatchVariantAndInactiveScope = MatchVariantWithoutScope; - type MatchVariantsIter = std::iter::Once; - fn match_variants( - this: Expr, - source_location: SourceLocation, - ) -> Self::MatchVariantsIter { - let _ = this; - let _ = source_location; - std::iter::once(MatchVariantWithoutScope(($(Expr::field(this, stringify!($num)),)*))) - } - fn mask_type(&self) -> Self::MaskType { - let ($($var,)*) = self; - ($($var.mask_type(),)*) - } - fn canonical(&self) -> CanonicalType { - Bundle::new(self.fields()).canonical() - } - #[track_caller] - fn from_canonical(canonical_type: CanonicalType) -> Self { - let CanonicalType::Bundle(bundle) = canonical_type else { - panic!("expected bundle"); - }; - let [$($var,)*] = *bundle.fields() else { - panic!("bundle has wrong number of fields"); - }; - $(let BundleField { name, flipped, ty } = $var; - assert_eq!(&*name, stringify!($num)); - assert_eq!(flipped, false); - let $var = $T::from_canonical(ty);)* - ($($var,)*) - } - fn source_location() -> SourceLocation { - SourceLocation::builtin() +impl ToExpr for DynBundle { + type Type = DynBundleType; + + fn ty(&self) -> Self::Type { + self.ty + } + + fn to_expr(&self) -> Expr<::Value> { + Expr::from_value(self) + } +} + +impl Value for DynBundle { + fn to_canonical(&self) -> ::CanonicalValue { + self.clone() + } + fn to_bits_impl(this: &Self) -> Interned { + BundleValue::to_bits_impl(this) + } +} + +impl BundleValue for DynBundle {} + +impl CanonicalValue for DynBundle { + fn value_enum_impl(this: &Self) -> ValueEnum { + ValueEnum::Bundle(this.clone()) + } + fn to_bits_impl(this: &Self) -> Interned { + BundleValue::to_bits_impl(this) + } +} + +macro_rules! impl_tuple_builder { + ($builder:ident, [ + $(($before_Ts:ident $before_fields:ident $before_members:literal))* + ] [ + ($T:ident $field:ident $m:literal) + $(($after_Ts:ident $after_fields:ident $after_members:literal))* + ]) => { + impl_tuple_builder!($builder, [ + $(($before_Ts $before_fields $before_members))* + ($T $field $m) + ] [ + $(($after_Ts $after_fields $after_members))* + ]); + + impl $builder< + Phantom, + $($before_Ts,)* + (), + $($after_Ts,)* + > { + pub fn $field<$T: ToExpr>(self, $field: $T) -> $builder< + Phantom, + $($before_Ts,)* + Expr<<$T::Type as Type>::Value>, + $($after_Ts,)* + > { + let Self { + $($before_fields,)* + $field: _, + $($after_fields, )* + _phantom: _, + } = self; + let $field = $field.to_expr(); + $builder { + $($before_fields,)* + $field, + $($after_fields,)* + _phantom: PhantomData, + } } } - impl<$($T: Type,)*> BundleType for ($($T,)*) { - type Builder = TupleBuilder<($(Unfilled<$T>,)*)>; - type FilledBuilder = TupleBuilder<($(Expr<$T>,)*)>; - fn fields(&self) -> Interned<[BundleField]> { - let ($($var,)*) = self; - [$(BundleField { name: stringify!($num).intern(), flipped: false, ty: $var.canonical() }),*][..].intern() + }; + ($builder:ident, [$($before:tt)*] []) => {}; +} + +macro_rules! into_unit { + ($($tt:tt)*) => { + () + }; +} + +macro_rules! impl_tuple { + ($builder:ident, $(($T:ident $T2:ident $field:ident $m:tt)),*) => { + pub struct $builder { + $($field: $T,)* + _phantom: PhantomData, + } + + impl_tuple_builder!($builder, [] [$(($T $field $m))*]); + + impl<$($T: Value),*> $builder<($($T,)*), $(Expr<$T>,)*> + where + $($T::Type: Type,)* + { + pub fn build(self) -> Expr<($($T,)*)> { + let Self { + $($field,)* + _phantom: _, + } = self; + BundleLiteral::new_unchecked( + [$($field.to_canonical_dyn()),*][..].intern(), + ($($field.ty(),)*), + ).to_expr() } } - impl<$($T: Type,)*> TypeWithDeref for ($($T,)*) { - fn expr_deref(this: &Expr) -> &Self::MatchVariant { - let _ = this; - Interned::<_>::into_inner(($(Expr::field(*this, stringify!($num)),)*).intern_sized()) - } - } - impl<$($T: StaticType,)*> StaticType for ($($T,)*) { - const TYPE: Self = ($($T::TYPE,)*); - const MASK_TYPE: Self::MaskType = ($($T::MASK_TYPE,)*); - const TYPE_PROPERTIES: TypeProperties = { - let builder = BundleTypePropertiesBuilder::new(); - $(let builder = builder.field(false, $T::TYPE_PROPERTIES);)* - builder.finish() - }; - const MASK_TYPE_PROPERTIES: TypeProperties = { - let builder = BundleTypePropertiesBuilder::new(); - $(let builder = builder.field(false, $T::MASK_TYPE_PROPERTIES);)* - builder.finish() - }; - } + impl<$($T: ToExpr,)*> ToExpr for ($($T,)*) { type Type = ($($T::Type,)*); - fn to_expr(&self) -> Expr { - let ($($var,)*) = self; - $(let $var = $var.to_expr();)* - let ty = ($(Expr::ty($var),)*); - let field_values = [$(Expr::canonical($var)),*]; - BundleLiteral::new(ty, field_values[..].intern()).to_expr() + #[allow(clippy::unused_unit)] + fn ty(&self) -> Self::Type { + let ($($field,)*) = self; + ($($field.ty(),)*) } - } - impl<$($T: Type,)*> ToExpr for TupleBuilder<($(Expr<$T>,)*)> { - type Type = ($($T,)*); - fn to_expr(&self) -> Expr { - let ($($var,)*) = self.0; - let ty = ($(Expr::ty($var),)*); - let field_values = [$(Expr::canonical($var)),*]; - BundleLiteral::new(ty, field_values[..].intern()).to_expr() + fn to_expr(&self) -> Expr<::Value> { + let ($($field,)*) = self; + $(let $field = $field.to_expr();)* + BundleLiteral::new_unchecked( + [$($field.to_canonical_dyn()),*][..].intern(), + ($($field.ty(),)*), + ).to_expr() } } - }; - ([$($lhs:tt)*] [$rhs_first:tt $($rhs:tt)*]) => { - impl_tuples!([$($lhs)*] []); - impl_tuples!([$($lhs)* $rhs_first] [$($rhs)*]); + + impl<$($T, $T2,)*> Connect<($($T2,)*)> for ($($T,)*) + where + $($T: Connect<$T2>,)* + { + } + + impl<$($T: Type,)*> Type for ($($T,)*) + where + $($T::Value: Value,)* + { + type CanonicalType = DynBundleType; + type Value = ($($T::Value,)*); + type CanonicalValue = DynBundle; + type MaskType = ($($T::MaskType,)*); + type MaskValue = ($($T::MaskValue,)*); + type MatchVariant = ($(Expr<$T::Value>,)*); + type MatchActiveScope = (); + type MatchVariantAndInactiveScope = MatchVariantWithoutScope; + type MatchVariantsIter = std::iter::Once; + + fn match_variants( + this: Expr, + module_builder: &mut ModuleBuilder, + source_location: SourceLocation, + ) -> Self::MatchVariantsIter + where + IO::Type: BundleType, + { + let _ = this; + let _ = module_builder; + let _ = source_location; + std::iter::once(MatchVariantWithoutScope(($(this.field(stringify!($m)),)*))) + } + + #[allow(clippy::unused_unit)] + fn mask_type(&self) -> Self::MaskType { + let ($($field,)*) = self; + ($($field.mask_type(),)*) + } + + fn canonical(&self) -> Self::CanonicalType { + DynBundleType::new(self.fields()) + } + + fn source_location(&self) -> SourceLocation { + SourceLocation::builtin() + } + + fn type_enum(&self) -> TypeEnum { + TypeEnum::BundleType(self.canonical()) + } + + #[allow(clippy::unused_unit)] + fn from_canonical_type(t: Self::CanonicalType) -> Self { + let [$($field),*] = *t.fields() else { + panic!("wrong number of fields"); + }; + ($($field.from_canonical_type_helper(stringify!($m), false),)*) + } + } + + impl<$($T: Type,)*> TypeWithDeref for ($($T,)*) + where + $($T::Value: Value,)* + { + fn expr_deref( + this: &::fayalite::expr::Expr<::Value>, + ) -> &::MatchVariant { + let _ = this; + Interned::<_>::into_inner( + Intern::intern_sized(( + $(this.field(stringify!($m)),)* + )), + ) + } + } + + impl<$($T: Type,)*> BundleType for ($($T,)*) + where + $($T::Value: Value,)* + { + type Builder = $builder<($($T::Value,)*), $(into_unit!($T),)*>; + fn builder() -> Self::Builder { + $builder { + $($field: (),)* + _phantom: PhantomData, + } + } + fn fields( + &self, + ) -> Interned<[FieldType>]> { + [ + $(FieldType { + name: stringify!($m).intern(), + flipped: false, + ty: self.$m.canonical_dyn(), + },)* + ][..].intern() + } + fn fields_hint() -> FieldsHint { + FieldsHint::new([ + $(FieldType { + name: stringify!($m).intern(), + flipped: false, + ty: TypeHint::<$T>::intern_dyn(), + },)* + ], false) + } + } + + impl<$($T: StaticType,)*> StaticType for ($($T,)*) + where + $($T::Value: Value,)* + { + #[allow(clippy::unused_unit)] + fn static_type() -> Self { + ($($T::static_type(),)*) + } + } + + impl<$($T: Value,)*> Value for ($($T,)*) + where + $($T::Type: Type,)* + { + fn to_canonical(&self) -> ::CanonicalValue { + let ty = self.ty().canonical(); + DynBundle::new( + ty, + Arc::new([ + $(self.$m.to_canonical_dyn(),)* + ]), + ) + } + fn to_bits_impl(this: &Self) -> Interned { + BundleValue::to_bits_impl(this) + } + } + + impl<$($T: Value,)*> BundleValue for ($($T,)*) + where + $($T::Type: Type,)* + { + } }; } -impl_tuples! { - [] [ - {#[num = 0, field = field_0] v0: T0} - {#[num = 1, field = field_1] v1: T1} - {#[num = 2, field = field_2] v2: T2} - {#[num = 3, field = field_3] v3: T3} - {#[num = 4, field = field_4] v4: T4} - {#[num = 5, field = field_5] v5: T5} - {#[num = 6, field = field_6] v6: T6} - {#[num = 7, field = field_7] v7: T7} - {#[num = 8, field = field_8] v8: T8} - {#[num = 9, field = field_9] v9: T9} - {#[num = 10, field = field_10] v10: T10} - {#[num = 11, field = field_11] v11: T11} - ] -} +impl_tuple!(TupleBuilder0,); +impl_tuple!(TupleBuilder1, (A A2 field_0 0)); +impl_tuple!(TupleBuilder2, (A A2 field_0 0), (B B2 field_1 1)); +impl_tuple!(TupleBuilder3, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2)); +impl_tuple!(TupleBuilder4, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2), (D D2 field_3 3)); +impl_tuple!(TupleBuilder5, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2), (D D2 field_3 3), (E E2 field_4 4)); +impl_tuple!(TupleBuilder6, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2), (D D2 field_3 3), (E E2 field_4 4), (F F2 field_5 5)); +impl_tuple!(TupleBuilder7, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2), (D D2 field_3 3), (E E2 field_4 4), (F F2 field_5 5), (G G2 field_6 6)); +impl_tuple!(TupleBuilder8, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2), (D D2 field_3 3), (E E2 field_4 4), (F F2 field_5 5), (G G2 field_6 6), (H H2 field_7 7)); +impl_tuple!(TupleBuilder9, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2), (D D2 field_3 3), (E E2 field_4 4), (F F2 field_5 5), (G G2 field_6 6), (H H2 field_7 7), (I I2 field_8 8)); +impl_tuple!(TupleBuilder10, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2), (D D2 field_3 3), (E E2 field_4 4), (F F2 field_5 5), (G G2 field_6 6), (H H2 field_7 7), (I I2 field_8 8), (J J2 field_9 9)); +impl_tuple!(TupleBuilder11, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2), (D D2 field_3 3), (E E2 field_4 4), (F F2 field_5 5), (G G2 field_6 6), (H H2 field_7 7), (I I2 field_8 8), (J J2 field_9 9), (K K2 field_10 10)); +impl_tuple!(TupleBuilder12, (A A2 field_0 0), (B B2 field_1 1), (C C2 field_2 2), (D D2 field_3 3), (E E2 field_4 4), (F F2 field_5 5), (G G2 field_6 6), (H H2 field_7 7), (I I2 field_8 8), (J J2 field_9 9), (K K2 field_10 10), (L L2 field_11 11)); diff --git a/crates/fayalite/src/cli.rs b/crates/fayalite/src/cli.rs index f848d36..412e565 100644 --- a/crates/fayalite/src/cli.rs +++ b/crates/fayalite/src/cli.rs @@ -1,5 +1,5 @@ use crate::{ - bundle::{Bundle, BundleType}, + bundle::{BundleType, BundleValue, DynBundle}, firrtl, intern::Interned, module::Module, @@ -82,7 +82,7 @@ impl FirrtlOutput { } impl FirrtlArgs { - fn run_impl(&self, top_module: Module) -> Result { + fn run_impl(&self, top_module: Module) -> Result { let firrtl::FileBackend { top_fir_file_stem, .. } = firrtl::export(self.base.to_firrtl_file_backend(), &top_module)?; @@ -94,14 +94,20 @@ impl FirrtlArgs { } } -impl RunPhase> for FirrtlArgs { +impl RunPhase> for FirrtlArgs +where + T::Type: BundleType, +{ type Output = FirrtlOutput; fn run(&self, top_module: Module) -> Result { self.run_impl(top_module.canonical()) } } -impl RunPhase>> for FirrtlArgs { +impl RunPhase>> for FirrtlArgs +where + T::Type: BundleType, +{ type Output = FirrtlOutput; fn run(&self, top_module: Interned>) -> Result { self.run(*top_module) @@ -222,7 +228,7 @@ enum CliCommand { /// Use like: /// /// ```no_run -/// # use fayalite::prelude::*; +/// # use fayalite::hdl_module; /// # #[hdl_module] /// # fn my_module() {} /// use fayalite::cli; @@ -235,7 +241,7 @@ enum CliCommand { /// You can also use it with a larger [`clap`]-based CLI like so: /// /// ```no_run -/// # use fayalite::prelude::*; +/// # use fayalite::hdl_module; /// # #[hdl_module] /// # fn my_module() {} /// use clap::{Subcommand, Parser}; diff --git a/crates/fayalite/src/clock.rs b/crates/fayalite/src/clock.rs index fe99653..415d7b6 100644 --- a/crates/fayalite/src/clock.rs +++ b/crates/fayalite/src/clock.rs @@ -2,61 +2,111 @@ // See Notices.txt for copyright information use crate::{ expr::{Expr, ToExpr}, - hdl, - int::Bool, + int::{UInt, UIntType}, + intern::Interned, reset::Reset, source_location::SourceLocation, - ty::{impl_match_variant_as_self, CanonicalType, StaticType, Type, TypeProperties}, + ty::{ + impl_match_values_as_self, CanonicalType, CanonicalTypeKind, CanonicalValue, Connect, + DynCanonicalType, StaticType, Type, TypeEnum, Value, ValueEnum, + }, + util::interned_bit, }; +use bitvec::slice::BitSlice; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Default)] -pub struct Clock; +pub struct ClockType; -impl Type for Clock { - type BaseType = Clock; - type MaskType = Bool; +impl ClockType { + pub const fn new() -> Self { + Self + } +} - impl_match_variant_as_self!(); +impl Type for ClockType { + type Value = Clock; + type CanonicalType = ClockType; + type CanonicalValue = Clock; + type MaskType = UIntType<1>; + type MaskValue = UInt<1>; + + impl_match_values_as_self!(); fn mask_type(&self) -> Self::MaskType { - Bool + UIntType::new() } - fn canonical(&self) -> CanonicalType { - CanonicalType::Clock(*self) + fn type_enum(&self) -> TypeEnum { + TypeEnum::Clock(*self) } - fn source_location() -> SourceLocation { + fn from_canonical_type(t: Self::CanonicalType) -> Self { + t + } + + fn canonical(&self) -> Self::CanonicalType { + *self + } + + fn source_location(&self) -> SourceLocation { SourceLocation::builtin() } - fn from_canonical(canonical_type: CanonicalType) -> Self { - let CanonicalType::Clock(retval) = canonical_type else { - panic!("expected Clock"); - }; - retval + fn as_dyn_canonical_type_impl(this: &Self) -> Option<&dyn DynCanonicalType> { + Some(this) } } -impl Clock { - pub fn type_properties(self) -> TypeProperties { - Self::TYPE_PROPERTIES - } - pub fn can_connect(self, _rhs: Self) -> bool { - true +impl Connect for ClockType {} + +impl CanonicalType for ClockType { + const CANONICAL_TYPE_KIND: CanonicalTypeKind = CanonicalTypeKind::Clock; +} + +impl StaticType for ClockType { + fn static_type() -> Self { + Self } } -impl StaticType for Clock { - const TYPE: Self = Self; - const MASK_TYPE: Self::MaskType = Bool; - const TYPE_PROPERTIES: TypeProperties = TypeProperties { - is_passive: true, - is_storable: false, - is_castable_from_bits: true, - bit_width: 1, - }; - const MASK_TYPE_PROPERTIES: TypeProperties = Bool::TYPE_PROPERTIES; +#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] +pub struct Clock(pub bool); + +impl ToExpr for Clock { + type Type = ClockType; + + fn ty(&self) -> Self::Type { + ClockType + } + + fn to_expr(&self) -> Expr { + Expr::from_value(self) + } +} + +impl Value for Clock { + fn to_canonical(&self) -> ::CanonicalValue { + *self + } + fn to_bits_impl(this: &Self) -> Interned { + interned_bit(this.0) + } +} + +impl CanonicalValue for Clock { + fn value_enum_impl(this: &Self) -> ValueEnum { + ValueEnum::Clock(*this) + } + fn to_bits_impl(this: &Self) -> Interned { + interned_bit(this.0) + } +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Value)] +#[hdl(static, outline_generated)] +pub struct ClockDomain { + pub clk: Clock, + pub rst: Reset, } pub trait ToClock { @@ -87,10 +137,10 @@ impl ToClock for Expr { } } -#[hdl] -pub struct ClockDomain { - pub clk: Clock, - pub rst: Reset, +impl ToClock for Clock { + fn to_clock(&self) -> Expr { + self.to_expr() + } } impl ToClock for bool { @@ -98,3 +148,9 @@ impl ToClock for bool { self.to_expr().to_clock() } } + +impl ToClock for UInt<1> { + fn to_clock(&self) -> Expr { + self.to_expr().to_clock() + } +} diff --git a/crates/fayalite/src/enum_.rs b/crates/fayalite/src/enum_.rs index 384414c..6b9c104 100644 --- a/crates/fayalite/src/enum_.rs +++ b/crates/fayalite/src/enum_.rs @@ -1,39 +1,42 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // See Notices.txt for copyright information - +#![allow(clippy::type_complexity)] use crate::{ + bundle::{BundleValue, TypeHintTrait}, expr::{ops::VariantAccess, Expr, ToExpr}, - hdl, - int::Bool, - intern::{Intern, Interned}, + int::{UInt, UIntType}, + intern::{Intern, Interned, MemoizeGeneric}, module::{ - enum_match_variants_helper, EnumMatchVariantAndInactiveScopeImpl, - EnumMatchVariantsIterImpl, Scope, + EnumMatchVariantAndInactiveScopeImpl, EnumMatchVariantsIterImpl, ModuleBuilder, + NormalModule, Scope, }, source_location::SourceLocation, - ty::{CanonicalType, MatchVariantAndInactiveScope, StaticType, Type, TypeProperties}, + ty::{ + CanonicalType, CanonicalTypeKind, CanonicalValue, Connect, DynCanonicalType, + DynCanonicalValue, DynType, MatchVariantAndInactiveScope, Type, TypeEnum, Value, ValueEnum, + }, }; +use bitvec::{order::Lsb0, slice::BitSlice, vec::BitVec, view::BitView}; use hashbrown::HashMap; -use std::{fmt, iter::FusedIterator}; +use std::{ + borrow::Cow, + fmt, + hash::{Hash, Hasher}, + iter::FusedIterator, + marker::PhantomData, +}; -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct EnumVariant { +#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] +pub struct VariantType { pub name: Interned, - pub ty: Option, + pub ty: Option, } -impl EnumVariant { - pub fn fmt_debug_in_enum(self) -> FmtDebugInEnum { - FmtDebugInEnum(self) - } -} +pub struct FmtDebugInEnum<'a, T>(&'a VariantType); -#[derive(Copy, Clone)] -pub struct FmtDebugInEnum(EnumVariant); - -impl fmt::Debug for FmtDebugInEnum { +impl fmt::Debug for FmtDebugInEnum<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let EnumVariant { name, ty } = self.0; + let VariantType { name, ref ty } = *self.0; if let Some(ty) = ty { write!(f, "{name}({ty:?})") } else { @@ -42,22 +45,76 @@ impl fmt::Debug for FmtDebugInEnum { } } -impl fmt::Display for FmtDebugInEnum { +impl fmt::Display for FmtDebugInEnum<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(self, f) } } -#[derive(Clone, Eq)] -struct EnumImpl { - variants: Interned<[EnumVariant]>, - name_indexes: HashMap, usize>, - type_properties: TypeProperties, +impl VariantType { + pub fn map_opt_ty) -> Option>(self, f: F) -> VariantType { + let Self { name, ty } = self; + VariantType { name, ty: f(ty) } + } + pub fn map_ty U>(self, f: F) -> VariantType { + let Self { name, ty } = self; + VariantType { + name, + ty: ty.map(f), + } + } + pub fn as_ref_ty(&self) -> VariantType<&T> { + VariantType { + name: self.name, + ty: self.ty.as_ref(), + } + } + pub fn fmt_debug_in_enum(&self) -> FmtDebugInEnum { + FmtDebugInEnum(self) + } } -impl std::fmt::Debug for EnumImpl { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("Enum ")?; +impl VariantType { + pub fn canonical(&self) -> VariantType { + self.as_ref_ty().map_ty(T::canonical) + } + pub fn to_dyn(&self) -> VariantType> { + self.as_ref_ty().map_ty(T::to_dyn) + } + pub fn canonical_dyn(&self) -> VariantType> { + self.as_ref_ty().map_ty(T::canonical_dyn) + } +} + +impl VariantType> { + pub fn from_canonical_type_helper_has_value(self, expected_name: &str) -> T { + assert_eq!(&*self.name, expected_name, "variant name doesn't match"); + let Some(ty) = self.ty else { + panic!("variant {expected_name} has no value but a value is expected"); + }; + T::from_dyn_canonical_type(ty) + } + pub fn from_canonical_type_helper_no_value(self, expected_name: &str) { + assert_eq!(&*self.name, expected_name, "variant name doesn't match"); + assert!( + self.ty.is_none(), + "variant {expected_name} has a value but is expected to have no value" + ); + } +} + +#[derive(Clone, Eq)] +struct DynEnumTypeImpl { + variants: Interned<[VariantType>]>, + name_indexes: HashMap, usize>, + bit_width: usize, + is_storable: bool, + is_castable_from_bits: bool, +} + +impl fmt::Debug for DynEnumTypeImpl { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "DynEnumType ")?; f.debug_set() .entries( self.variants @@ -68,123 +125,66 @@ impl std::fmt::Debug for EnumImpl { } } -impl std::hash::Hash for EnumImpl { - fn hash(&self, state: &mut H) { - self.variants.hash(state); - } -} - -impl PartialEq for EnumImpl { +impl PartialEq for DynEnumTypeImpl { fn eq(&self, other: &Self) -> bool { self.variants == other.variants } } -#[derive(Copy, Clone, PartialEq, Eq, Hash)] -pub struct Enum(Interned); +impl Hash for DynEnumTypeImpl { + fn hash(&self, state: &mut H) { + self.variants.hash(state); + } +} -impl fmt::Debug for Enum { +#[derive(Copy, Clone, Hash, PartialEq, Eq)] +pub struct DynEnumType(Interned); + +impl fmt::Debug for DynEnumType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } -const fn discriminant_bit_width_impl(variant_count: usize) -> usize { - match variant_count.next_power_of_two().checked_ilog2() { - Some(x) => x as usize, - None => 0, - } +fn discriminant_bit_width_impl(variant_count: usize) -> usize { + variant_count + .next_power_of_two() + .checked_ilog2() + .unwrap_or(0) as usize } -#[derive(Clone)] -pub struct EnumTypePropertiesBuilder { - type_properties: TypeProperties, - variant_count: usize, -} - -impl EnumTypePropertiesBuilder { - #[must_use] - pub const fn new() -> Self { - Self { - type_properties: TypeProperties { - is_passive: true, - is_storable: true, - is_castable_from_bits: true, - bit_width: 0, - }, - variant_count: 0, - } - } - pub const fn clone(&self) -> Self { - Self { ..*self } - } - #[must_use] - pub const fn variant(self, field_props: Option) -> Self { - let Self { - mut type_properties, - variant_count, - } = self; - if let Some(TypeProperties { - is_passive, - is_storable, - is_castable_from_bits, - bit_width, - }) = field_props - { - assert!(is_passive, "variant type must be a passive type"); - type_properties = TypeProperties { - is_passive: true, - is_storable: type_properties.is_storable & is_storable, - is_castable_from_bits: type_properties.is_castable_from_bits - & is_castable_from_bits, - bit_width: if type_properties.bit_width < bit_width { - bit_width - } else { - type_properties.bit_width - }, - }; - } - Self { - type_properties, - variant_count: variant_count + 1, - } - } - pub const fn finish(self) -> TypeProperties { - assert!( - self.variant_count != 0, - "zero-variant enums aren't yet supported: \ - https://github.com/chipsalliance/firrtl-spec/issues/208", - ); - let Some(bit_width) = self - .type_properties - .bit_width - .checked_add(discriminant_bit_width_impl(self.variant_count)) - else { - panic!("enum is too big: bit-width overflowed"); - }; - TypeProperties { - bit_width, - ..self.type_properties - } - } -} - -impl Enum { +impl DynEnumType { #[track_caller] - pub fn new(variants: Interned<[EnumVariant]>) -> Self { + pub fn new(variants: Interned<[VariantType>]>) -> Self { + assert!(!variants.is_empty(), "zero-variant enums aren't yet supported: https://github.com/chipsalliance/firrtl-spec/issues/208"); let mut name_indexes = HashMap::with_capacity(variants.len()); - let mut type_props_builder = EnumTypePropertiesBuilder::new(); - for (index, EnumVariant { name, ty }) in variants.iter().enumerate() { - if let Some(old_index) = name_indexes.insert(*name, index) { + let mut body_bit_width = 0usize; + let mut is_storable = true; + let mut is_castable_from_bits = true; + for (index, &VariantType { name, ty }) in variants.iter().enumerate() { + if let Some(old_index) = name_indexes.insert(name, index) { panic!("duplicate variant name {name:?}: at both index {old_index} and {index}"); } - type_props_builder = type_props_builder.variant(ty.map(CanonicalType::type_properties)); + if let Some(ty) = ty { + assert!( + ty.is_passive(), + "variant type must be a passive type: {ty:?}" + ); + body_bit_width = body_bit_width.max(ty.bit_width()); + is_storable &= ty.is_storable(); + is_castable_from_bits &= ty.is_castable_from_bits(); + } } + let bit_width = body_bit_width + .checked_add(discriminant_bit_width_impl(variants.len())) + .unwrap_or_else(|| panic!("enum is too big: bit-width overflowed")); Self( - EnumImpl { + DynEnumTypeImpl { variants, name_indexes, - type_properties: type_props_builder.finish(), + bit_width, + is_storable, + is_castable_from_bits, } .intern_sized(), ) @@ -192,62 +192,233 @@ impl Enum { pub fn discriminant_bit_width(self) -> usize { discriminant_bit_width_impl(self.variants().len()) } - pub fn type_properties(self) -> TypeProperties { - self.0.type_properties + pub fn is_passive(self) -> bool { + true + } + pub fn is_storable(self) -> bool { + self.0.is_storable + } + pub fn is_castable_from_bits(self) -> bool { + self.0.is_castable_from_bits + } + pub fn bit_width(self) -> usize { + self.0.bit_width } pub fn name_indexes(&self) -> &HashMap, usize> { &self.0.name_indexes } - pub fn can_connect(self, rhs: Self) -> bool { - if self.0.variants.len() != rhs.0.variants.len() { - return false; +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct DynEnum { + ty: DynEnumType, + variant_index: usize, + variant_value: Option, +} + +impl DynEnum { + #[track_caller] + pub fn new_by_index( + ty: DynEnumType, + variant_index: usize, + variant_value: Option, + ) -> Self { + let variant = ty.variants()[variant_index]; + assert_eq!( + variant_value.as_ref().map(|v| v.ty()), + variant.ty, + "variant value doesn't match type" + ); + Self { + ty, + variant_index, + variant_value, } - for ( - &EnumVariant { - name: lhs_name, - ty: lhs_ty, - }, - &EnumVariant { - name: rhs_name, - ty: rhs_ty, - }, - ) in self.0.variants.iter().zip(rhs.0.variants.iter()) - { - if lhs_name != rhs_name { - return false; - } - match (lhs_ty, rhs_ty) { - (None, None) => {} - (None, Some(_)) | (Some(_), None) => return false, - (Some(lhs_ty), Some(rhs_ty)) => { - if !lhs_ty.can_connect(rhs_ty) { - return false; - } - } + } + #[track_caller] + pub fn new_by_name( + ty: DynEnumType, + variant_name: Interned, + variant_value: Option, + ) -> Self { + let variant_index = ty.name_indexes()[&variant_name]; + Self::new_by_index(ty, variant_index, variant_value) + } + pub fn variant_index(&self) -> usize { + self.variant_index + } + pub fn variant_value(&self) -> &Option { + &self.variant_value + } + pub fn variant_with_type(&self) -> VariantType> { + self.ty.variants()[self.variant_index] + } + pub fn variant_name(&self) -> Interned { + self.variant_with_type().name + } + pub fn variant_type(&self) -> Option> { + self.variant_with_type().ty + } + pub fn variant_with_value(&self) -> VariantType<&DynCanonicalValue> { + self.variant_with_type() + .map_opt_ty(|_| self.variant_value.as_ref()) + } +} + +#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] +pub struct VariantsHint { + pub known_variants: Interned<[VariantType>]>, + pub more_variants: bool, +} + +impl VariantsHint { + pub fn new( + known_variants: impl IntoIterator>>, + more_variants: bool, + ) -> Self { + let known_variants = Intern::intern_owned(Vec::from_iter(known_variants)); + Self { + known_variants, + more_variants, + } + } + pub fn check_variant( + self, + index: usize, + variant: VariantType<&dyn DynType>, + ) -> Result<(), String> { + let Some(&known_variant) = self.known_variants.get(index) else { + return if self.more_variants { + Ok(()) + } else { + Err(format!( + "too many variants: name={:?} index={index}", + variant.name + )) + }; + }; + let VariantType { + name: known_name, + ty: type_hint, + } = known_variant; + let VariantType { name, ty } = variant; + if name != known_name { + Err(format!( + "wrong variant name {name:?}, expected {known_name:?}" + )) + } else { + match (ty, type_hint) { + (Some(ty), Some(type_hint)) => type_hint.matches(ty), + (None, None) => Ok(()), + (None, Some(_)) => Err(format!( + "expected variant {name:?} to have type, no type provided" + )), + (Some(_), None) => Err(format!( + "expected variant {name:?} to have no type, but a type was provided" + )), } } - true } } pub trait EnumType: Type< - BaseType = Enum, - MaskType = Bool, - MatchActiveScope = Scope, - MatchVariantAndInactiveScope = EnumMatchVariantAndInactiveScope, - MatchVariantsIter = EnumMatchVariantsIter, -> + CanonicalType = DynEnumType, + CanonicalValue = DynEnum, + MaskType = UIntType<1>, + MaskValue = UInt<1>, + MatchActiveScope = Scope, + MatchVariantAndInactiveScope = EnumMatchVariantAndInactiveScope, + MatchVariantsIter = EnumMatchVariantsIter, + > + Connect +where + Self::Value: EnumValue + ToExpr, { - fn variants(&self) -> Interned<[EnumVariant]>; + type Builder; fn match_activate_scope( v: Self::MatchVariantAndInactiveScope, ) -> (Self::MatchVariant, Self::MatchActiveScope); + fn builder() -> Self::Builder; + fn variants(&self) -> Interned<[VariantType>]>; + fn variants_hint() -> VariantsHint; + #[allow(clippy::result_unit_err)] + fn variant_to_bits( + &self, + variant_index: usize, + variant_value: Option<&VariantValue>, + ) -> Result, ()> { + #[derive(Hash, Eq, PartialEq)] + struct VariantToBitsMemoize(PhantomData<(E, V)>); + impl Clone for VariantToBitsMemoize { + fn clone(&self) -> Self { + *self + } + } + impl Copy for VariantToBitsMemoize {} + impl< + E: EnumType>, + V: ToExpr + Eq + Hash + Send + Sync + 'static + Clone, + > MemoizeGeneric for VariantToBitsMemoize + { + type InputRef<'a> = (&'a E, usize, Option<&'a V>); + type InputOwned = (E, usize, Option); + type InputCow<'a> = (Cow<'a, E>, usize, Option>); + type Output = Result, ()>; + + fn input_borrow(input: &Self::InputOwned) -> Self::InputRef<'_> { + (&input.0, input.1, input.2.as_ref()) + } + fn input_eq(a: Self::InputRef<'_>, b: Self::InputRef<'_>) -> bool { + a == b + } + fn input_cow_into_owned(input: Self::InputCow<'_>) -> Self::InputOwned { + (input.0.into_owned(), input.1, input.2.map(Cow::into_owned)) + } + fn input_cow_borrow<'a>(input: &'a Self::InputCow<'_>) -> Self::InputRef<'a> { + (&input.0, input.1, input.2.as_deref()) + } + fn input_cow_from_owned<'a>(input: Self::InputOwned) -> Self::InputCow<'a> { + (Cow::Owned(input.0), input.1, input.2.map(Cow::Owned)) + } + fn input_cow_from_ref(input: Self::InputRef<'_>) -> Self::InputCow<'_> { + (Cow::Borrowed(input.0), input.1, input.2.map(Cow::Borrowed)) + } + fn inner(self, input: Self::InputRef<'_>) -> Self::Output { + let (ty, variant_index, variant_value) = input; + let ty = ty.canonical(); + let mut bits = BitVec::with_capacity(ty.bit_width()); + bits.extend_from_bitslice( + &variant_index.view_bits::()[..ty.discriminant_bit_width()], + ); + if let Some(variant_value) = variant_value { + bits.extend_from_bitslice(&variant_value.to_expr().to_literal_bits()?); + } + bits.resize(ty.bit_width(), false); + Ok(Intern::intern_owned(bits)) + } + } + VariantToBitsMemoize::(PhantomData).get(( + self, + variant_index, + variant_value, + )) + } } -pub struct EnumMatchVariantAndInactiveScope(EnumMatchVariantAndInactiveScopeImpl); +pub trait EnumValue: Value +where + ::Type: EnumType, +{ +} -impl MatchVariantAndInactiveScope for EnumMatchVariantAndInactiveScope { +pub struct EnumMatchVariantAndInactiveScope(EnumMatchVariantAndInactiveScopeImpl) +where + T::Value: EnumValue; + +impl MatchVariantAndInactiveScope for EnumMatchVariantAndInactiveScope +where + T::Value: EnumValue, +{ type MatchVariant = T::MatchVariant; type MatchActiveScope = Scope; @@ -256,22 +427,36 @@ impl MatchVariantAndInactiveScope for EnumMatchVariantAndInactiveSc } } -impl EnumMatchVariantAndInactiveScope { - pub fn variant_access(&self) -> VariantAccess { +impl EnumMatchVariantAndInactiveScope +where + T::Value: EnumValue, +{ + pub fn variant_access(&self) -> Interned>> { self.0.variant_access() } - pub fn activate(self) -> (VariantAccess, Scope) { + pub fn activate( + self, + ) -> ( + Interned>>, + Scope, + ) { self.0.activate() } } #[derive(Clone)] -pub struct EnumMatchVariantsIter { +pub struct EnumMatchVariantsIter +where + T::Value: EnumValue, +{ pub(crate) inner: EnumMatchVariantsIterImpl, pub(crate) variant_index: std::ops::Range, } -impl Iterator for EnumMatchVariantsIter { +impl Iterator for EnumMatchVariantsIter +where + T::Value: EnumValue, +{ type Item = EnumMatchVariantAndInactiveScope; fn next(&mut self) -> Option { @@ -285,15 +470,21 @@ impl Iterator for EnumMatchVariantsIter { } } -impl ExactSizeIterator for EnumMatchVariantsIter { +impl ExactSizeIterator for EnumMatchVariantsIter +where + T::Value: EnumValue, +{ fn len(&self) -> usize { self.variant_index.len() } } -impl FusedIterator for EnumMatchVariantsIter {} +impl FusedIterator for EnumMatchVariantsIter where T::Value: EnumValue {} -impl DoubleEndedIterator for EnumMatchVariantsIter { +impl DoubleEndedIterator for EnumMatchVariantsIter +where + T::Value: EnumValue, +{ fn next_back(&mut self) -> Option { self.variant_index.next_back().map(|variant_index| { EnumMatchVariantAndInactiveScope(self.inner.for_variant_index(variant_index)) @@ -301,66 +492,129 @@ impl DoubleEndedIterator for EnumMatchVariantsIter { } } -impl EnumType for Enum { - fn match_activate_scope( - v: Self::MatchVariantAndInactiveScope, - ) -> (Self::MatchVariant, Self::MatchActiveScope) { - let (expr, scope) = v.0.activate(); - (expr.variant_type().map(|_| expr.to_expr()), scope) - } - fn variants(&self) -> Interned<[EnumVariant]> { - self.0.variants - } -} - -impl Type for Enum { - type BaseType = Enum; - type MaskType = Bool; - type MatchVariant = Option>; +impl Type for DynEnumType { + type CanonicalType = DynEnumType; + type Value = DynEnum; + type CanonicalValue = DynEnum; + type MaskType = UIntType<1>; + type MaskValue = UInt<1>; + type MatchVariant = Option>; type MatchActiveScope = Scope; type MatchVariantAndInactiveScope = EnumMatchVariantAndInactiveScope; type MatchVariantsIter = EnumMatchVariantsIter; - fn match_variants( - this: Expr, + fn match_variants( + this: Expr, + module_builder: &mut ModuleBuilder, source_location: SourceLocation, - ) -> Self::MatchVariantsIter { - enum_match_variants_helper(this, source_location) + ) -> Self::MatchVariantsIter + where + IO::Type: crate::bundle::BundleType, + { + module_builder.enum_match_variants_helper(this, source_location) } fn mask_type(&self) -> Self::MaskType { - Bool + UIntType::new() } - fn canonical(&self) -> CanonicalType { - CanonicalType::Enum(*self) + fn canonical(&self) -> Self::CanonicalType { + *self } - #[track_caller] - fn from_canonical(canonical_type: CanonicalType) -> Self { - let CanonicalType::Enum(retval) = canonical_type else { - panic!("expected enum"); - }; - retval - } - fn source_location() -> SourceLocation { + fn source_location(&self) -> SourceLocation { SourceLocation::builtin() } + + fn type_enum(&self) -> TypeEnum { + TypeEnum::EnumType(*self) + } + + fn from_canonical_type(t: Self::CanonicalType) -> Self { + t + } + + fn as_dyn_canonical_type_impl(this: &Self) -> Option<&dyn DynCanonicalType> { + Some(this) + } } -#[hdl] -pub enum HdlOption { - HdlNone, - HdlSome(T), +impl Connect for DynEnumType {} + +pub struct NoBuilder; + +impl EnumType for DynEnumType { + type Builder = NoBuilder; + + fn match_activate_scope( + v: Self::MatchVariantAndInactiveScope, + ) -> (Self::MatchVariant, Self::MatchActiveScope) { + let (expr, scope) = v.0.activate(); + (expr.variant_type().ty.map(|_| expr.to_expr()), scope) + } + + fn builder() -> Self::Builder { + NoBuilder + } + + fn variants(&self) -> Interned<[VariantType>]> { + self.0.variants + } + + fn variants_hint() -> VariantsHint { + VariantsHint { + known_variants: [][..].intern(), + more_variants: true, + } + } } -#[allow(non_snake_case)] -pub fn HdlNone() -> Expr> { - HdlOption[T::TYPE].HdlNone() +impl CanonicalType for DynEnumType { + const CANONICAL_TYPE_KIND: CanonicalTypeKind = CanonicalTypeKind::EnumType; } -#[allow(non_snake_case)] -pub fn HdlSome(value: impl ToExpr) -> Expr> { - let value = value.to_expr(); - HdlOption[Expr::ty(value)].HdlSome(value) +impl ToExpr for DynEnum { + type Type = DynEnumType; + + fn ty(&self) -> Self::Type { + self.ty + } + + fn to_expr(&self) -> Expr<::Value> { + Expr::from_value(self) + } +} + +impl Value for DynEnum { + fn to_canonical(&self) -> ::CanonicalValue { + self.clone() + } + fn to_bits_impl(this: &Self) -> Interned { + this.ty + .variant_to_bits(this.variant_index, this.variant_value.as_ref()) + .unwrap() + } +} + +impl EnumValue for DynEnum {} + +impl CanonicalValue for DynEnum { + fn value_enum_impl(this: &Self) -> ValueEnum { + ValueEnum::Enum(this.clone()) + } + fn to_bits_impl(this: &Self) -> Interned { + this.ty + .variant_to_bits(this.variant_index, this.variant_value.as_ref()) + .unwrap() + } +} + +mod impl_option { + #[allow(dead_code)] + #[derive(crate::ty::Value)] + #[hdl(target(std::option::Option), connect_inexact, outline_generated)] + pub enum Option { + None, + Some(T), + } } diff --git a/crates/fayalite/src/expr.rs b/crates/fayalite/src/expr.rs index 607ff1e..2b8f2b2 100644 --- a/crates/fayalite/src/expr.rs +++ b/crates/fayalite/src/expr.rs @@ -1,102 +1,96 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // See Notices.txt for copyright information - use crate::{ - array::{Array, ArrayType}, - bundle::{Bundle, BundleType}, - enum_::{Enum, EnumType}, - expr::{ - ops::ExprCastTo, - target::{GetTarget, Target}, - }, - int::{Bool, DynSize, IntType, SIntType, SIntValue, Size, UInt, UIntType, UIntValue}, - intern::{Intern, Interned}, + array::ArrayType, + bundle::{BundleType, BundleValue, DynBundle, DynBundleType, FieldType}, + enum_::{DynEnumType, EnumType, EnumValue}, + int::{DynSIntType, DynUInt, DynUIntType, IntValue, StaticOrDynIntType, UInt, UIntType}, + intern::{Intern, Interned, InternedCompare, PtrEqWithTypeId, SupportsPtrEqWithTypeId}, memory::{DynPortType, MemPort, PortType}, module::{ transform::visit::{Fold, Folder, Visit, Visitor}, - Instance, ModuleIO, + Instance, ModuleIO, TargetName, }, reg::Reg, - ty::{CanonicalType, StaticType, Type, TypeWithDeref}, + source_location::SourceLocation, + ty::{ + DynCanonicalType, DynCanonicalValue, DynType, DynValue, DynValueTrait, Type, TypeWithDeref, + Value, + }, + util::ConstBool, + valueless::Valueless, wire::Wire, }; use bitvec::slice::BitSlice; -use std::{convert::Infallible, fmt, ops::Deref}; +use std::{any::Any, convert::Infallible, fmt, hash::Hash, marker::PhantomData, ops::Deref}; pub mod ops; -pub mod target; macro_rules! expr_enum { ( pub enum $ExprEnum:ident { - $($Variant:ident($VariantTy:ty),)* + $($Variant:ident($VariantTy:ty),)+ } ) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash)] + #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub enum $ExprEnum { - $($Variant($VariantTy),)* + $($Variant(Interned<$VariantTy>),)+ } impl fmt::Debug for $ExprEnum { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - $(Self::$Variant(v) => v.fmt(f),)* + $(Self::$Variant(v) => v.fmt(f),)+ } } } - $(impl From<$VariantTy> for $ExprEnum { - fn from(v: $VariantTy) -> Self { - Self::$Variant(v) - } - })* - - impl Fold for $ExprEnum { - fn fold(self, state: &mut State) -> Result { - state.fold_expr_enum(self) - } - - fn default_fold(self, state: &mut State) -> Result { + impl $ExprEnum { + pub fn target(self) -> Option> { match self { - $(Self::$Variant(v) => Fold::fold(v, state).map(Self::$Variant),)* + $(Self::$Variant(v) => v.target(),)+ } } - } - - impl Visit for $ExprEnum { - fn visit(&self, state: &mut State) -> Result<(), State::Error> { - state.visit_expr_enum(self) - } - - fn default_visit(&self, state: &mut State) -> Result<(), State::Error> { + #[allow(clippy::result_unit_err)] + pub fn to_literal_bits(&self) -> Result, ()> { match self { - $(Self::$Variant(v) => Visit::visit(v, state),)* + $(Self::$Variant(v) => v.to_literal_bits(),)+ } } } impl ToExpr for $ExprEnum { - type Type = CanonicalType; + type Type = Interned; - fn to_expr(&self) -> Expr { + fn ty(&self) -> Self::Type { match self { - $(Self::$Variant(v) => Expr::canonical(v.to_expr()),)* + $(Self::$Variant(v) => v.ty().canonical_dyn(),)+ + } + } + + fn to_expr(&self) -> Expr { + Expr::new_unchecked(*self) + } + } + + impl Fold for $ExprEnum { + fn fold(self, state: &mut State) -> Result { + state.fold_expr_enum(self) + } + fn default_fold(self, state: &mut State) -> Result { + match self { + $(Self::$Variant(v) => Fold::fold(v, state).map(Self::$Variant),)+ } } } - impl GetTarget for $ExprEnum { - fn target(&self) -> Option> { - match self { - $(Self::$Variant(v) => v.target(),)* - } + impl Visit for $ExprEnum { + fn visit(&self, state: &mut State) -> Result<(), State::Error> { + state.visit_expr_enum(self) } - } - - impl ToLiteralBits for $ExprEnum { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { + fn default_visit(&self, state: &mut State) -> Result<(), State::Error> { match self { - $(Self::$Variant(v) => v.to_literal_bits(),)* + $(Self::$Variant(v) => Visit::visit(v, state),)+ } } } @@ -105,279 +99,237 @@ macro_rules! expr_enum { expr_enum! { pub enum ExprEnum { - UIntLiteral(Interned), - SIntLiteral(Interned), - BoolLiteral(bool), - BundleLiteral(ops::BundleLiteral), - ArrayLiteral(ops::ArrayLiteral), - EnumLiteral(ops::EnumLiteral), - NotU(ops::NotU), - NotS(ops::NotS), - NotB(ops::NotB), - Neg(ops::Neg), - BitAndU(ops::BitAndU), - BitAndS(ops::BitAndS), - BitAndB(ops::BitAndB), - BitOrU(ops::BitOrU), - BitOrS(ops::BitOrS), - BitOrB(ops::BitOrB), - BitXorU(ops::BitXorU), - BitXorS(ops::BitXorS), - BitXorB(ops::BitXorB), - AddU(ops::AddU), - AddS(ops::AddS), - SubU(ops::SubU), - SubS(ops::SubS), - MulU(ops::MulU), - MulS(ops::MulS), - DivU(ops::DivU), - DivS(ops::DivS), - RemU(ops::RemU), - RemS(ops::RemS), - DynShlU(ops::DynShlU), - DynShlS(ops::DynShlS), - DynShrU(ops::DynShrU), - DynShrS(ops::DynShrS), - FixedShlU(ops::FixedShlU), - FixedShlS(ops::FixedShlS), - FixedShrU(ops::FixedShrU), - FixedShrS(ops::FixedShrS), - CmpLtB(ops::CmpLtB), - CmpLeB(ops::CmpLeB), - CmpGtB(ops::CmpGtB), - CmpGeB(ops::CmpGeB), - CmpEqB(ops::CmpEqB), - CmpNeB(ops::CmpNeB), - CmpLtU(ops::CmpLtU), - CmpLeU(ops::CmpLeU), - CmpGtU(ops::CmpGtU), - CmpGeU(ops::CmpGeU), - CmpEqU(ops::CmpEqU), - CmpNeU(ops::CmpNeU), - CmpLtS(ops::CmpLtS), - CmpLeS(ops::CmpLeS), - CmpGtS(ops::CmpGtS), - CmpGeS(ops::CmpGeS), - CmpEqS(ops::CmpEqS), - CmpNeS(ops::CmpNeS), - CastUIntToUInt(ops::CastUIntToUInt), - CastUIntToSInt(ops::CastUIntToSInt), - CastSIntToUInt(ops::CastSIntToUInt), - CastSIntToSInt(ops::CastSIntToSInt), - CastBoolToUInt(ops::CastBoolToUInt), - CastBoolToSInt(ops::CastBoolToSInt), - CastUIntToBool(ops::CastUIntToBool), - CastSIntToBool(ops::CastSIntToBool), - CastBoolToSyncReset(ops::CastBoolToSyncReset), - CastUIntToSyncReset(ops::CastUIntToSyncReset), - CastSIntToSyncReset(ops::CastSIntToSyncReset), - CastBoolToAsyncReset(ops::CastBoolToAsyncReset), - CastUIntToAsyncReset(ops::CastUIntToAsyncReset), - CastSIntToAsyncReset(ops::CastSIntToAsyncReset), - CastSyncResetToBool(ops::CastSyncResetToBool), - CastSyncResetToUInt(ops::CastSyncResetToUInt), - CastSyncResetToSInt(ops::CastSyncResetToSInt), - CastSyncResetToReset(ops::CastSyncResetToReset), - CastAsyncResetToBool(ops::CastAsyncResetToBool), - CastAsyncResetToUInt(ops::CastAsyncResetToUInt), - CastAsyncResetToSInt(ops::CastAsyncResetToSInt), - CastAsyncResetToReset(ops::CastAsyncResetToReset), - CastResetToBool(ops::CastResetToBool), - CastResetToUInt(ops::CastResetToUInt), - CastResetToSInt(ops::CastResetToSInt), - CastBoolToClock(ops::CastBoolToClock), - CastUIntToClock(ops::CastUIntToClock), - CastSIntToClock(ops::CastSIntToClock), - CastClockToBool(ops::CastClockToBool), - CastClockToUInt(ops::CastClockToUInt), - CastClockToSInt(ops::CastClockToSInt), - FieldAccess(ops::FieldAccess), - VariantAccess(ops::VariantAccess), - ArrayIndex(ops::ArrayIndex), - DynArrayIndex(ops::DynArrayIndex), - ReduceBitAndU(ops::ReduceBitAndU), - ReduceBitAndS(ops::ReduceBitAndS), - ReduceBitOrU(ops::ReduceBitOrU), - ReduceBitOrS(ops::ReduceBitOrS), - ReduceBitXorU(ops::ReduceBitXorU), - ReduceBitXorS(ops::ReduceBitXorS), - SliceUInt(ops::SliceUInt), - SliceSInt(ops::SliceSInt), + Literal(Literal>), + ArrayLiteral(ops::ArrayLiteral>), + BundleLiteral(ops::BundleLiteral), + EnumLiteral(ops::EnumLiteral), + NotU(ops::Not), + NotS(ops::Not), + Neg(ops::Neg), + BitAndU(ops::BitAnd), + BitAndS(ops::BitAnd), + BitOrU(ops::BitOr), + BitOrS(ops::BitOr), + BitXorU(ops::BitXor), + BitXorS(ops::BitXor), + AddU(ops::Add), + AddS(ops::Add), + SubU(ops::Sub), + SubS(ops::Sub), + MulU(ops::Mul), + MulS(ops::Mul), + DynShlU(ops::DynShl), + DynShlS(ops::DynShl), + DynShrU(ops::DynShr), + DynShrS(ops::DynShr), + FixedShlU(ops::FixedShl), + FixedShlS(ops::FixedShl), + FixedShrU(ops::FixedShr), + FixedShrS(ops::FixedShr), + CmpLtU(ops::CmpLt), + CmpLtS(ops::CmpLt), + CmpLeU(ops::CmpLe), + CmpLeS(ops::CmpLe), + CmpGtU(ops::CmpGt), + CmpGtS(ops::CmpGt), + CmpGeU(ops::CmpGe), + CmpGeS(ops::CmpGe), + CmpEqU(ops::CmpEq), + CmpEqS(ops::CmpEq), + CmpNeU(ops::CmpNe), + CmpNeS(ops::CmpNe), + CastUIntToUInt(ops::CastInt), + CastUIntToSInt(ops::CastInt), + CastSIntToUInt(ops::CastInt), + CastSIntToSInt(ops::CastInt), + SliceUInt(ops::Slice), + SliceSInt(ops::Slice), + ReduceBitAnd(ops::ReduceBitAnd>), + ReduceBitOr(ops::ReduceBitOr>), + ReduceBitXor(ops::ReduceBitXor>), + FieldAccess(ops::FieldAccess>), + VariantAccess(ops::VariantAccess>), + ArrayIndex(ops::ArrayIndex>), + DynArrayIndex(ops::DynArrayIndex>), CastToBits(ops::CastToBits), - CastBitsTo(ops::CastBitsTo), - ModuleIO(ModuleIO), - Instance(Instance), - Wire(Wire), - Reg(Reg), + CastBitsTo(ops::CastBitsTo>), + CastBitToClock(ops::CastBitToClock), + CastBitToSyncReset(ops::CastBitToSyncReset), + CastBitToAsyncReset(ops::CastBitToAsyncReset), + CastSyncResetToReset(ops::CastSyncResetToReset), + CastAsyncResetToReset(ops::CastAsyncResetToReset), + CastClockToBit(ops::CastClockToBit), + CastSyncResetToBit(ops::CastSyncResetToBit), + CastAsyncResetToBit(ops::CastAsyncResetToBit), + CastResetToBit(ops::CastResetToBit), + ModuleIO(ModuleIO>), + Instance(Instance), + Wire(Wire>), + Reg(Reg>), MemPort(MemPort), } } -impl From for ExprEnum { - fn from(value: UIntValue) -> Self { - ExprEnum::UIntLiteral(Intern::intern_sized(value)) +pub struct Expr { + /// use weird names to help work around rust-analyzer bug + __enum: ExprEnum, + __phantom: PhantomData, +} + +impl Expr { + pub fn expr_enum(self) -> ExprEnum { + self.__enum + } + pub fn new_unchecked(expr_enum: ExprEnum) -> Self { + Self { + __enum: expr_enum, + __phantom: PhantomData, + } + } + pub fn canonical(self) -> Expr<::CanonicalValue> + where + T: Value, + { + Expr { + __enum: self.expr_enum(), + __phantom: PhantomData, + } + } + pub fn dyn_canonical_type(self) -> Interned { + self.expr_enum().ty() + } + pub fn canonical_type(self) -> ::CanonicalType + where + T: Value, + { + ::CanonicalType::from_dyn_canonical_type(self.dyn_canonical_type()) + } + pub fn valueless(self) -> Valueless + where + T: Value>, + { + Valueless { ty: self.ty() } + } + #[allow(clippy::result_unit_err)] + pub fn to_literal_bits(&self) -> Result, ()> { + self.expr_enum().to_literal_bits() + } + #[track_caller] + pub fn with_type>>(self) -> Expr + where + T: Value>, + { + let retval = Expr::::new_unchecked(self.expr_enum()); + let _ = retval.ty(); // check that the type is correct + retval + } + pub fn to_dyn(self) -> Expr { + Expr::new_unchecked(self.expr_enum()) + } + pub fn to_canonical_dyn(self) -> Expr { + Expr::new_unchecked(self.expr_enum()) + } + #[track_caller] + pub fn from_value(value: &T) -> Self + where + T: Value>, + { + Literal::::new_unchecked(value.to_canonical()).to_expr() + } + pub fn target(self) -> Option> { + self.expr_enum().target() + } + pub fn flow(self) -> Flow { + self.target().map(|v| v.flow()).unwrap_or(Flow::Source) } } -impl From for ExprEnum { - fn from(value: SIntValue) -> Self { - ExprEnum::SIntLiteral(Intern::intern_sized(value)) - } -} +impl Copy for Expr {} -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -#[non_exhaustive] -pub struct NotALiteralExpr; - -impl fmt::Display for NotALiteralExpr { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Not a literal expression") - } -} - -impl std::error::Error for NotALiteralExpr {} - -pub trait ToLiteralBits { - fn to_literal_bits(&self) -> Result, NotALiteralExpr>; -} - -impl ToLiteralBits for Result, NotALiteralExpr> { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { +impl Clone for Expr { + fn clone(&self) -> Self { *self } } -impl ToLiteralBits for Interned { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - Ok(*self) - } -} - -impl ToLiteralBits for NotALiteralExpr { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - Err(*self) - } -} - -#[derive(Copy, Clone, PartialEq, Eq, Hash)] -pub struct Expr { - __enum: Interned, - __ty: T, - __flow: Flow, -} - -impl fmt::Debug for Expr { +impl fmt::Debug for Expr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.__enum.fmt(f) + let Self { + __enum, + __phantom: _, + } = self; + __enum.fmt(f) } } -impl Expr { - pub fn expr_enum(this: Self) -> Interned { - this.__enum - } - pub fn ty(this: Self) -> T { - this.__ty - } - pub fn flow(this: Self) -> Flow { - this.__flow - } - pub fn canonical(this: Self) -> Expr { - Expr { - __enum: this.__enum, - __ty: this.__ty.canonical(), - __flow: this.__flow, - } - } - pub fn from_canonical(this: Expr) -> Self { - Expr { - __enum: this.__enum, - __ty: T::from_canonical(this.__ty), - __flow: this.__flow, - } - } - pub fn from_dyn_int(this: Expr) -> Self - where - T: IntType, - { - Expr { - __enum: this.__enum, - __ty: T::from_dyn_int(this.__ty), - __flow: this.__flow, - } - } - pub fn as_dyn_int(this: Self) -> Expr - where - T: IntType, - { - Expr { - __enum: this.__enum, - __ty: this.__ty.as_dyn_int(), - __flow: this.__flow, - } - } - pub fn as_bundle(this: Self) -> Expr - where - T: BundleType, - { - Expr { - __enum: this.__enum, - __ty: Bundle::new(this.__ty.fields()), - __flow: this.__flow, - } - } - pub fn from_bundle(this: Expr) -> Self - where - T: BundleType, - { - Expr { - __enum: this.__enum, - __ty: T::from_canonical(CanonicalType::Bundle(this.__ty)), - __flow: this.__flow, - } - } - #[track_caller] - pub fn field(this: Self, name: &str) -> Expr - where - T: BundleType, - { - ops::FieldAccess::new_by_name(Self::as_bundle(this), name.intern()).to_expr() - } - pub fn as_enum(this: Self) -> Expr - where - T: EnumType, - { - Expr { - __enum: this.__enum, - __ty: Enum::new(this.__ty.variants()), - __flow: this.__flow, - } - } - pub fn from_enum(this: Expr) -> Self - where - T: EnumType, - { - Expr { - __enum: this.__enum, - __ty: T::from_canonical(CanonicalType::Enum(this.__ty)), - __flow: this.__flow, - } +impl>> sealed::Sealed for Expr {} + +impl PartialEq for Expr { + fn eq(&self, other: &Self) -> bool { + let Self { + __enum, + __phantom: _, + } = self; + *__enum == other.__enum } } -impl ToLiteralBits for Expr { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.__enum.to_literal_bits() +impl Eq for Expr {} + +impl Hash for Expr { + fn hash(&self, state: &mut H) { + let Self { + __enum, + __phantom: _, + } = self; + __enum.hash(state); } } -impl GetTarget for Expr { - fn target(&self) -> Option> { - self.__enum.target() +impl Expr> +where + T: StaticOrDynIntType< + 1, + Signed = ConstBool, + CanonicalType = DynUIntType, + CanonicalValue = DynUInt, + >, +{ + pub fn as_bool(self) -> Expr> { + assert_eq!(self.canonical_type().width, 1); + Expr::new_unchecked(self.expr_enum()) } } -impl Deref for Expr { +impl>> Expr { + pub fn field>>( + self, + name: &str, + ) -> Expr { + ops::FieldAccess::::new_unchecked( + self.canonical(), + name.intern(), + ) + .to_expr() + } +} + +impl>> ToExpr for Expr { + type Type = T::Type; + + fn ty(&self) -> T::Type { + T::Type::from_dyn_canonical_type(self.dyn_canonical_type()) + } + + fn to_expr(&self) -> Expr { + *self + } +} + +impl, T> Deref for Expr +where + T: TypeWithDeref, +{ type Target = T::MatchVariant; fn deref(&self) -> &Self::Target { @@ -385,115 +337,27 @@ impl Deref for Expr { } } -impl Expr> { - pub fn as_dyn_array(this: Self) -> Expr { - Expr { - __enum: this.__enum, - __ty: this.__ty.as_dyn_array(), - __flow: this.__flow, - } - } -} - -impl Fold for Expr { +impl>, State: ?Sized + Folder> Fold for Expr { fn fold(self, state: &mut State) -> Result { state.fold_expr(self) } - fn default_fold(self, state: &mut State) -> Result { - Ok(Expr::from_canonical(self.__enum.fold(state)?.to_expr())) + Ok(Expr::::new_unchecked(self.expr_enum().fold(state)?).with_type()) } } -impl Visit for Expr { +impl>, State: ?Sized + Visitor> Visit for Expr { fn visit(&self, state: &mut State) -> Result<(), State::Error> { state.visit_expr(self) } - fn default_visit(&self, state: &mut State) -> Result<(), State::Error> { - self.__enum.visit(state) + self.expr_enum().visit(state) } } -pub trait ToExpr { - type Type: Type; - fn to_expr(&self) -> Expr; -} - -impl ToExpr for Expr { - type Type = T; - - fn to_expr(&self) -> Expr { - *self - } -} - -impl ToExpr for &'_ T { - type Type = T::Type; - - fn to_expr(&self) -> Expr { - T::to_expr(self) - } -} - -impl ToExpr for &'_ mut T { - type Type = T::Type; - - fn to_expr(&self) -> Expr { - T::to_expr(self) - } -} - -impl ToExpr for Box { - type Type = T::Type; - - fn to_expr(&self) -> Expr { - T::to_expr(self) - } -} - -impl ToExpr for Interned { - type Type = T::Type; - - fn to_expr(&self) -> Expr { - T::to_expr(self) - } -} - -impl ToExpr for UIntValue { - type Type = UIntType; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::UIntLiteral(self.clone().as_dyn_int().intern()).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } -} - -impl ToExpr for SIntValue { - type Type = SIntType; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::SIntLiteral(self.clone().as_dyn_int().intern()).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } -} - -impl ToExpr for bool { - type Type = Bool; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::BoolLiteral(*self).intern(), - __ty: Bool, - __flow: Flow::Source, - } - } +pub trait ExprTraitBase: + fmt::Debug + Any + SupportsPtrEqWithTypeId + Send + Sync + sealed::Sealed + ToExpr +{ } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] @@ -520,180 +384,712 @@ impl Flow { } } +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct TargetPathBundleField { + pub name: Interned, +} + +impl fmt::Display for TargetPathBundleField { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, ".{}", self.name) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct TargetPathArrayElement { + pub index: usize, +} + +impl fmt::Display for TargetPathArrayElement { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[{}]", self.index) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct TargetPathDynArrayElement {} + +impl fmt::Display for TargetPathDynArrayElement { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[]") + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum TargetPathElement { + BundleField(TargetPathBundleField), + ArrayElement(TargetPathArrayElement), + DynArrayElement(TargetPathDynArrayElement), +} + +impl From for TargetPathElement { + fn from(value: TargetPathBundleField) -> Self { + Self::BundleField(value) + } +} + +impl From for TargetPathElement { + fn from(value: TargetPathArrayElement) -> Self { + Self::ArrayElement(value) + } +} + +impl From for TargetPathElement { + fn from(value: TargetPathDynArrayElement) -> Self { + Self::DynArrayElement(value) + } +} + +impl fmt::Display for TargetPathElement { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::BundleField(v) => v.fmt(f), + Self::ArrayElement(v) => v.fmt(f), + Self::DynArrayElement(v) => v.fmt(f), + } + } +} + +impl TargetPathElement { + pub fn canonical_ty(&self, parent: Interned) -> Interned { + match self { + &Self::BundleField(TargetPathBundleField { name }) => { + let parent_ty = parent + .canonical_ty() + .type_enum() + .bundle_type() + .expect("parent type is known to be a bundle"); + let field = parent_ty + .field_by_name(name) + .expect("field name is known to be a valid field of parent type"); + field.ty + } + &Self::ArrayElement(TargetPathArrayElement { index }) => { + let parent_ty = parent + .canonical_ty() + .type_enum() + .array_type() + .expect("parent type is known to be an array"); + assert!(index < parent_ty.len()); + *parent_ty.element() + } + Self::DynArrayElement(_) => { + let parent_ty = parent + .canonical_ty() + .type_enum() + .array_type() + .expect("parent type is known to be an array"); + *parent_ty.element() + } + } + } + pub fn flow(&self, parent: Interned) -> Flow { + match self { + Self::BundleField(v) => { + let parent_ty = parent + .canonical_ty() + .type_enum() + .bundle_type() + .expect("parent type is known to be a bundle"); + let field = parent_ty + .field_by_name(v.name) + .expect("field name is known to be a valid field of parent type"); + parent.flow().flip_if(field.flipped) + } + Self::ArrayElement(_) => parent.flow(), + Self::DynArrayElement(_) => parent.flow(), + } + } + pub fn is_static(&self) -> bool { + match self { + Self::BundleField(_) | Self::ArrayElement(_) => true, + Self::DynArrayElement(_) => false, + } + } +} + +macro_rules! impl_target_base { + ( + $(#[$enum_meta:meta])* + $enum_vis:vis enum $TargetBase:ident { + $( + #[is = $is_fn:ident] + #[to = $to_fn:ident] + $(#[$variant_meta:meta])* + $Variant:ident($VariantTy:ty), + )* + } + ) => { + $(#[$enum_meta])* + $enum_vis enum $TargetBase { + $( + $(#[$variant_meta])* + $Variant($VariantTy), + )* + } + + impl fmt::Debug for $TargetBase { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + $(Self::$Variant(v) => v.fmt(f),)* + } + } + } + + $( + impl From<$VariantTy> for $TargetBase { + fn from(value: $VariantTy) -> Self { + Self::$Variant(value) + } + } + + impl From<$VariantTy> for Target { + fn from(value: $VariantTy) -> Self { + $TargetBase::$Variant(value).into() + } + } + )* + + impl $TargetBase { + $( + $enum_vis fn $is_fn(&self) -> bool { + self.$to_fn().is_some() + } + $enum_vis fn $to_fn(&self) -> Option<&$VariantTy> { + if let Self::$Variant(retval) = self { + Some(retval) + } else { + None + } + } + )* + $enum_vis fn must_connect_to(&self) -> bool { + match self { + $(Self::$Variant(v) => v.must_connect_to(),)* + } + } + $enum_vis fn flow(&self) -> Flow { + match self { + $(Self::$Variant(v) => v.flow(),)* + } + } + $enum_vis fn source_location(&self) -> SourceLocation { + match self { + $(Self::$Variant(v) => v.source_location(),)* + } + } + } + }; +} + +impl_target_base! { + #[derive(Clone, PartialEq, Eq, Hash)] + pub enum TargetBase { + #[is = is_module_io] + #[to = module_io] + ModuleIO(ModuleIO>), + #[is = is_mem_port] + #[to = mem_port] + MemPort(MemPort), + #[is = is_reg] + #[to = reg] + Reg(Reg>), + #[is = is_wire] + #[to = wire] + Wire(Wire>), + #[is = is_instance] + #[to = instance] + Instance(Instance), + } +} + +impl fmt::Display for TargetBase { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self.target_name()) + } +} + +impl TargetBase { + pub fn target_name(&self) -> TargetName { + match self { + TargetBase::ModuleIO(v) => TargetName(v.scoped_name(), None), + TargetBase::MemPort(v) => TargetName(v.mem_name(), Some(v.port_name())), + TargetBase::Reg(v) => TargetName(v.scoped_name(), None), + TargetBase::Wire(v) => TargetName(v.scoped_name(), None), + TargetBase::Instance(v) => TargetName(v.scoped_name(), None), + } + } + pub fn canonical_ty(&self) -> Interned { + match self { + TargetBase::ModuleIO(v) => v.ty(), + TargetBase::MemPort(v) => v.ty().canonical_dyn(), + TargetBase::Reg(v) => v.ty(), + TargetBase::Wire(v) => v.ty(), + TargetBase::Instance(v) => v.ty().canonical_dyn(), + } + } +} + +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +pub struct TargetChild { + parent: Interned, + path_element: Interned, + canonical_ty: Interned, + flow: Flow, +} + +impl fmt::Debug for TargetChild { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + parent, + path_element, + canonical_ty: _, + flow: _, + } = self; + parent.fmt(f)?; + fmt::Display::fmt(path_element, f) + } +} + +impl fmt::Display for TargetChild { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + parent, + path_element, + canonical_ty: _, + flow: _, + } = self; + parent.fmt(f)?; + path_element.fmt(f) + } +} + +impl TargetChild { + pub fn new(parent: Interned, path_element: Interned) -> Self { + Self { + parent, + path_element, + canonical_ty: path_element.canonical_ty(parent), + flow: path_element.flow(parent), + } + } + pub fn parent(self) -> Interned { + self.parent + } + pub fn path_element(self) -> Interned { + self.path_element + } + pub fn canonical_ty(self) -> Interned { + self.canonical_ty + } + pub fn flow(self) -> Flow { + self.flow + } + pub fn bundle_field(self) -> Option>> { + if let TargetPathElement::BundleField(TargetPathBundleField { name }) = *self.path_element { + let parent_ty = self + .parent + .canonical_ty() + .type_enum() + .bundle_type() + .expect("parent known to be bundle"); + Some( + parent_ty + .field_by_name(name) + .expect("field name known to be a valid field of parent"), + ) + } else { + None + } + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub enum Target { + Base(Interned), + Child(TargetChild), +} + +impl From for Target { + fn from(value: TargetBase) -> Self { + Self::Base(Intern::intern_sized(value)) + } +} + +impl From for Target { + fn from(value: TargetChild) -> Self { + Self::Child(value) + } +} + +impl From> for Target { + fn from(value: Interned) -> Self { + Self::Base(value) + } +} + +impl Target { + pub fn base(&self) -> Interned { + let mut target = self; + loop { + match target { + Self::Base(v) => break *v, + Self::Child(v) => target = &v.parent, + } + } + } + pub fn child(&self) -> Option { + match *self { + Target::Base(_) => None, + Target::Child(v) => Some(v), + } + } + pub fn is_static(&self) -> bool { + let mut target = self; + loop { + match target { + Self::Base(_) => return true, + Self::Child(v) if !v.path_element().is_static() => return false, + Self::Child(v) => target = &v.parent, + } + } + } + #[must_use] + pub fn join(&self, path_element: Interned) -> Self { + TargetChild::new(self.intern(), path_element).into() + } + pub fn flow(&self) -> Flow { + match self { + Self::Base(v) => v.flow(), + Self::Child(v) => v.flow(), + } + } + pub fn canonical_ty(&self) -> Interned { + match self { + Target::Base(v) => v.canonical_ty(), + Target::Child(v) => v.canonical_ty(), + } + } +} + +impl fmt::Display for Target { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Base(v) => v.fmt(f), + Self::Child(v) => v.fmt(f), + } + } +} + +impl fmt::Debug for Target { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Base(v) => v.fmt(f), + Self::Child(v) => v.fmt(f), + } + } +} + +pub trait ExprTrait: ExprTraitBase { + fn expr_enum(&self) -> ExprEnum; + fn target(&self) -> Option>; + fn valueless(&self) -> Valueless { + Valueless { ty: self.ty() } + } + #[allow(clippy::result_unit_err)] + fn to_literal_bits(&self) -> Result, ()>; +} + +impl ExprTraitBase for T {} + +impl InternedCompare for dyn ExprTrait { + type InternedCompareKey = PtrEqWithTypeId; + fn interned_compare_key_ref(this: &Self) -> Self::InternedCompareKey { + Self::get_ptr_eq_with_type_id(this) + } + fn interned_compare_key_weak(this: &std::sync::Weak) -> Self::InternedCompareKey { + Self::get_ptr_eq_with_type_id(&*this.upgrade().unwrap()) + } +} + +pub struct SimState {} + +mod sealed { + pub trait Sealed {} +} + +pub trait ToExpr { + type Type: Type; + fn ty(&self) -> Self::Type; + fn to_expr(&self) -> Expr<::Value>; +} + +impl ToExpr for &'_ T { + type Type = T::Type; + + fn ty(&self) -> Self::Type { + (**self).ty() + } + + fn to_expr(&self) -> Expr<::Value> { + (**self).to_expr() + } +} + +impl ToExpr for &'_ mut T { + type Type = T::Type; + + fn ty(&self) -> Self::Type { + (**self).ty() + } + + fn to_expr(&self) -> Expr<::Value> { + (**self).to_expr() + } +} + +impl ToExpr for Box { + type Type = T::Type; + + fn ty(&self) -> Self::Type { + (**self).ty() + } + + fn to_expr(&self) -> Expr<::Value> { + (**self).to_expr() + } +} + +#[derive(Clone, Eq, PartialEq, Hash)] +pub struct Literal { + value: T::CanonicalValue, +} + +impl fmt::Debug for Literal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.value.fmt(f) + } +} + +impl Literal { + #[track_caller] + pub fn new_unchecked(value: T::CanonicalValue) -> Self { + assert!( + value.ty().is_passive(), + "can't have a literal with flipped fields" + ); + Self { value } + } + pub fn value(&self) -> &T::CanonicalValue { + &self.value + } + pub fn canonical(&self) -> Literal { + Literal { + value: self.value.clone(), + } + } +} + +impl sealed::Sealed for Literal {} + +impl ToExpr for Literal { + type Type = T; + + fn ty(&self) -> Self::Type { + Self::Type::from_canonical_type(self.value.ty()) + } + + fn to_expr(&self) -> Expr<::Value> { + Expr::new_unchecked(self.expr_enum()) + } +} + +impl ExprTrait for Literal { + fn expr_enum(&self) -> ExprEnum { + ExprEnum::Literal( + Literal { + value: self.value.to_canonical_dyn(), + } + .intern_sized(), + ) + } + + fn target(&self) -> Option> { + None + } + + fn to_literal_bits(&self) -> Result, ()> { + Ok(self.value.to_bits()) + } +} + +impl Fold for Literal +where + T::CanonicalValue: Fold, +{ + fn fold(self, state: &mut State) -> Result { + state.fold_literal(self) + } + fn default_fold(self, state: &mut State) -> Result { + Ok(Literal { + value: self.value.fold(state)?, + }) + } +} + +impl Visit for Literal +where + T::CanonicalValue: Visit, +{ + fn visit(&self, state: &mut State) -> Result<(), ::Error> { + state.visit_literal(self) + } + fn default_visit(&self, state: &mut State) -> Result<(), ::Error> { + self.value.visit(state) + } +} + +impl sealed::Sealed for ModuleIO {} + impl ToExpr for ModuleIO { type Type = T; - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::ModuleIO(self.canonical()).intern_sized(), - __ty: self.ty(), - __flow: self.flow(), - } + fn ty(&self) -> Self::Type { + self.field_type().ty.clone() + } + + fn to_expr(&self) -> Expr<::Value> { + Expr::new_unchecked(self.expr_enum()) } } -impl ToLiteralBits for ModuleIO { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - Err(NotALiteralExpr) +impl ExprTrait for ModuleIO { + fn expr_enum(&self) -> ExprEnum { + ExprEnum::ModuleIO(self.to_canonical_dyn_module_io().intern_sized()) + } + + fn target(&self) -> Option> { + Some(Intern::intern_sized( + self.to_canonical_dyn_module_io().into(), + )) + } + + fn to_literal_bits(&self) -> Result, ()> { + Err(()) } } -impl GetTarget for ModuleIO { +impl sealed::Sealed for Instance where T::Type: BundleType {} + +impl ToExpr for Instance +where + T::Type: BundleType, +{ + type Type = T::Type; + + fn ty(&self) -> Self::Type { + (*self.instantiated().io_ty()).clone() + } + + fn to_expr(&self) -> Expr<::Value> { + Expr::new_unchecked(self.expr_enum()) + } +} + +impl ExprTrait for Instance +where + T::Type: BundleType, +{ + fn expr_enum(&self) -> ExprEnum { + ExprEnum::Instance(self.canonical().intern_sized()) + } + fn target(&self) -> Option> { Some(Intern::intern_sized(self.canonical().into())) } -} -impl ToExpr for Instance { - type Type = T; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::Instance(self.canonical()).intern_sized(), - __ty: self.ty(), - __flow: self.flow(), - } + fn to_literal_bits(&self) -> Result, ()> { + Err(()) } } -impl ToLiteralBits for Instance { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - Err(NotALiteralExpr) - } -} +impl sealed::Sealed for Wire {} + +impl ExprTrait for Wire { + fn expr_enum(&self) -> ExprEnum { + ExprEnum::Wire(self.to_dyn_canonical_wire().intern_sized()) + } -impl GetTarget for Instance { fn target(&self) -> Option> { - Some(Intern::intern_sized(self.canonical().into())) + Some(Intern::intern_sized(self.to_dyn_canonical_wire().into())) + } + + fn to_literal_bits(&self) -> Result, ()> { + Err(()) } } -impl ToExpr for Wire { - type Type = T; +impl sealed::Sealed for Reg {} - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::Wire(self.canonical()).intern_sized(), - __ty: self.ty(), - __flow: self.flow(), - } +impl ExprTrait for Reg { + fn expr_enum(&self) -> ExprEnum { + ExprEnum::Reg(self.to_dyn_canonical_reg().intern_sized()) } -} -impl ToLiteralBits for Wire { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - Err(NotALiteralExpr) - } -} - -impl GetTarget for Wire { fn target(&self) -> Option> { - Some(Intern::intern_sized(self.canonical().into())) + Some(Intern::intern_sized(self.to_dyn_canonical_reg().into())) + } + + fn to_literal_bits(&self) -> Result, ()> { + Err(()) } } -impl ToExpr for Reg { - type Type = T; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::Reg(self.canonical()).intern_sized(), - __ty: self.ty(), - __flow: self.flow(), - } - } -} - -impl ToLiteralBits for Reg { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - Err(NotALiteralExpr) - } -} - -impl GetTarget for Reg { - fn target(&self) -> Option> { - Some(Intern::intern_sized(self.canonical().into())) - } -} - -impl ToExpr for MemPort { - type Type = T::Port; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::MemPort(self.canonical()).intern_sized(), - __ty: self.ty(), - __flow: self.flow(), - } - } -} - -impl ToLiteralBits for MemPort { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - Err(NotALiteralExpr) - } -} - -impl GetTarget for MemPort { - fn target(&self) -> Option> { - Some(Intern::intern_sized(self.canonical().into())) - } -} - -pub trait ReduceBits { - type UIntOutput; - type BoolOutput; - fn reduce_bitand(self) -> Self::UIntOutput; - fn reduce_bitor(self) -> Self::UIntOutput; - fn reduce_bitxor(self) -> Self::UIntOutput; - fn any_one_bits(self) -> Self::BoolOutput; - fn any_zero_bits(self) -> Self::BoolOutput; - fn all_one_bits(self) -> Self::BoolOutput; - fn all_zero_bits(self) -> Self::BoolOutput; - fn parity_odd(self) -> Self::BoolOutput; - fn parity_even(self) -> Self::BoolOutput; -} - -pub trait CastToBits { - fn cast_to_bits(&self) -> Expr; -} - -impl CastToBits for T { - fn cast_to_bits(&self) -> Expr { - ops::CastToBits::new(Expr::canonical(self.to_expr())).to_expr() - } -} - -pub trait CastBitsTo { - fn cast_bits_to(&self, ty: T) -> Expr; -} - -impl> + ?Sized, Width: Size> CastBitsTo for T { - fn cast_bits_to(&self, ty: ToType) -> Expr { - ops::CastBitsTo::new(Expr::as_dyn_int(self.to_expr()), ty).to_expr() - } -} - -pub trait CastTo: ToExpr { - fn cast_to(&self, to_type: ToType) -> Expr - where - Self::Type: ExprCastTo, - { - ExprCastTo::cast_to(self.to_expr(), to_type) - } - fn cast_to_static(&self) -> Expr - where - Self::Type: ExprCastTo, - { - ExprCastTo::cast_to(self.to_expr(), ToType::TYPE) - } -} - -impl CastTo for T {} - #[doc(hidden)] -pub fn check_match_expr( - _expr: Expr, - _check_fn: impl FnOnce(T::MatchVariant, Infallible), -) { +pub fn value_from_expr_type(_expr: Expr, infallible: Infallible) -> V { + match infallible {} +} + +#[doc(hidden)] +pub fn check_match_expr(_expr: Expr, _check_fn: impl FnOnce(V, Infallible)) {} + +#[doc(hidden)] +#[inline] +pub fn make_enum_expr( + _check_fn: impl FnOnce(Infallible) -> V, + build: impl FnOnce(::Builder) -> Expr, +) -> Expr +where + V::Type: EnumType, +{ + build(V::Type::builder()) +} + +#[doc(hidden)] +#[inline] +pub fn make_bundle_expr( + _check_fn: impl FnOnce(Infallible) -> V, + build: impl FnOnce(::Builder) -> Expr, +) -> Expr +where + V::Type: BundleType, +{ + build(V::Type::builder()) +} + +impl sealed::Sealed for MemPort where Self: ToExpr {} + +impl ExprTrait for MemPort +where + Self: ToExpr, +{ + fn expr_enum(&self) -> ExprEnum { + ExprEnum::MemPort(self.canonical().intern_sized()) + } + fn target(&self) -> Option> { + Some(Intern::intern_sized(self.canonical().into())) + } + fn to_literal_bits(&self) -> Result, ()> { + Err(()) + } } diff --git a/crates/fayalite/src/expr/ops.rs b/crates/fayalite/src/expr/ops.rs index 4814d2d..c1a16f1 100644 --- a/crates/fayalite/src/expr/ops.rs +++ b/crates/fayalite/src/expr/ops.rs @@ -1,2156 +1,1058 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // See Notices.txt for copyright information - use crate::{ - array::{Array, ArrayType}, - bundle::{Bundle, BundleField, BundleType}, - clock::{Clock, ToClock}, - enum_::{Enum, EnumType, EnumVariant}, + array::{Array, ArrayType, ArrayTypeTrait, ValueArrayOrSlice}, + bundle::{BundleType, BundleValue, DynBundleType, FieldType}, + clock::{Clock, ClockType, ToClock}, + enum_::{DynEnumType, EnumType, EnumValue, VariantType}, expr::{ - target::{ - GetTarget, Target, TargetPathArrayElement, TargetPathBundleField, - TargetPathDynArrayElement, TargetPathElement, - }, - CastTo, Expr, ExprEnum, Flow, NotALiteralExpr, ReduceBits, ToExpr, ToLiteralBits, + sealed, Expr, ExprEnum, ExprTrait, Target, TargetPathArrayElement, TargetPathBundleField, + TargetPathDynArrayElement, TargetPathElement, ToExpr, }, int::{ - Bool, BoolOrIntType, DynSize, IntCmp, IntType, KnownSize, SInt, SIntType, SIntValue, Size, - UInt, UIntType, UIntValue, + DynInt, DynIntType, DynSInt, DynSIntType, DynUInt, DynUIntType, StaticOrDynIntType, Int, + IntCmp, IntType, IntTypeTrait, IntValue, UInt, UIntType, }, intern::{Intern, Interned}, - reset::{AsyncReset, Reset, SyncReset, ToAsyncReset, ToReset, ToSyncReset}, - ty::{CanonicalType, StaticType, Type}, - util::ConstUsize, + reset::{ + AsyncReset, AsyncResetType, Reset, ResetType, SyncReset, SyncResetType, ToAsyncReset, + ToReset, ToSyncReset, + }, + ty::{ + CanonicalType, CanonicalValue, DynCanonicalType, DynCanonicalValue, DynType, DynValueTrait, + Type, Value, + }, + util::{interned_bit, ConstBool, ConstBoolDispatch, ConstBoolDispatchTag, GenericConstBool}, + valueless::{Valueless, ValuelessTr}, }; -use bitvec::{order::Lsb0, slice::BitSlice, vec::BitVec, view::BitView}; -use num_bigint::BigInt; -use num_traits::{ToPrimitive, Zero}; +use bitvec::{slice::BitSlice, vec::BitVec}; +use num_traits::ToPrimitive; use std::{ fmt, - marker::PhantomData, - ops::{ - Add, BitAnd, BitOr, BitXor, Div, Index, Mul, Neg as StdNeg, Not, Range, RangeBounds, Rem, - Shl, Shr, Sub, - }, + hash::{Hash, Hasher}, + ops::{self, Index, Range, RangeBounds}, }; -macro_rules! forward_value_to_expr_unary_op_trait { +macro_rules! fixed_ary_op { ( - #[generics($($generics:tt)*)] - #[value($Value:ty)] - $Trait:ident::$method:ident - ) => { - impl<$($generics)*> $Trait for $Value + pub struct $name:ident<$($T:ident,)* $(#[const] $C:ident: $CTy:ty,)*> where - Expr<<$Value as ToExpr>::Type>: $Trait, + ($($where:tt)*) { - type Output = ::Type> as $Trait>::Output; - - fn $method(self) -> Self::Output { - $Trait::$method(self.to_expr()) + $($arg_vis:vis $arg:ident: $Arg:ty,)+ + $(#[cache] + $cache_before_ty:ident: $CacheBeforeTy:ty = $cache_before_ty_expr:expr,)* + #[type$(($ty_arg:ident))?] + $ty_vis:vis $ty_name:ident: $Ty:ty = $ty_expr:expr, + $(#[cache] + $cache_after_ty:ident: $CacheAfterTy:ty = $cache_after_ty_expr:expr,)* + $(#[target] + $target_name:ident: Option> = $target_expr:expr,)? + fn simulate(&$simulate_self:ident, $sim_state:ident: &mut SimState) -> _ { + $($simulate_body:tt)+ } - } - }; -} -macro_rules! impl_unary_op_trait { - ( - #[generics($($generics:tt)*)] - fn $Trait:ident::$method:ident($arg:ident: $Arg:ty) -> $Output:ty { - $($body:tt)* + fn expr_enum(&$expr_enum_self:ident) -> _ { + $($expr_enum_body:tt)+ + } + + fn to_literal_bits(&$to_literal_bits_self:ident) -> Result, ()> { + $($to_literal_bits_body:tt)+ + } } ) => { - impl<$($generics)*> $Trait for Expr<$Arg> + pub struct $name<$($T,)* $(const $C: $CTy,)*> + where + $($where)* { - type Output = Expr<$Output>; + $($arg_vis $arg: $Arg,)+ + $($cache_before_ty: $CacheBeforeTy,)* + $ty_vis $ty_name: $Ty, + $($cache_after_ty: $CacheAfterTy,)* + $($target_name: Option>,)? + } - fn $method(self) -> Self::Output { - let $arg = self; - $($body)* + impl<$($T,)* $(const $C: $CTy,)*> $name<$($T,)* $($C,)*> + where + $($where)* + { + pub fn new_unchecked($($arg: $Arg,)* $($ty_arg: $Ty,)?) -> Self { + $(let $cache_before_ty: $CacheBeforeTy = $cache_before_ty_expr;)* + let $ty_name: $Ty = $ty_expr; + $(let $cache_after_ty: $CacheAfterTy = $cache_after_ty_expr;)* + $(let $target_name: Option> = $target_expr;)? + Self { + $($arg,)* + $($cache_before_ty,)* + $ty_name, + $($cache_after_ty,)* + $($target_name,)? + } + } + pub fn canonical(&self) -> $name<$($T::CanonicalType,)* $($C,)*> { + $name { + $($arg: self.$arg.clone(),)* + $($cache_before_ty: self.$cache_before_ty.clone(),)* + $ty_name: self.$ty_name.canonical(), + $($cache_after_ty: self.$cache_after_ty.clone(),)* + $($target_name: self.$target_name,)? + } } } - }; -} -macro_rules! impl_get_target_none { - ([$($generics:tt)*] $ty:ty) => { - impl<$($generics)*> GetTarget for $ty { + impl<$($T,)* $(const $C: $CTy,)*> Clone for $name<$($T,)* $($C,)*> + where + $($where)* + { + fn clone(&self) -> Self { + Self { + $($arg: self.$arg.clone(),)* + $($cache_before_ty: self.$cache_before_ty.clone(),)* + $ty_name: self.$ty_name.clone(), + $($cache_after_ty: self.$cache_after_ty.clone(),)* + $($target_name: self.$target_name,)? + } + } + } + + impl<$($T,)* $(const $C: $CTy,)*> PartialEq for $name<$($T,)* $($C,)*> + where + $($where)* + { + fn eq(&self, rhs: &Self) -> bool { + $(self.$arg == rhs.$arg &&)* self.$ty_name == rhs.$ty_name + } + } + + impl<$($T,)* $(const $C: $CTy,)*> Eq for $name<$($T,)* $($C,)*> + where + $($where)* + { + } + + impl<$($T,)* $(const $C: $CTy,)*> Hash for $name<$($T,)* $($C,)*> + where + $($where)* + { + fn hash(&self, state: &mut H) { + $(self.$arg.hash(state);)* + self.$ty_name.hash(state); + } + } + + impl<$($T,)* $(const $C: $CTy,)*> fmt::Debug for $name<$($T,)* $($C,)*> + where + $($where)* + { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + f.debug_tuple(stringify!($name))$(.field(&self.$arg))*.finish() + } + } + + impl<$($T,)* $(const $C: $CTy,)*> ToExpr for $name<$($T,)* $($C,)*> + where + $($where)* + { + type Type = $Ty; + + fn ty(&self) -> Self::Type { + self.$ty_name.clone() + } + fn to_expr(&self) -> Expr<::Value> { + Expr::new_unchecked(self.expr_enum()) + } + } + + impl<$($T,)* $(const $C: $CTy,)*> ExprTrait for $name<$($T,)* $($C,)*> + where + $($where)* + { + fn expr_enum(&$expr_enum_self) -> ExprEnum { + $($expr_enum_body)+ + } fn target(&self) -> Option> { - None + ($(self.$target_name,)? None::>,).0 + } + fn to_literal_bits(&$to_literal_bits_self) -> Result, ()> { + $($to_literal_bits_body)+ } } - }; -} -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct NotU { - arg: Expr>, - literal_bits: Result, NotALiteralExpr>, -} - -impl NotU { - pub fn new(arg: Expr>) -> Self { - Self { - arg, - literal_bits: arg - .to_literal_bits() - .map(|bits| Intern::intern_owned(bits.to_bitvec().not())), - } - } - pub fn arg(self) -> Expr> { - self.arg - } -} - -impl ToExpr for NotU { - type Type = UIntType; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::NotU(NotU { - arg: Expr::as_dyn_int(self.arg), - literal_bits: self.literal_bits, - }) - .intern(), - __ty: self.arg.__ty, - __flow: Flow::Source, - } - } -} - -impl ToLiteralBits for NotU { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } -} - -impl_get_target_none!([Width: Size] NotU); - -impl_unary_op_trait! { - #[generics(Width: Size)] - fn Not::not(arg: UIntType) -> UIntType { - NotU::new(arg).to_expr() - } -} - -forward_value_to_expr_unary_op_trait! { - #[generics(Width: Size)] - #[value(UIntValue)] - Not::not -} - -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct NotS { - arg: Expr>, - literal_bits: Result, NotALiteralExpr>, -} - -impl NotS { - pub fn new(arg: Expr>) -> Self { - Self { - arg, - literal_bits: arg - .to_literal_bits() - .map(|bits| Intern::intern_owned(bits.to_bitvec().not())), - } - } - pub fn arg(self) -> Expr> { - self.arg - } -} - -impl ToExpr for NotS { - type Type = UIntType; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::NotS(NotS { - arg: Expr::as_dyn_int(self.arg), - literal_bits: self.literal_bits, - }) - .intern(), - __ty: self.arg.__ty.as_same_width_uint(), - __flow: Flow::Source, - } - } -} - -impl ToLiteralBits for NotS { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } -} - -impl_get_target_none!([Width: Size] NotS); - -impl_unary_op_trait! { - #[generics(Width: Size)] - fn Not::not(arg: SIntType) -> UIntType { - NotS::new(arg).to_expr() - } -} - -forward_value_to_expr_unary_op_trait! { - #[generics(Width: Size)] - #[value(SIntValue)] - Not::not -} - -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct NotB { - arg: Expr, - literal_bits: Result, NotALiteralExpr>, -} - -impl NotB { - pub fn new(arg: Expr) -> Self { - Self { - arg, - literal_bits: arg - .to_literal_bits() - .map(|bits| Intern::intern_owned(bits.to_bitvec().not())), - } - } - pub fn arg(self) -> Expr { - self.arg - } -} - -impl ToExpr for NotB { - type Type = Bool; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::NotB(NotB { - arg: self.arg, - literal_bits: self.literal_bits, - }) - .intern(), - __ty: self.arg.__ty, - __flow: Flow::Source, - } - } -} - -impl ToLiteralBits for NotB { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } -} - -impl_get_target_none!([] NotB); - -impl_unary_op_trait! { - #[generics()] - fn Not::not(arg: Bool) -> Bool { - NotB::new(arg).to_expr() - } -} - -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct Neg { - arg: Expr, - literal_bits: Result, NotALiteralExpr>, -} - -impl Neg { - pub fn new(arg: Expr) -> Self { - let mut retval = Self { - arg, - literal_bits: Err(NotALiteralExpr), - }; - let result_ty = retval.ty(); - retval.literal_bits = arg.to_literal_bits().map(|bits| { - Intern::intern_owned(result_ty.bits_from_bigint_wrapping(-SInt::bits_to_bigint(&bits))) - }); - retval - } - pub fn ty(self) -> SInt { - SInt::new_dyn( - Expr::ty(self.arg) - .width() - .checked_add(1) - .expect("width too big"), - ) - } - pub fn arg(self) -> Expr { - self.arg - } -} - -impl ToExpr for Neg { - type Type = SInt; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::Neg(*self).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } -} - -impl ToLiteralBits for Neg { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } -} - -impl_get_target_none!([] Neg); - -impl_unary_op_trait! { - #[generics(Width: Size)] - fn StdNeg::neg(arg: SIntType) -> SInt { - Neg::new(Expr::as_dyn_int(arg)).to_expr() - } -} - -forward_value_to_expr_unary_op_trait! { - #[generics(Width: Size)] - #[value(SIntValue)] - StdNeg::neg -} - -macro_rules! impl_binary_op_trait { - ( - #[generics($($generics:tt)*)] - fn $Trait:ident::$method:ident($lhs:ident: $Lhs:ty, $rhs:ident: $Rhs:ty) -> $Output:ty { - $($body:tt)* - } - ) => { - impl< - Rhs: ToExpr, - $($generics)* - > $Trait for Expr<$Lhs> - { - type Output = Expr<$Output>; - - fn $method(self, rhs: Rhs) -> Self::Output { - let $lhs = self; - let $rhs = rhs.to_expr(); - $($body)* - } - } - }; -} - -macro_rules! forward_value_to_expr_binary_op_trait { - ( - #[generics($($generics:tt)*)] - #[lhs_value($LhsValue:ty)] - $Trait:ident::$method:ident - ) => { - impl< - Rhs, - $($generics)* - > $Trait for $LhsValue + impl<$($T,)* $(const $C: $CTy,)*> sealed::Sealed for $name<$($T,)* $($C,)*> where - Expr<<$LhsValue as ToExpr>::Type>: $Trait, + $($where)* { - type Output = ::Type> as $Trait>::Output; - - fn $method(self, rhs: Rhs) -> Self::Output { - $Trait::$method(self.to_expr(), rhs) - } } }; } -fn binary_op_literal_bits( - result_ty: ResultTy, - lhs: Expr, - rhs: Expr, - f: impl FnOnce(BigInt, BigInt) -> Result, -) -> Result, NotALiteralExpr> { - let lhs = lhs.to_literal_bits()?; - let rhs = rhs.to_literal_bits()?; - let lhs = Lhs::bits_to_bigint(&lhs); - let rhs = Rhs::bits_to_bigint(&rhs); - let result = f(lhs, rhs)?; - Ok(Intern::intern_owned( - result_ty.bits_from_bigint_wrapping(result), - )) -} - -macro_rules! binary_op_bitwise { - ($name:ident, $ty:ident, bool, $Trait:ident::$method:ident) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - lhs: Expr<$ty>, - rhs: Expr<$ty>, - literal_bits: Result, NotALiteralExpr>, - } - - impl $name { - pub fn new(lhs: Expr<$ty>, rhs: Expr<$ty>) -> Self { - Self { - lhs, - rhs, - literal_bits: binary_op_literal_bits($ty, lhs, rhs, |lhs, rhs| { - Ok($Trait::$method(lhs, rhs)) - }), - } - } - pub fn lhs(self) -> Expr<$ty> { - self.lhs - } - pub fn rhs(self) -> Expr<$ty> { - self.rhs - } - } - - impl ToLiteralBits for $name { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } - } - - impl_get_target_none!([] $name); - - impl ToExpr for $name { - type Type = $ty; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::$name(*self).intern(), - __ty: $ty, - __flow: Flow::Source, - } - } - } - - /// intentionally only implemented for expressions, not rust's bool type, - /// since that helps avoid using `==`/`!=` in hdl boolean expressions, which doesn't do - /// what is usually wanted. - impl $Trait for Expr { - type Output = Expr; - - fn $method(self, rhs: Expr) -> Expr { - $name::new(self, rhs).to_expr() - } - } - }; - ($name:ident, $ty:ident, $value:ident, $Trait:ident::$method:ident) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - lhs: Expr<$ty>, - rhs: Expr<$ty>, - literal_bits: Result, NotALiteralExpr>, - } - - impl $name { - pub fn new(lhs: Expr<$ty>, rhs: Expr<$ty>) -> Self { - let mut retval = Self { - lhs, - rhs, - literal_bits: Err(NotALiteralExpr), - }; - retval.literal_bits = binary_op_literal_bits(retval.ty(), lhs, rhs, |lhs, rhs| { - Ok($Trait::$method(lhs, rhs)) - }); - retval - } - pub fn lhs(self) -> Expr<$ty> { - self.lhs - } - pub fn rhs(self) -> Expr<$ty> { - self.rhs - } - pub fn ty(self) -> UInt { - UInt::new_dyn(Expr::ty(self.lhs).width().max(Expr::ty(self.rhs).width())) - } - } - - impl ToLiteralBits for $name { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } - } - - impl_get_target_none!([] $name); - - impl ToExpr for $name { - type Type = UInt; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::$name(*self).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } - } - - impl_binary_op_trait! { - #[generics(LhsWidth: Size, RhsWidth: Size)] - fn $Trait::$method(lhs: $ty, rhs: $ty) -> UInt { - $name::new(Expr::as_dyn_int(lhs), Expr::as_dyn_int(rhs)).to_expr() - } - } - - forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value($value)] - $Trait::$method - } - }; -} - -binary_op_bitwise!(BitAndU, UIntType, UIntValue, BitAnd::bitand); -binary_op_bitwise!(BitAndS, SIntType, SIntValue, BitAnd::bitand); -binary_op_bitwise!(BitAndB, Bool, bool, BitAnd::bitand); -binary_op_bitwise!(BitOrU, UIntType, UIntValue, BitOr::bitor); -binary_op_bitwise!(BitOrS, SIntType, SIntValue, BitOr::bitor); -binary_op_bitwise!(BitOrB, Bool, bool, BitOr::bitor); -binary_op_bitwise!(BitXorU, UIntType, UIntValue, BitXor::bitxor); -binary_op_bitwise!(BitXorS, SIntType, SIntValue, BitXor::bitxor); -binary_op_bitwise!(BitXorB, Bool, bool, BitXor::bitxor); - -macro_rules! binary_op_add_sub { - ($name:ident, $ty:ident, $value:ident, $Trait:ident::$method:ident) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - lhs: Expr<$ty>, - rhs: Expr<$ty>, - literal_bits: Result, NotALiteralExpr>, - } - - impl $name { - pub fn new(lhs: Expr<$ty>, rhs: Expr<$ty>) -> Self { - let mut retval = Self { - lhs, - rhs, - literal_bits: Err(NotALiteralExpr), - }; - retval.literal_bits = binary_op_literal_bits(retval.ty(), lhs, rhs, |lhs, rhs| { - Ok($Trait::$method(lhs, rhs)) - }); - retval - } - pub fn lhs(self) -> Expr<$ty> { - self.lhs - } - pub fn rhs(self) -> Expr<$ty> { - self.rhs - } - pub fn ty(self) -> $ty { - $ty::new_dyn( - Expr::ty(self.lhs) - .width() - .max(Expr::ty(self.rhs).width()) - .checked_add(1) - .expect("width too big"), - ) - } - } - - impl ToLiteralBits for $name { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } - } - - impl_get_target_none!([] $name); - - impl ToExpr for $name { - type Type = $ty; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::$name(*self).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } - } - - impl_binary_op_trait! { - #[generics(LhsWidth: Size, RhsWidth: Size)] - fn $Trait::$method(lhs: $ty, rhs: $ty) -> $ty { - $name::new(Expr::as_dyn_int(lhs), Expr::as_dyn_int(rhs)).to_expr() - } - } - - forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value($value)] - $Trait::$method - } - }; -} - -binary_op_add_sub!(AddU, UIntType, UIntValue, Add::add); -binary_op_add_sub!(AddS, SIntType, SIntValue, Add::add); -binary_op_add_sub!(SubU, UIntType, UIntValue, Sub::sub); -binary_op_add_sub!(SubS, SIntType, SIntValue, Sub::sub); - -macro_rules! binary_op_mul { - ($name:ident, $ty:ident, $value:ident) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - lhs: Expr<$ty>, - rhs: Expr<$ty>, - literal_bits: Result, NotALiteralExpr>, - } - - impl $name { - pub fn new(lhs: Expr<$ty>, rhs: Expr<$ty>) -> Self { - let mut retval = Self { - lhs, - rhs, - literal_bits: Err(NotALiteralExpr), - }; - retval.literal_bits = binary_op_literal_bits(retval.ty(), lhs, rhs, |lhs, rhs| { - Ok(Mul::mul(lhs, rhs)) - }); - retval - } - pub fn lhs(self) -> Expr<$ty> { - self.lhs - } - pub fn rhs(self) -> Expr<$ty> { - self.rhs - } - pub fn ty(self) -> $ty { - $ty::new_dyn( - Expr::ty(self.lhs) - .width() - .checked_add(Expr::ty(self.rhs).width()) - .expect("width too big"), - ) - } - } - - impl ToLiteralBits for $name { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } - } - - impl_get_target_none!([] $name); - - impl ToExpr for $name { - type Type = $ty; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::$name(*self).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } - } - - impl_binary_op_trait! { - #[generics(LhsWidth: Size, RhsWidth: Size)] - fn Mul::mul(lhs: $ty, rhs: $ty) -> $ty { - $name::new(Expr::as_dyn_int(lhs), Expr::as_dyn_int(rhs)).to_expr() - } - } - - forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value($value)] - Mul::mul - } - }; -} - -binary_op_mul!(MulU, UIntType, UIntValue); -binary_op_mul!(MulS, SIntType, SIntValue); - -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct DivU { - lhs: Expr>, - rhs: Expr, - literal_bits: Result, NotALiteralExpr>, -} - -impl DivU { - pub fn new(lhs: Expr>, rhs: Expr) -> Self { - let mut retval = Self { - lhs, - rhs, - literal_bits: Err(NotALiteralExpr), - }; - retval.literal_bits = binary_op_literal_bits(retval.ty(), lhs, rhs, |lhs, rhs| { - lhs.checked_div(&rhs).ok_or(NotALiteralExpr) - }); - retval - } - pub fn lhs(self) -> Expr> { - self.lhs - } - pub fn rhs(self) -> Expr { - self.rhs - } - pub fn ty(self) -> UIntType { - Expr::ty(self.lhs) - } -} - -impl ToLiteralBits for DivU { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } -} - -impl_get_target_none!([LhsWidth: Size] DivU); - -impl ToExpr for DivU { - type Type = UIntType; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::DivU(DivU { - lhs: Expr::as_dyn_int(self.lhs), - rhs: self.rhs, - literal_bits: self.literal_bits, - }) - .intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } -} - -impl_binary_op_trait! { - #[generics(LhsWidth: Size, RhsWidth: Size)] - fn Div::div(lhs: UIntType, rhs: UIntType) -> UIntType { - DivU::new(lhs, Expr::as_dyn_int(rhs)).to_expr() - } -} - -forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value(UIntValue)] - Div::div -} - -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct DivS { - lhs: Expr, - rhs: Expr, - literal_bits: Result, NotALiteralExpr>, -} - -impl DivS { - pub fn new(lhs: Expr, rhs: Expr) -> Self { - let mut retval = Self { - lhs, - rhs, - literal_bits: Err(NotALiteralExpr), - }; - retval.literal_bits = binary_op_literal_bits(retval.ty(), lhs, rhs, |lhs, rhs| { - lhs.checked_div(&rhs).ok_or(NotALiteralExpr) - }); - retval - } - pub fn lhs(self) -> Expr { - self.lhs - } - pub fn rhs(self) -> Expr { - self.rhs - } - pub fn ty(self) -> SInt { - SInt::new_dyn( - Expr::ty(self.lhs) - .width() - .checked_add(1) - .expect("width too big"), - ) - } -} - -impl ToLiteralBits for DivS { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } -} - -impl_get_target_none!([] DivS); - -impl ToExpr for DivS { - type Type = SInt; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::DivS(*self).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } -} - -impl_binary_op_trait! { - #[generics(LhsWidth: Size, RhsWidth: Size)] - fn Div::div(lhs: SIntType, rhs: SIntType) -> SInt { - DivS::new(Expr::as_dyn_int(lhs), Expr::as_dyn_int(rhs)).to_expr() - } -} - -forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value(SIntValue)] - Div::div -} - -macro_rules! binary_op_rem { - ($name:ident, $ty:ident, $value:ident) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - lhs: Expr<$ty>, - rhs: Expr<$ty>, - literal_bits: Result, NotALiteralExpr>, - } - - impl $name { - pub fn new(lhs: Expr<$ty>, rhs: Expr<$ty>) -> Self { - let mut retval = Self { - lhs, - rhs, - literal_bits: Err(NotALiteralExpr), - }; - retval.literal_bits = binary_op_literal_bits(retval.ty(), lhs, rhs, |lhs, rhs| { - if rhs.is_zero() { - Err(NotALiteralExpr) - } else { - Ok(lhs % rhs) - } - }); - retval - } - pub fn lhs(self) -> Expr<$ty> { - self.lhs - } - pub fn rhs(self) -> Expr<$ty> { - self.rhs - } - pub fn ty(self) -> $ty { - $ty::new_dyn(Expr::ty(self.lhs).width().min(Expr::ty(self.rhs).width())) - } - } - - impl ToLiteralBits for $name { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } - } - - impl_get_target_none!([] $name); - - impl ToExpr for $name { - type Type = $ty; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::$name(*self).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } - } - - impl_binary_op_trait! { - #[generics(LhsWidth: Size, RhsWidth: Size)] - fn Rem::rem(lhs: $ty, rhs: $ty) -> $ty { - $name::new(Expr::as_dyn_int(lhs), Expr::as_dyn_int(rhs)).to_expr() - } - } - - forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value($value)] - Rem::rem - } - }; -} - -binary_op_rem!(RemU, UIntType, UIntValue); -binary_op_rem!(RemS, SIntType, SIntValue); - -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct BundleLiteral { - ty: T, - field_values: Interned<[Expr]>, - literal_bits: Result, NotALiteralExpr>, -} - -impl BundleLiteral { - #[track_caller] - pub fn new(ty: T, field_values: Interned<[Expr]>) -> Self { - let fields = ty.fields(); - assert!( - Bundle::new(fields).type_properties().is_passive, - "bundle literal's type must be a passive type" - ); - assert_eq!(fields.len(), field_values.len()); - let mut literal_bits = Some(BitVec::new()); - for (&field, &field_value) in fields.iter().zip(field_values.iter()) { - assert_eq!( - field.ty, - Expr::ty(field_value), - "field's type doesn't match value's type: field name {:?}", - field.name - ); - if let (Some(literal_bits), Ok(field_bits)) = - (&mut literal_bits, field_value.to_literal_bits()) - { - literal_bits.extend_from_bitslice(&field_bits); - } else { - literal_bits = None; - } - } - Self { - ty, - field_values, - literal_bits: literal_bits - .map(Intern::intern_owned) - .ok_or(NotALiteralExpr), - } - } - pub fn ty(self) -> T { - self.ty - } - pub fn field_values(self) -> Interned<[Expr]> { - self.field_values - } -} - -impl ToLiteralBits for BundleLiteral { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } -} - -impl_get_target_none!([T: BundleType] BundleLiteral); - -impl ToExpr for BundleLiteral { - type Type = T; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::BundleLiteral(BundleLiteral { - ty: Bundle::new(self.ty.fields()), - field_values: self.field_values, - literal_bits: self.literal_bits, - }) - .intern(), - __ty: self.ty, - __flow: Flow::Source, - } - } -} - -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct ArrayLiteral { - element_type: Element, - element_values: Interned<[Expr]>, - literal_bits: Result, NotALiteralExpr>, - _phantom: PhantomData, -} - -impl ArrayLiteral { - #[track_caller] - pub fn new(element_type: Element, element_values: Interned<[Expr]>) -> Self { - let canonical_element_type = element_type.canonical(); - assert!( - canonical_element_type.is_passive(), - "array literal's type must be a passive type" - ); - Len::from_usize(element_values.len()); // check that len is correct - let mut literal_bits = Some(BitVec::new()); - for &element_value in element_values.iter() { - assert_eq!( - canonical_element_type, - Expr::ty(element_value), - "array's element type doesn't match element value's type", - ); - if let (Some(literal_bits), Ok(element_bits)) = - (&mut literal_bits, element_value.to_literal_bits()) - { - literal_bits.extend_from_bitslice(&element_bits); - } else { - literal_bits = None; - } - } - Self { - element_type, - element_values, - literal_bits: literal_bits - .map(Intern::intern_owned) - .ok_or(NotALiteralExpr), - _phantom: PhantomData, - } - } - pub fn element_type(self) -> Element { - self.element_type - } - pub fn len(self) -> usize { - self.element_values.len() - } - pub fn is_empty(self) -> bool { - self.element_values.is_empty() - } - pub fn ty(self) -> ArrayType { - ArrayType::new( - self.element_type, - Len::from_usize(self.element_values.len()), - ) - } - pub fn element_values(self) -> Interned<[Expr]> { - self.element_values - } -} - -impl ToLiteralBits for ArrayLiteral { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } -} - -impl_get_target_none!([Element: Type, Len: Size] ArrayLiteral); - -impl ToExpr for ArrayLiteral { - type Type = ArrayType; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::ArrayLiteral(ArrayLiteral { - element_type: self.element_type.canonical(), - element_values: self.element_values, - literal_bits: self.literal_bits, - _phantom: PhantomData, - }) - .intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } -} - -impl, const N: usize> ToExpr for [T; N] -where - ConstUsize: KnownSize, -{ - type Type = Array; - - fn to_expr(&self) -> Expr { - ArrayLiteral::new( - T::Type::TYPE, - self.iter().map(|v| Expr::canonical(v.to_expr())).collect(), - ) - .to_expr() - } -} - -impl> ToExpr for [T] { - type Type = Array; - - fn to_expr(&self) -> Expr { - ArrayLiteral::new( - T::Type::TYPE, - self.iter().map(|v| Expr::canonical(v.to_expr())).collect(), - ) - .to_expr() - } -} - -impl> ToExpr for Vec { - type Type = Array; - - fn to_expr(&self) -> Expr { - <[T]>::to_expr(self) - } -} - -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct EnumLiteral { - ty: T, - variants: Interned<[EnumVariant]>, - variant_index: usize, - variant_value: Option>, - literal_bits: Result, NotALiteralExpr>, -} - -impl EnumLiteral { - #[track_caller] - pub fn new_by_index( - ty: T, - variant_index: usize, - variant_value: Option>, - ) -> Self { - let variants = ty.variants(); - let canonical_ty = Enum::new(variants); - assert!(variant_index < variants.len()); - assert_eq!( - variants[variant_index].ty, - variant_value.map(Expr::ty), - "variant's type doesn't match value's type: variant name {:?}", - variants[variant_index].name - ); - let literal_bits = if let Ok(variant_value) = variant_value - .map(|variant_value| variant_value.to_literal_bits()) - .transpose() - { - let mut literal_bits = BitVec::with_capacity(canonical_ty.type_properties().bit_width); - literal_bits.extend_from_bitslice( - &[variant_index].view_bits::()[..canonical_ty.discriminant_bit_width()], - ); - if let Some(variant_value) = variant_value { - literal_bits.extend_from_bitslice(&variant_value); - } - literal_bits.resize(canonical_ty.type_properties().bit_width, false); - Ok(Intern::intern_owned(literal_bits)) - } else { - Err(NotALiteralExpr) - }; - Self { - ty, - variants, - variant_index, - variant_value, - literal_bits, - } - } - #[track_caller] - pub fn new_by_name( - ty: T, - variant_name: Interned, - variant_value: Option>, - ) -> Self { - let enum_ty = Enum::new(ty.variants()); - let Some(variant_index) = enum_ty.name_indexes().get(&variant_name) else { - panic!("unknown variant {variant_name:?}: in {ty:?}"); - }; - Self::new_by_index(ty, *variant_index, variant_value) - } - pub fn ty(self) -> T { - self.ty - } - pub fn variant_index(self) -> usize { - self.variant_index - } - pub fn variant_name(self) -> Interned { - self.variants[self.variant_index].name - } - pub fn variant_value(self) -> Option> { - self.variant_value - } -} - -impl ToLiteralBits for EnumLiteral { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } -} - -impl_get_target_none!([T: EnumType] EnumLiteral); - -impl ToExpr for EnumLiteral { - type Type = T; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::EnumLiteral(EnumLiteral { - ty: Enum::new(self.variants), - variants: self.variants, - variant_index: self.variant_index, - variant_value: self.variant_value, - literal_bits: self.literal_bits, - }) - .intern(), - __ty: self.ty, - __flow: Flow::Source, - } - } -} - -macro_rules! impl_dyn_shl { - ($name:ident, $ty:ident, $value:ident) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - lhs: Expr<$ty>, - rhs: Expr, - literal_bits: Result, NotALiteralExpr>, - } - - impl $name { - #[track_caller] - pub fn new(lhs: Expr<$ty>, rhs: Expr) -> Self { - let mut retval = Self { - lhs, - rhs, - literal_bits: Err(NotALiteralExpr), - }; - retval.literal_bits = binary_op_literal_bits(retval.ty(), lhs, rhs, |lhs, rhs| { - Ok(lhs << rhs.to_usize().ok_or(NotALiteralExpr)?) - }); - retval - } - pub fn lhs(self) -> Expr<$ty> { - self.lhs - } - pub fn rhs(self) -> Expr { - self.rhs - } - #[track_caller] - pub fn ty(self) -> $ty { - let Some(pow2_rhs_width) = Expr::ty(self.rhs) - .width() - .try_into() - .ok() - .and_then(|v| 2usize.checked_pow(v)) - else { - panic!( - "dynamic left-shift amount's bit-width is too big, try casting the shift \ - amount to a smaller bit-width before shifting" - ); - }; - $ty::new_dyn( - (pow2_rhs_width - 1) - .checked_add(Expr::ty(self.lhs).width()) - .expect("width too big"), - ) - } - } - - impl ToLiteralBits for $name { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } - } - - impl_get_target_none!([] $name); - - impl ToExpr for $name { - type Type = $ty; - - #[track_caller] - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::$name(*self).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } - } - - impl_binary_op_trait! { - #[generics(LhsWidth: Size, RhsWidth: Size)] - fn Shl::shl(lhs: $ty, rhs: UIntType) -> $ty { - $name::new(Expr::as_dyn_int(lhs), Expr::as_dyn_int(rhs)).to_expr() - } - } - }; -} - -impl_dyn_shl!(DynShlU, UIntType, UIntValue); -impl_dyn_shl!(DynShlS, SIntType, SIntValue); - -macro_rules! impl_dyn_shr { - ($name:ident, $ty:ident, $value:ident) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - lhs: Expr<$ty>, - rhs: Expr, - literal_bits: Result, NotALiteralExpr>, - } - - impl $name { - #[track_caller] - pub fn new(lhs: Expr<$ty>, rhs: Expr) -> Self { - let mut retval = Self { - lhs, - rhs, - literal_bits: Err(NotALiteralExpr), - }; - retval.literal_bits = binary_op_literal_bits(retval.ty(), lhs, rhs, |lhs, rhs| { - Ok(lhs << rhs.to_usize().ok_or(NotALiteralExpr)?) - }); - retval - } - pub fn lhs(self) -> Expr<$ty> { - self.lhs - } - pub fn rhs(self) -> Expr { - self.rhs - } - #[track_caller] - pub fn ty(self) -> $ty { - Expr::ty(self.lhs) - } - } - - impl ToLiteralBits for $name { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } - } - - impl_get_target_none!([] $name); - - impl ToExpr for $name { - type Type = $ty; - - #[track_caller] - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::$name($name { - lhs: Expr::as_dyn_int(self.lhs), - rhs: self.rhs, - literal_bits: self.literal_bits, - }) - .intern(), - __ty: Expr::ty(self.lhs), - __flow: Flow::Source, - } - } - } - - impl_binary_op_trait! { - #[generics(LhsWidth: Size, RhsWidth: Size)] - fn Shr::shr(lhs: $ty, rhs: UIntType) -> $ty { - $name::new(lhs, Expr::as_dyn_int(rhs)).to_expr() - } - } - }; -} - -impl_dyn_shr!(DynShrU, UIntType, UIntValue); -impl_dyn_shr!(DynShrS, SIntType, SIntValue); - -fn fixed_shr_width(lhs_width: usize, rhs: usize) -> Option { - Some(lhs_width.saturating_sub(rhs).max(1)) -} - -macro_rules! binary_op_fixed_shift { - ($name:ident, $ty:ident, $value:ident, $width_fn:path, $Trait:ident::$method:ident) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - lhs: Expr<$ty>, - rhs: usize, - literal_bits: Result, NotALiteralExpr>, - } - - impl $name { - pub fn new(lhs: Expr<$ty>, rhs: usize) -> Self { - let mut retval = Self { - lhs, - rhs, - literal_bits: Err(NotALiteralExpr), - }; - retval.literal_bits = lhs.to_literal_bits().map(|bits| { - Intern::intern_owned(retval.ty().bits_from_bigint_wrapping($Trait::$method( - $ty::bits_to_bigint(&bits), - rhs, - ))) - }); - retval - } - pub fn lhs(self) -> Expr<$ty> { - self.lhs - } - pub fn rhs(self) -> usize { - self.rhs - } - pub fn ty(self) -> $ty { - $ty::new_dyn( - $width_fn(Expr::ty(self.lhs).width(), self.rhs).expect("width too big"), - ) - } - } - - impl ToLiteralBits for $name { - fn to_literal_bits(&self) -> Result, NotALiteralExpr> { - self.literal_bits - } - } - - impl_get_target_none!([] $name); - - impl ToExpr for $name { - type Type = $ty; - - fn to_expr(&self) -> Expr { - Expr { - __enum: ExprEnum::$name(*self).intern(), - __ty: self.ty(), - __flow: Flow::Source, - } - } - } - - impl $Trait for Expr<$ty> { - type Output = Expr<$ty>; - - fn $method(self, rhs: usize) -> Self::Output { - $name::new(Expr::as_dyn_int(self), rhs).to_expr() - } - } - }; -} - -binary_op_fixed_shift!(FixedShlU, UIntType, UIntValue, usize::checked_add, Shl::shl); -binary_op_fixed_shift!(FixedShlS, SIntType, SIntValue, usize::checked_add, Shl::shl); -binary_op_fixed_shift!(FixedShrU, UIntType, UIntValue, fixed_shr_width, Shr::shr); -binary_op_fixed_shift!(FixedShrS, SIntType, SIntValue, fixed_shr_width, Shr::shr); - -forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value(UIntValue)] - Shl::shl -} - -forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value(SIntValue)] - Shl::shl -} - -forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value(UIntValue)] - Shr::shr -} - -forward_value_to_expr_binary_op_trait! { - #[generics(LhsWidth: Size)] - #[lhs_value(SIntValue)] - Shr::shr -} - -pub trait IntCmpExpr: Type { - fn cmp_eq(lhs: Expr, rhs: Expr) -> Expr; - fn cmp_ne(lhs: Expr, rhs: Expr) -> Expr; - fn cmp_lt(lhs: Expr, rhs: Expr) -> Expr; - fn cmp_le(lhs: Expr, rhs: Expr) -> Expr; - fn cmp_gt(lhs: Expr, rhs: Expr) -> Expr; - fn cmp_ge(lhs: Expr, rhs: Expr) -> Expr; -} - -impl IntCmp for Lhs -where - Lhs::Type: IntCmpExpr, -{ - fn cmp_eq(self, rhs: Rhs) -> Expr { - IntCmpExpr::cmp_eq(self.to_expr(), rhs.to_expr()) - } - fn cmp_ne(self, rhs: Rhs) -> Expr { - IntCmpExpr::cmp_ne(self.to_expr(), rhs.to_expr()) - } - fn cmp_lt(self, rhs: Rhs) -> Expr { - IntCmpExpr::cmp_lt(self.to_expr(), rhs.to_expr()) - } - fn cmp_le(self, rhs: Rhs) -> Expr { - IntCmpExpr::cmp_le(self.to_expr(), rhs.to_expr()) - } - fn cmp_gt(self, rhs: Rhs) -> Expr { - IntCmpExpr::cmp_gt(self.to_expr(), rhs.to_expr()) - } - fn cmp_ge(self, rhs: Rhs) -> Expr { - IntCmpExpr::cmp_ge(self.to_expr(), rhs.to_expr()) - } -} - -macro_rules! impl_compare_op { +macro_rules! unary_op { ( - $(#[width($LhsWidth:ident, $RhsWidth:ident)])? - #[dyn_type($DynTy:ident)] - #[to_dyn_type($lhs:ident => $dyn_lhs:expr, $rhs:ident => $dyn_rhs:expr)] - #[type($Lhs:ty, $Rhs:ty)] - $( - struct $name:ident; - fn $method:ident(); - $CmpTrait:ident::$cmp_method:ident(); - )* - ) => { - $(#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - lhs: Expr<$DynTy>, - rhs: Expr<$DynTy>, - literal_bits: Result, NotALiteralExpr>, + #[method = $op:ident] + impl<$T:ident> $Op:ident for _ where ($($where:tt)*) { + fn expr_enum(&$expr_enum_self:ident) -> _ { + $($expr_enum_body:tt)+ + } } + ) => { + fixed_ary_op! { + pub struct $Op<$T,> + where ( + $($where)* + ) + { + pub arg: Expr<$T::CanonicalValue>, + #[type] + ty: < as ops::$Op>::Output as ValuelessTr>::Type = ops::$Op::$op( + Valueless::<$T>::from_canonical(arg.valueless()), + ).ty, + #[cache] + literal_bits: Result, ()> = { + arg.to_literal_bits() + .map(|v| ops::$Op::$op($T::CanonicalValue::from_bit_slice(&v)).to_bits()) + }, - impl $name { - pub fn new(lhs: Expr<$DynTy>, rhs: Expr<$DynTy>) -> Self { - Self { - lhs, - rhs, - literal_bits: binary_op_literal_bits(Bool, lhs, rhs, |lhs, rhs| { - Ok($CmpTrait::$cmp_method(&lhs, &rhs).into()) - }), + fn simulate(&self, sim_state: &mut SimState) -> _ { + ops::$Op::$op(self.arg.simulate(sim_state)) + } + + fn expr_enum(&$expr_enum_self) -> _ { + $($expr_enum_body)+ + } + + fn to_literal_bits(&self) -> Result, ()> { + self.literal_bits } } - pub fn lhs(self) -> Expr<$DynTy> { - self.lhs + } + + impl<$T, V: Value> ops::$Op for Expr + where + $($where)* + { + type Output = Expr<< as ops::$Op>::Output as ValuelessTr>::Value>; + + fn $op(self) -> Self::Output { + $Op::<$T>::new_unchecked(self.canonical()).to_expr() } - pub fn rhs(self) -> Expr<$DynTy> { - self.rhs + } + }; +} + +unary_op! { + #[method = not] + impl Not for _ + where ( + T: IntTypeTrait< + CanonicalType = DynIntType<::Signed>, + CanonicalValue = DynInt<::Signed>, + >, + ) + { + fn expr_enum(&self) -> _ { + struct Tag; + impl ConstBoolDispatchTag for Tag { + type Type = Not>; + } + match ConstBoolDispatch::new::(self.canonical()) { + ConstBoolDispatch::False(v) => ExprEnum::NotU(v.intern_sized()), + ConstBoolDispatch::True(v) => ExprEnum::NotS(v.intern_sized()), + } + } + } +} + +unary_op! { + #[method = neg] + impl Neg for _ + where ( + T: IntTypeTrait< + Signed = ConstBool, + CanonicalType = DynSIntType, + CanonicalValue = DynSInt, + >, + ) + { + fn expr_enum(&self) -> _ { + ExprEnum::Neg(self.canonical().intern_sized()) + } + } +} + +macro_rules! binary_op { + ( + #[ + method = $op:ident, + rhs_to_canonical_dyn = $rhs_to_canonical_dyn:ident, + expr_enum_u = $expr_enum_u:ident, + expr_enum_s = $expr_enum_s:ident + ] + impl<$LhsType:ident, $RhsType:ident> $Op:ident for _ where $($where:tt)* + ) => { + fixed_ary_op! { + pub struct $Op<$LhsType, $RhsType,> + where ( + $($where)* + ) + { + pub lhs: Expr<$LhsType::CanonicalValue>, + pub rhs: Expr<$RhsType::CanonicalValue>, + #[type] + ty: < + as ops::$Op>>::Output + as ValuelessTr + >::Type = ops::$Op::$op( + Valueless::<$LhsType>::from_canonical(lhs.valueless()), + Valueless::<$RhsType>::from_canonical(rhs.valueless()), + ).ty, + #[cache] + literal_bits: Result, ()> = { + lhs.to_literal_bits() + .ok() + .zip(rhs.to_literal_bits().ok()) + .map(|(lhs, rhs)| { + ops::$Op::$op( + $LhsType::CanonicalValue::from_bit_slice(&lhs), + $RhsType::CanonicalValue::from_bit_slice(&rhs), + ) + .to_bits() + }) + .ok_or(()) + }, + fn simulate(&self, sim_state: &mut SimState) -> _ { + ops::$Op::$op(self.lhs.simulate(sim_state), self.rhs.simulate(sim_state)) + } + fn expr_enum(&self) -> _ { + struct Tag; + impl ConstBoolDispatchTag for Tag { + type Type = + $Op, DynIntType, DynUIntType>; + } + match ConstBoolDispatch::new::(self.canonical()) { + ConstBoolDispatch::False(v) => ExprEnum::$CmpOpU(v.intern_sized()), + ConstBoolDispatch::True(v) => ExprEnum::$CmpOpS(v.intern_sized()), + } + } + + fn to_literal_bits(&self) -> Result, ()> { + self.literal_bits } } })* - impl$(<$LhsWidth: Size, $RhsWidth: Size>)? IntCmpExpr<$Rhs> for $Lhs { - $(fn $method($lhs: Expr, $rhs: Expr<$Rhs>) -> Expr { - $name::new($dyn_lhs, $dyn_rhs).to_expr() + impl< + LhsType: IntTypeTrait< + CanonicalType = DynIntType<::Signed>, + CanonicalValue = DynInt<::Signed>, + >, + RhsType: IntTypeTrait< + Signed = LhsType::Signed, + CanonicalType = DynIntType<::Signed>, + CanonicalValue = DynInt<::Signed>, + >, + Rhs: ToExpr, + Lhs: Value, + > IntCmp for Expr + { + type Output = Expr>; + + $(fn $fn(self, rhs: Rhs) -> Self::Output { + $CmpOp::>::new_unchecked( + self.canonical(), + rhs.to_expr().canonical(), + ).to_expr() + })* + } + + impl< + LhsType: IntTypeTrait< + CanonicalType = DynIntType<::Signed>, + CanonicalValue = DynInt<::Signed>, + >, + RhsType: IntTypeTrait< + Signed = LhsType::Signed, + CanonicalType = DynIntType<::Signed>, + CanonicalValue = DynInt<::Signed>, + >, + Rhs: ToExpr, + > IntCmp for IntValue { + type Output = Expr>; + + $(fn $fn(self, rhs: Rhs) -> Self::Output { + self.to_expr().$fn(rhs) + })* + } + + impl< + LhsType: IntTypeTrait, + RhsType: IntTypeTrait, + > IntCmp> for Valueless { + type Output = Valueless>; + + $(fn $fn(self, _rhs: Valueless) -> Self::Output { + Valueless { ty: UIntType::new() } })* } }; } -impl_compare_op! { - #[dyn_type(Bool)] - #[to_dyn_type(lhs => lhs, rhs => rhs)] - #[type(Bool, Bool)] - struct CmpEqB; fn cmp_eq(); PartialEq::eq(); - struct CmpNeB; fn cmp_ne(); PartialEq::ne(); - struct CmpLtB; fn cmp_lt(); PartialOrd::lt(); - struct CmpLeB; fn cmp_le(); PartialOrd::le(); - struct CmpGtB; fn cmp_gt(); PartialOrd::gt(); - struct CmpGeB; fn cmp_ge(); PartialOrd::ge(); +cmp_op! { + CmpLt, CmpLtU, CmpLtS, cmp_lt, PartialOrd::lt; + CmpLe, CmpLeU, CmpLeS, cmp_le, PartialOrd::le; + CmpGt, CmpGtU, CmpGtS, cmp_gt, PartialOrd::gt; + CmpGe, CmpGeU, CmpGeS, cmp_ge, PartialOrd::ge; + CmpEq, CmpEqU, CmpEqS, cmp_eq, PartialEq::eq; + CmpNe, CmpNeU, CmpNeS, cmp_ne, PartialEq::ne; } -impl_compare_op! { - #[width(LhsWidth, RhsWidth)] - #[dyn_type(UInt)] - #[to_dyn_type(lhs => Expr::as_dyn_int(lhs), rhs => Expr::as_dyn_int(rhs))] - #[type(UIntType, UIntType)] - struct CmpEqU; fn cmp_eq(); PartialEq::eq(); - struct CmpNeU; fn cmp_ne(); PartialEq::ne(); - struct CmpLtU; fn cmp_lt(); PartialOrd::lt(); - struct CmpLeU; fn cmp_le(); PartialOrd::le(); - struct CmpGtU; fn cmp_gt(); PartialOrd::gt(); - struct CmpGeU; fn cmp_ge(); PartialOrd::ge(); -} +fixed_ary_op! { + pub struct CastInt + where ( + FromType: IntTypeTrait< + CanonicalType = DynIntType<::Signed>, + CanonicalValue = DynInt<::Signed>, + >, + ToType: IntTypeTrait< + CanonicalType = DynIntType<::Signed>, + CanonicalValue = DynInt<::Signed>, + >, + ) + { + pub value: Expr, + #[type(ty)] + pub ty: ToType = ty, + #[cache] + literal_bits: Result, ()> = { + value.to_literal_bits().map(|literal_bits| { + let mut bits = literal_bits.to_bitvec(); + let fill = FromType::Signed::VALUE + && bits.len().checked_sub(1).map(|i| bits[i]).unwrap_or(false); + bits.resize(ty.width(), fill); + Intern::intern_owned(bits) + }) + }, -impl_compare_op! { - #[width(LhsWidth, RhsWidth)] - #[dyn_type(SInt)] - #[to_dyn_type(lhs => Expr::as_dyn_int(lhs), rhs => Expr::as_dyn_int(rhs))] - #[type(SIntType, SIntType)] - struct CmpEqS; fn cmp_eq(); PartialEq::eq(); - struct CmpNeS; fn cmp_ne(); PartialEq::ne(); - struct CmpLtS; fn cmp_lt(); PartialOrd::lt(); - struct CmpLeS; fn cmp_le(); PartialOrd::le(); - struct CmpGtS; fn cmp_gt(); PartialOrd::gt(); - struct CmpGeS; fn cmp_ge(); PartialOrd::ge(); -} - -pub trait ExprCastTo: Type { - fn cast_to(src: Expr, to_type: ToType) -> Expr; -} - -impl ExprCastTo for Bool { - fn cast_to(src: Expr, _to_type: Bool) -> Expr { - src - } -} - -macro_rules! impl_cast_int_op { - ($name:ident, $from:ident, $to:ident) => { - #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] - pub struct $name { - arg: Expr<$from>, - ty: $to, - literal_bits: Result, NotALiteralExpr>, + fn simulate(&self, sim_state: &mut SimState) -> _ { + self.value.simulate(sim_state).cast_as_type(self.ty.canonical()) } - impl $name { - pub fn new(arg: Expr<$from>, ty: $to) -> Self { - Self { - arg, - ty, - literal_bits: arg.to_literal_bits().map(|bits| { - Intern::intern_owned( - ty.bits_from_bigint_wrapping($from::bits_to_bigint(&bits)), - ) - }), + fn expr_enum(&self) -> _ { + struct Tag1; + impl ConstBoolDispatchTag for Tag1 { + type Type = ConstBoolDispatch< + CastInt, DynUIntType>, + CastInt, DynSIntType>, + >; + } + struct Tag2(FromSigned); + impl ConstBoolDispatchTag for Tag2 { + type Type = + CastInt, DynIntType