fayalite/crates/fayalite-proc-macros-impl/src/hdl_type_common.rs

4264 lines
144 KiB
Rust

// SPDX-License-Identifier: LGPL-3.0-or-later
// See Notices.txt for copyright information
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=>
#[allow(clippy::type_complexity)]
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<F: FnOnce(&mut TokenStream)>(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<ParsedExpr>,
}
impl_fold! {
struct ParsedExprDelimited<> {
delim: ExprDelimiter,
expr: Box<ParsedExpr>,
}
}
impl From<ParsedExprDelimited> 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<ParsedExprNamedParamConst> 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<Expr>),
}
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<Expr>),
}
}
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<ParsedExpr> 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<Box<ParsedExpr>> for Expr {
fn from(value: Box<ParsedExpr>) -> Self {
(*value).into()
}
}
impl ParseTypes<Expr> for ParsedExpr {
fn parse_types(input: &mut Expr, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
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<F: FnOnce(&mut TokenStream)>(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<ParsedType>,
}
impl_fold! {
struct ParsedTypeDelimited<> {
delim: TypeDelimiter,
elem: Box<ParsedType>,
}
}
impl From<ParsedTypeDelimited> 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<ParsedType, Token![,]>,
}
impl_fold! {
struct ParsedTypeTuple<> {
paren_token: Paren,
elems: Punctuated<ParsedType, Token![,]>,
}
}
impl From<ParsedTypeTuple> 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<TypeTuple> for ParsedTypeTuple {
fn parse_types(ty: &mut TypeTuple, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
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<GenericArgument> for ParsedGenericArgument {
fn parse_types(
arg: &mut GenericArgument,
parser: &mut TypesParser<'_>,
) -> Result<Self, ParseFailed> {
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<ParsedGenericArgument> 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<Token![::]>,
pub(crate) lt_token: Token![<],
pub(crate) args: Punctuated<ParsedGenericArgument, Token![,]>,
pub(crate) gt_token: Token![>],
}
impl_fold! {
struct ParsedGenericArguments<> {
colon2_token: Option<Token![::]>,
lt_token: Token![<],
args: Punctuated<ParsedGenericArgument, Token![,]>,
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<AngleBracketedGenericArguments> for ParsedGenericArguments {
fn parse_types(
args: &mut AngleBracketedGenericArguments,
parser: &mut TypesParser<'_>,
) -> Result<Self, ParseFailed> {
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<ParsedGenericArguments> 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<ParsedGenericArguments>,
}
impl_fold! {
struct ParsedTypeNamed<> {
path: Path,
args: Option<ParsedGenericArguments>,
}
}
impl From<ParsedTypeNamed> 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<ParsedTypeNamedParam> 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<ParsedTypeConstUsize> 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<ParsedTypeConstUsize> 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<Result<Self, ParsedTypeNamed>, 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<Result<Self, ParsedTypeNamed>, 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<ParsedType>,
#[separator]
comma_token: Token![,],
#[const]
const_len: Option<Box<ParsedExpr>>,
#[type(default = |span| ParsedType::DynSize(known_items::DynSize(span)))]
type_len: Box<ParsedType>,
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<Box<ParsedExpr>>,
#[type(default = |span| ParsedType::DynSize(known_items::DynSize(span)))]
type_width: Box<ParsedType>,
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<Box<ParsedExpr>>,
#[type(default = |span| ParsedType::DynSize(known_items::DynSize(span)))]
type_width: Box<ParsedType>,
gt_token: Token![>],
}
}
#[derive(Debug, Clone)]
pub(crate) struct ParsedTypePhantomData {
pub(crate) phantom_data: known_items::PhantomData,
pub(crate) lt_token: Token![<],
pub(crate) ty: Box<ParsedType>,
pub(crate) gt_token: Token![>],
}
impl_fold! {
struct ParsedTypePhantomData<> {
phantom_data: known_items::PhantomData,
lt_token: Token![<],
ty: Box<ParsedType>,
gt_token: Token![>],
}
}
impl ParsedTypePhantomData {
pub(crate) fn try_from_named(
named: ParsedTypeNamed,
parser: &mut TypesParser<'_>,
) -> Result<Result<Self, ParsedTypeNamed>, ParseFailed> {
let ParsedTypeNamed { path, args } = named;
let parsed_path = known_items::PhantomData::parse_path(path);
let phantom_data = match parsed_path {
Ok(phantom_data) => phantom_data,
Err(path) => return Ok(Err(ParsedTypeNamed { path, args })),
};
let Some(ParsedGenericArguments {
colon2_token: _,
lt_token,
args,
gt_token,
}) = args
else {
parser
.errors()
.error(phantom_data, "PhantomData requires generic arguments");
return Err(ParseFailed);
};
let args_len = args.len();
if args_len != 1 {
parser.errors().error(
phantom_data,
format_args!(
"wrong number of generic arguments supplied: got {args_len}, expected 1"
),
);
return Err(ParseFailed);
}
let ty = args.into_iter().next().unwrap();
let ParsedGenericArgument::Type(ty) = ty else {
parser.errors().error(ty, "expected a type");
return Err(ParseFailed);
};
Ok(Ok(Self {
phantom_data,
lt_token,
ty: Box::new(ty),
gt_token,
}))
}
}
impl From<ParsedTypePhantomData> for Type {
fn from(value: ParsedTypePhantomData) -> Type {
let ParsedTypePhantomData {
phantom_data,
lt_token,
ty,
gt_token,
} = value;
let path = phantom_data.path;
let mut args = Punctuated::new();
args.push(GenericArgument::Type(ty.into()));
let args = AngleBracketedGenericArguments {
colon2_token: Some(Token![::](lt_token.span)),
lt_token,
args,
gt_token,
};
let mut segments = path.segments;
segments.last_mut().unwrap().arguments = PathArguments::AngleBracketed(args);
Type::Path(TypePath {
qself: None,
path: Path {
leading_colon: path.leading_colon,
segments,
},
})
}
}
impl MakeHdlTypeExpr for ParsedTypePhantomData {
fn make_hdl_type_expr(&self, _context: &MakeHdlTypeExprContext) -> Expr {
let ParsedTypePhantomData {
phantom_data,
lt_token: _,
ty: _,
gt_token: _,
} = self;
Expr::Path(ExprPath {
attrs: vec![],
qself: None,
path: phantom_data.path.clone(),
})
}
}
impl ToTokens for ParsedTypePhantomData {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Self {
phantom_data,
lt_token,
ty,
gt_token,
} = self;
phantom_data.to_tokens(tokens);
lt_token.to_tokens(tokens);
ty.to_tokens(tokens);
gt_token.to_tokens(tokens);
}
}
#[derive(Debug, Clone)]
pub(crate) enum ParsedType {
Delimited(ParsedTypeDelimited),
Named(ParsedTypeNamed),
NamedParam(ParsedTypeNamedParam),
Tuple(ParsedTypeTuple),
ConstUsize(ParsedTypeConstUsize),
PhantomData(ParsedTypePhantomData),
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),
PhantomData(ParsedTypePhantomData),
Array(ParsedTypeArray),
UInt(ParsedTypeUInt),
SInt(ParsedTypeSInt),
CanonicalType(known_items::CanonicalType),
DynSize(known_items::DynSize),
}
}
impl From<ParsedType> 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::PhantomData(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<known_items::CanonicalType> for Type {
fn from(value: known_items::CanonicalType) -> Self {
Self::Path(TypePath {
qself: None,
path: value.path,
})
}
}
impl From<known_items::DynSize> for Type {
fn from(value: known_items::DynSize) -> Self {
Self::Path(TypePath {
qself: None,
path: value.path,
})
}
}
impl From<MaybeParsed<ParsedType, Type>> for Type {
fn from(value: MaybeParsed<ParsedType, Type>) -> Self {
match value {
MaybeParsed::Unrecognized(value) => value,
MaybeParsed::Parsed(value) => value.into(),
}
}
}
impl From<Box<ParsedType>> for Type {
fn from(value: Box<ParsedType>) -> 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::PhantomData(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<Path> for ParsedType {
fn parse_types(path: &mut Path, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
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 args.is_some() {
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 ParsedTypePhantomData::try_from_named(named, parser)? {
Ok(v) => return Ok(Self::PhantomData(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<TypePath> for ParsedType {
fn parse_types(ty: &mut TypePath, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
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<Type> for ParsedType {
fn parse_types(ty: &mut Type, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
Ok(match ty {
Type::Array(_) => parse_failed!(
parser,
ty,
"Rust array types are not allowed here, \
use Array<T, N> or ArrayType<T, Len> 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<ParsedConstGenericType> for Type {
fn from(value: ParsedConstGenericType) -> Self {
match value {
ParsedConstGenericType::Usize(v) => parse_quote! { #v },
}
}
}
impl From<MaybeParsed<ParsedConstGenericType, Type>> for Type {
fn from(value: MaybeParsed<ParsedConstGenericType, Type>) -> Self {
match value {
MaybeParsed::Unrecognized(value) => value,
MaybeParsed::Parsed(value) => value.into(),
}
}
}
impl From<Box<ParsedConstGenericType>> for Type {
fn from(value: Box<ParsedConstGenericType>) -> 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<Path> for ParsedConstGenericType {
fn parse_types(path: &mut Path, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
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 args.is_some() {
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<TypePath> for ParsedConstGenericType {
fn parse_types(ty: &mut TypePath, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
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<Type> for ParsedConstGenericType {
fn parse_types(ty: &mut Type, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
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<usize>,
errors: &'a mut Errors,
}
impl<'a> TypesParser<'a> {
pub(crate) fn run_with_errors<T: ParseTypes<I>, I>(
generics: &ParsedGenerics,
input: &mut I,
errors: &mut Errors,
) -> Result<T, ParseFailed> {
TypesParser {
generics,
cur_param_index: None,
errors,
}
.parse(input)
}
pub(crate) fn maybe_run<T: ParseTypes<I>, I, G>(
generics: MaybeParsed<&ParsedGenerics, G>,
mut input: I,
errors: &mut Errors,
) -> MaybeParsed<T, I> {
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<T: ParseTypes<I>, I>(&mut self, input: &mut I) -> Result<T, ParseFailed> {
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<I>: Sized {
fn parse_types(input: &mut I, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed>;
}
impl<T: ParseTypes<I>, I> ParseTypes<Box<I>> for Box<T> {
fn parse_types(input: &mut Box<I>, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
Ok(Box::new(parser.parse(&mut **input)?))
}
}
impl<T: ParseTypes<I>, I, P: Clone> ParseTypes<Punctuated<I, P>> for Punctuated<T, P> {
fn parse_types(
input: &mut Punctuated<I, P>,
parser: &mut TypesParser<'_>,
) -> Result<Self, ParseFailed> {
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<Attribute>,
options: HdlAttr<TypeParamOptions, kw::hdl>,
ident: Ident,
colon_token: Token![:],
bounds: ParsedBounds,
mask_type_bounds: ParsedTypeBounds,
},
Const {
attrs: Vec<Attribute>,
options: HdlAttr<ConstParamOptions, kw::hdl>,
const_token: Token![const],
ident: Ident,
colon_token: Token![:],
ty: ParsedConstGenericType,
bounds: Option<ParsedConstParamWhereBounds>,
},
}
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[0].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<Self, Path> {
if let Some(ident) = path.get_ident() {
if ident == stringify!($known_item) {
return Ok(Self { span: ident.span(), path });
}
}
for &path_segments in Self::PATH_SEGMENTS.iter() {
if path.segments.len() == path_segments.len()
&& path
.segments
.iter()
.zip(path_segments)
.all(|(seg, expected)| {
matches!(seg.arguments, PathArguments::None)
&& seg.ident == *expected
})
{
return Ok(Self { span: path.segments.last().unwrap().ident.span(), path });
}
}
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> {
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<Result<Self, super::ParsedTypeNamed>, 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 {
($(#[alias = $(::$alias:ident)+])* [$(::$seg:ident)+] ::$known_item:ident) => {
impl_known_item_body!($known_item);
impl $known_item {
pub(crate) const PATH_SEGMENTS: &'static [&'static [&'static str]] = &[
&[
$(stringify!($seg),)+
stringify!($known_item),
],
$(&[
$(stringify!($alias),)+
],)*
];
}
};
($(#[alias = $(::$alias:ident)+])* $([$(::$head:ident)*])? ::$next:ident $(::$tail:ident)+) => {
impl_known_item!($(#[alias = $(::$alias)+])* [$($(::$head)*)? ::$next] $(::$tail)+);
};
}
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::BoolOrIntType);
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!(
#[alias = ::std::primitive::usize]
#[alias = ::core::primitive::usize]
::fayalite::__std::primitive::usize
);
impl_known_item!(
#[alias = ::std::marker::PhantomData]
#[alias = ::core::marker::PhantomData]
::fayalite::__std::marker::PhantomData
);
}
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<known_items::$Variant> 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<Self, Path> {
$(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> {
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<known_items::$Variant>,)*
}
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(<Token![+]>::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<Self::Item> {
$(
if let Some(value) = self.0.$Variant.take() {
return Some($enum_type::$Variant(value));
}
)*
None
}
#[allow(unused_mut, unused_variables)]
fn fold<B, F: FnMut(B, Self::Item) -> 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<T: IntoIterator<Item = $enum_type>>(&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<T: IntoIterator<Item = $enum_type>>(iter: T) -> Self {
let mut retval = Self::default();
retval.extend(iter);
retval
}
}
impl Extend<$struct_type> for $struct_type {
fn extend<T: IntoIterator<Item = $struct_type>>(&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<T: IntoIterator<Item = $struct_type>>(iter: T) -> Self {
let mut retval = Self::default();
retval.extend(iter);
retval
}
}
impl Parse for $struct_type {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut retval = Self::default();
while !input.is_empty() {
retval.extend([input.parse::<$enum_type>()?]);
if input.is_empty() {
break;
}
input.parse::<Token![+]>()?;
}
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 {
BoolOrIntType,
BundleType,
EnumType,
IntType,
KnownSize,
Size,
StaticType,
Type,
}
}
impl_bounds! {
#[struct = ParsedTypeBounds]
pub(crate) enum ParsedTypeBound {
BoolOrIntType,
BundleType,
EnumType,
IntType,
StaticType,
Type,
}
}
impl From<ParsedTypeBound> for ParsedBound {
fn from(value: ParsedTypeBound) -> Self {
match value {
ParsedTypeBound::BoolOrIntType(v) => ParsedBound::BoolOrIntType(v),
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<ParsedTypeBounds> for ParsedBounds {
fn from(value: ParsedTypeBounds) -> Self {
let ParsedTypeBounds {
BoolOrIntType,
BundleType,
EnumType,
IntType,
StaticType,
Type,
} = value;
Self {
BoolOrIntType,
BundleType,
EnumType,
IntType,
KnownSize: None,
Size: None,
StaticType,
Type,
}
}
}
impl ParsedTypeBound {
fn implied_bounds(self) -> ParsedTypeBounds {
let span = self.span();
match self {
Self::BoolOrIntType(v) => ParsedTypeBounds::from_iter([
ParsedTypeBound::from(v),
ParsedTypeBound::Type(known_items::Type(span)),
]),
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::BoolOrIntType(known_items::BoolOrIntType(span)),
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<ParsedSizeTypeBound> for ParsedBound {
fn from(value: ParsedSizeTypeBound) -> Self {
match value {
ParsedSizeTypeBound::KnownSize(v) => ParsedBound::KnownSize(v),
ParsedSizeTypeBound::Size(v) => ParsedBound::Size(v),
}
}
}
impl From<ParsedSizeTypeBounds> for ParsedBounds {
fn from(value: ParsedSizeTypeBounds) -> Self {
let ParsedSizeTypeBounds { KnownSize, Size } = value;
Self {
BoolOrIntType: None,
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::BoolOrIntType(v) => ParsedBoundCategory::Type(ParsedTypeBound::BoolOrIntType(v)),
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<Attribute>,
pub(crate) options: HdlAttr<TypeParamOptions, kw::hdl>,
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<Attribute>,
pub(crate) options: HdlAttr<TypeParamOptions, kw::hdl>,
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<Attribute>,
pub(crate) options: HdlAttr<ConstParamOptions, kw::hdl>,
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, Default)]
pub(crate) struct ParsedGenerics {
pub(crate) lt_token: Option<Token![<]>,
pub(crate) params: Punctuated<ParsedGenericParam, Token![,]>,
pub(crate) gt_token: Option<Token![>]>,
pub(crate) param_name_to_index_map: HashMap<Ident, usize>,
}
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<usize>) -> 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 = &param.ident;
parse_quote! { #ident }
}
ParsedGenericParam::SizeType(param) => {
let ident = &param.ident;
parse_quote_spanned! {span=>
<#ident as ::fayalite::int::Size>::SizeType
}
}
ParsedGenericParam::Const(param) => {
let ident = &param.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<Expr> = (0..self.params.len())
.map(|index| {
let mut member = Index::from(index);
member.span = ident.span();
parse_quote_spanned! {ident.span()=>
self.#member
}
})
.collect();
let param_token = Ident::new("__param", ident.span());
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<GenericArgument>| {
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_token
};
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_token, || #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,
) -> <Self as ::fayalite::ty::FillInDefaultedGenerics>::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_token: #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_token
}])
.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_token: #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_token
}])
.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<SizeType = __Param> + #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_token: __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<Self> {
let Generics {
lt_token,
params: input_params,
gt_token,
where_clause,
} = generics;
let mut errors = Errors::new();
let mut predicates: Vec<WherePredicate> = 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<LateParsedParam<'a>> =
Vec::with_capacity(input_params.len());
let mut unparsed_params: Punctuated<UnparsedGenericParam, _> = 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::<LifetimeParamOptions, kw::hdl>::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::<TypeParamOptions, kw::hdl>::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::<ConstParamOptions, kw::hdl>::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<Ident, usize> = 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::<ParsedTypeBounds>(
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::<ParsedSizeTypeBounds>(
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<A_CONST_PARAM>`",
);
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::<ParsedBounds>(
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::BoolOrIntType(_)
| 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<Token![where]> {
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<ParsedGenerics> for Generics {
fn from(value: ParsedGenerics) -> Self {
From::<&ParsedGenerics>::from(&value)
}
}
#[derive(Debug, Copy, Clone)]
pub(crate) enum MaybeParsed<P, U> {
Unrecognized(U),
Parsed(P),
}
impl<P, U> MaybeParsed<P, U> {
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<PF: FnOnce(P) -> PR, UF: FnOnce(U) -> UR, PR, UR>(
self,
pf: PF,
uf: UF,
) -> MaybeParsed<PR, UR> {
match self {
MaybeParsed::Unrecognized(v) => MaybeParsed::Unrecognized(uf(v)),
MaybeParsed::Parsed(v) => MaybeParsed::Parsed(pf(v)),
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct MaybeParsedIter<P, U>(pub(crate) MaybeParsed<P, U>);
impl<P: Iterator, U: Iterator> Iterator for MaybeParsedIter<P, U> {
type Item = MaybeParsed<P::Item, U::Item>;
fn next(&mut self) -> Option<Self::Item> {
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<usize>) {
match &self.0 {
MaybeParsed::Unrecognized(i) => i.size_hint(),
MaybeParsed::Parsed(i) => i.size_hint(),
}
}
}
impl<P: ExactSizeIterator, U: ExactSizeIterator> ExactSizeIterator for MaybeParsedIter<P, U> {}
impl<P: DoubleEndedIterator, U: DoubleEndedIterator> DoubleEndedIterator for MaybeParsedIter<P, U> {
fn next_back(&mut self) -> Option<Self::Item> {
match &mut self.0 {
MaybeParsed::Unrecognized(i) => i.next_back().map(MaybeParsed::Unrecognized),
MaybeParsed::Parsed(i) => i.next_back().map(MaybeParsed::Parsed),
}
}
}
impl<P: IntoIterator, U: IntoIterator> IntoIterator for MaybeParsed<P, U> {
type Item = MaybeParsed<P::Item, U::Item>;
type IntoIter = MaybeParsedIter<P::IntoIter, U::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<P, U> MaybeParsed<P, U> {
#[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<P, U>
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<P, U>
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<MaybeParsed<ParsedGenerics, Generics>> for Generics {
fn from(value: MaybeParsed<ParsedGenerics, Generics>) -> Self {
match value {
MaybeParsed::Unrecognized(value) => value,
MaybeParsed::Parsed(value) => value.into(),
}
}
}
impl From<&'_ MaybeParsed<ParsedGenerics, Generics>> for Generics {
fn from(value: &MaybeParsed<ParsedGenerics, Generics>) -> Self {
match value {
MaybeParsed::Unrecognized(value) => value.clone(),
MaybeParsed::Parsed(value) => value.into(),
}
}
}
impl<P: ToTokens, U: ToTokens> ToTokens for MaybeParsed<P, U> {
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<P: AsTurbofish, U: AsTurbofish> AsTurbofish for MaybeParsed<P, U> {
type Turbofish<'a> = MaybeParsed<P::Turbofish<'a>, 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<P: SplitForImpl, U: SplitForImpl> SplitForImpl for MaybeParsed<P, U> {
type ImplGenerics<'a> = MaybeParsed<P::ImplGenerics<'a>, U::ImplGenerics<'a>>
where
Self: 'a;
type TypeGenerics<'a> = MaybeParsed<P::TypeGenerics<'a>, U::TypeGenerics<'a>>
where
Self: 'a;
type WhereClause<'a> = MaybeParsed<P::WhereClause<'a>, 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<Attribute>,
pub(crate) vis: Visibility,
pub(crate) ident: Option<Ident>,
pub(crate) colon_token: Option<Token![:]>,
pub(crate) ty: ParsedType,
}
impl ParseTypes<Field> for ParsedField {
fn parse_types(input: &mut Field, parser: &mut TypesParser<'_>) -> Result<Self, ParseFailed> {
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<ParsedField> 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<Ident> {
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<ParsedField, Token![,]>,
}
impl ParseTypes<FieldsNamed> for ParsedFieldsNamed {
fn parse_types(
input: &mut FieldsNamed,
parser: &mut TypesParser<'_>,
) -> Result<Self, ParseFailed> {
let FieldsNamed { brace_token, named } = input;
Ok(Self {
brace_token: *brace_token,
named: parser.parse(named)?,
})
}
}
impl From<ParsedFieldsNamed> 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<ParsedFieldsNamed, FieldsNamed> {
pub(crate) fn named(
&self,
) -> MaybeParsed<&Punctuated<ParsedField, Token![,]>, &Punctuated<Field, Token![,]>> {
self.as_ref().map(|v| &v.named, |v| &v.named)
}
}
impl From<MaybeParsed<ParsedFieldsNamed, FieldsNamed>> for FieldsNamed {
fn from(value: MaybeParsed<ParsedFieldsNamed, FieldsNamed>) -> Self {
match value {
MaybeParsed::Unrecognized(value) => value,
MaybeParsed::Parsed(value) => value.into(),
}
}
}
#[derive(Debug)]
pub(crate) struct MakeHdlTypeExprContext {
pub(crate) named_param_values: Vec<Expr>,
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::PhantomData(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) => {
let span = expr.span();
let const_usize = known_items::ConstUsize(span);
parse_quote_spanned! {expr.span()=>
#const_usize::<{ #expr }>
}
}
}
}
}
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(),
})
}
}