1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
//! This crate provides the [`derive@named_array`] derive macro, which allows you to access fields of a
//! struct as if they were elements of an array.
//! This provides an impl's of [`Index`] and [`IndexMut`], which translates from a `usize` index to the fields, in the
//! order in which they appear.
//!
//! The type of all the fields must be the same, and written identically.
//! For example, if one field is `Option<()>`, and another is `core::option::Option<()>`, the code
//! will be rejected.
//! This is because type information does not exist at the time of macro expansion, so there is no
//! way to confirm that the two refer to the same type.
//!
//! Indexing will panic if the index is out of bounds.
//!
//! # Example
//! ```rust
//! # use named_array::named_array;
//! #[derive(named_array)]
//! struct Example {
//! a: u32,
//! b: u32,
//! c: u32,
//! }
//!
//! # fn main() {
//! let example = Example { a: 1, b: 2, c: 3 };
//! assert_eq!(example[0], example.a);
//! assert_eq!(example[1], example.b);
//! assert_eq!(example[2], example.c);
//! # }
//! ```
//!
//! # Tuple structs
//!
//! This can be used with tuple structs as well.
//! However, you may be better off using `struct Foo([u32; 3])` instead of `struct Foo(u32, u32, u32)`.
//!
//! ```rust
//! # use named_array::named_array;
//! #[derive(named_array)]
//! struct Example(u32, u32, u32);
//! # fn main() {
//! let example = Example(1, 2, 3);
//! assert_eq!(example[0], example.0);
//! assert_eq!(example[1], example.1);
//! assert_eq!(example[2], example.2);
//! # }
//! ```
//!
//! [`Index`]: ::core::ops::Index
//! [`IndexMut`]: ::core::ops::IndexMut
use quote::quote;
/// See the [crate] level documentation.
#[proc_macro_derive(named_array)]
pub fn named_array(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let source: syn::ItemStruct = syn::parse(input).expect("Expected struct definition");
match &source.fields {
syn::Fields::Named(_) => make_named(source),
syn::Fields::Unnamed(_) => make_unnamed(source),
_ => panic!("unit structs are not supported"),
}
}
fn make_named(source: syn::ItemStruct) -> proc_macro::TokenStream {
let mut fields = match source.fields {
syn::Fields::Named(ref f) => f.named.iter(),
_ => unreachable!("Only call this function for structs with named fields"),
};
let mut errs = Vec::new();
let mut names = Vec::new();
let ty = fields
.next()
.map(|f| {
names.push(f.ident.as_ref().unwrap());
&f.ty
})
.expect("Expected at least one field");
for f in fields {
if f.ty != *ty {
errs.push(syn::Error::new_spanned(
&f.ty,
"All fields must have the same type",
));
}
names.push(f.ident.as_ref().unwrap());
}
let struct_name = source.ident;
if !errs.is_empty() {
let errs = errs.into_iter().map(|e| e.to_compile_error());
// If there are any errors, return a dummy impl to avoid a flood of errors where indexing
// gets used.
return quote! {
#(#errs)*
impl ::core::ops::Index<usize> for #struct_name {
type Output = #ty;
fn index(&self, _: usize) -> &Self::Output {
unimplemented!("Unable to generate code due to previous errors");
}
}
impl ::core::ops::IndexMut<usize> for #struct_name {
fn index_mut(&mut self, _: usize) -> &mut Self::Output {
unimplemented!("Unable to generate code due to previous errors");
}
}
}
.into();
}
let len = names.len();
let panic_msg = format!("index out of bounds: the len is {len} but the index is {{}}");
let range1 = 0usize..;
let range2 = 0usize..;
quote! {
impl ::core::ops::Index<usize> for #struct_name {
type Output = #ty;
fn index(&self, index: usize) -> &Self::Output {
match index {
#(
#range1 => &self.#names,
)*
i => panic!(#panic_msg, i),
}
}
}
impl ::core::ops::IndexMut<usize> for #struct_name {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
match index {
#(
#range2 => &mut self.#names,
)*
i => panic!(#panic_msg, i),
}
}
}
}
.into()
}
fn make_unnamed(source: syn::ItemStruct) -> proc_macro::TokenStream {
let mut fields = match source.fields {
syn::Fields::Unnamed(ref f) => f.unnamed.iter(),
_ => unreachable!("Only call this function for structs with named fields"),
};
let len = fields.len();
let mut errs = Vec::new();
let ty = fields
.next()
.map(|f| &f.ty)
.expect("Expected at least one field");
for f in fields {
if f.ty != *ty {
errs.push(syn::Error::new_spanned(
&f.ty,
"All fields must have the same type",
));
}
}
let struct_name = source.ident;
if !errs.is_empty() {
let errs = errs.into_iter().map(|e| e.to_compile_error());
// If there are any errors, return a dummy impl to avoid a flood of errors where indexing
// gets used.
return quote! {
#(#errs)*
impl ::core::ops::Index<usize> for #struct_name {
type Output = #ty;
fn index(&self, _: usize) -> &Self::Output {
unimplemented!("Unable to generate code due to previous errors");
}
}
impl ::core::ops::IndexMut<usize> for #struct_name {
fn index_mut(&mut self, _: usize) -> &mut Self::Output {
unimplemented!("Unable to generate code due to previous errors");
}
}
}
.into();
}
let panic_msg = format!("index out of bounds: the len is {len} but the index is {{}}");
let range1 = 0usize..len;
let range2 = 0usize..len;
let index1 = (0usize..len).map(syn::Index::from);
let index2 = (0usize..len).map(syn::Index::from);
quote! {
impl ::core::ops::Index<usize> for #struct_name {
type Output = #ty;
fn index(&self, index: usize) -> &Self::Output {
match index {
#( #range1 => &self.#index1, )*
i => panic!(#panic_msg, i),
}
}
}
impl ::core::ops::IndexMut<usize> for #struct_name {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
match index {
#( #range2 => &mut self.#index2, )*
i => panic!(#panic_msg, i),
}
}
}
}
.into()
}