| 1 | // Copyright 2022 Damir Jelić |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | #![doc = include_str!("../README.md")] |
| 16 | #![deny( |
| 17 | clippy::mem_forget, |
| 18 | clippy::unwrap_used, |
| 19 | dead_code, |
| 20 | missing_docs, |
| 21 | trivial_casts, |
| 22 | trivial_numeric_casts, |
| 23 | unsafe_code, |
| 24 | unsafe_op_in_unsafe_fn, |
| 25 | unused_extern_crates, |
| 26 | unused_import_braces, |
| 27 | unused_qualifications, |
| 28 | rust_2018_idioms |
| 29 | )] |
| 30 | #![cfg_attr(docsrs, feature(doc_auto_cfg))] |
| 31 | |
| 32 | use proc_macro::TokenStream; |
| 33 | use proc_macro2::TokenStream as TokenStream2; |
| 34 | use proc_macro_crate::{crate_name, FoundCrate}; |
| 35 | use proc_macro_error2::{abort_call_site, proc_macro_error}; |
| 36 | use quote::{format_ident, quote}; |
| 37 | use syn::{ |
| 38 | parse_macro_input, parse_quote, punctuated::Punctuated, token::Comma, Data, DataEnum, |
| 39 | DataStruct, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed, GenericParam, Type, |
| 40 | }; |
| 41 | |
| 42 | fn use_matrix_pickle() -> TokenStream2 { |
| 43 | if let Ok(FoundCrate::Name(name)) = crate_name("matrix-pickle") { |
| 44 | let import = format_ident!("{}", name); |
| 45 | quote! { ::#import } |
| 46 | } else { |
| 47 | quote! { ::matrix_pickle } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | /// Derive an `Encode` implementation for a struct or enum. |
| 52 | #[proc_macro_error] |
| 53 | #[proc_macro_derive(Encode)] |
| 54 | pub fn derive_encode(input: TokenStream) -> TokenStream { |
| 55 | let mut input = parse_macro_input!(input as DeriveInput); |
| 56 | let name = &input.ident; |
| 57 | |
| 58 | let matrix_pickle = use_matrix_pickle(); |
| 59 | |
| 60 | for param in &mut input.generics.params { |
| 61 | if let GenericParam::Type(ref mut type_param) = *param { |
| 62 | type_param.bounds.push(parse_quote!(#matrix_pickle::Encode)); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | let generics = input.generics; |
| 67 | let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); |
| 68 | |
| 69 | match input.data { |
| 70 | Data::Struct(DataStruct { |
| 71 | fields: Fields::Named(FieldsNamed { named, .. }), |
| 72 | .. |
| 73 | }) => { |
| 74 | let idents = named.iter().map(|f| &f.ident); |
| 75 | |
| 76 | quote! { |
| 77 | impl #impl_generics #matrix_pickle::Encode for #name #ty_generics #where_clause { |
| 78 | fn encode(&self, writer: &mut impl std::io::Write) -> Result<usize, #matrix_pickle::EncodeError> { |
| 79 | let mut ret = 0; |
| 80 | |
| 81 | #(ret += self.#idents.encode(writer)?;)* |
| 82 | |
| 83 | Ok(ret) |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | Data::Struct(DataStruct { |
| 89 | fields: Fields::Unnamed(FieldsUnnamed { unnamed, .. }), |
| 90 | .. |
| 91 | }) => { |
| 92 | let i = (0..unnamed.len()).map(syn::Index::from); |
| 93 | |
| 94 | quote! { |
| 95 | impl #impl_generics #matrix_pickle::Encode for #name #ty_generics #where_clause { |
| 96 | fn encode(&self, writer: &mut impl std::io::Write) -> Result<usize, #matrix_pickle::EncodeError> { |
| 97 | let mut ret = 0; |
| 98 | |
| 99 | #(ret += self.#i.encode(writer)?;)* |
| 100 | |
| 101 | Ok(ret) |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | Data::Enum(DataEnum { variants, .. }) => { |
| 107 | let names = variants.iter().map(|v| &v.ident); |
| 108 | let numbers = 0u8..variants.len().try_into().expect("Only enums with up to 256 elements are supported"); |
| 109 | |
| 110 | quote! { |
| 111 | impl #impl_generics #matrix_pickle::Encode for #name #ty_generics #where_clause { |
| 112 | fn encode(&self, writer: &mut impl std::io::Write) -> Result<usize, #matrix_pickle::EncodeError> { |
| 113 | let mut ret = 0; |
| 114 | |
| 115 | match self { |
| 116 | #(#name::#names(v) => { |
| 117 | ret += #numbers.encode(writer)?; |
| 118 | ret += v.encode(writer)?; |
| 119 | }),* |
| 120 | } |
| 121 | |
| 122 | Ok(ret) |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | _ => abort_call_site!("`#[derive(Encode)` only supports non-tuple structs"), |
| 129 | }.into() |
| 130 | } |
| 131 | |
| 132 | fn check_if_boxed(fields: &Punctuated<Field, Comma>) { |
| 133 | for field in fields { |
| 134 | for attribute in &field.attrs { |
| 135 | if attribute.path().is_ident("secret") { |
| 136 | match &field.ty { |
| 137 | Type::Array(_) => abort_call_site!( |
| 138 | "Arrays need to be boxed to avoid unintended copies of the secret" |
| 139 | ), |
| 140 | Type::Path(_) => {} |
| 141 | _ => { |
| 142 | abort_call_site!("Type {} does not support being decoded as a secret value") |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /// Derive an `Decode` implementation for a struct or enum. |
| 151 | #[proc_macro_error] |
| 152 | #[proc_macro_derive(Decode, attributes(secret))] |
| 153 | pub fn derive_decode(input: TokenStream) -> TokenStream { |
| 154 | let mut input = parse_macro_input!(input as DeriveInput); |
| 155 | let name = &input.ident; |
| 156 | |
| 157 | let matrix_pickle = use_matrix_pickle(); |
| 158 | |
| 159 | for param in &mut input.generics.params { |
| 160 | if let GenericParam::Type(ref mut type_param) = *param { |
| 161 | type_param.bounds.push(parse_quote!(#matrix_pickle::Encode)); |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | let generics = input.generics; |
| 166 | let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); |
| 167 | |
| 168 | match input.data { |
| 169 | Data::Struct(DataStruct { |
| 170 | fields: Fields::Named(FieldsNamed { named, .. }), |
| 171 | .. |
| 172 | }) => { |
| 173 | check_if_boxed(&named); |
| 174 | |
| 175 | let names = named.iter().map(|f| &f.ident); |
| 176 | let field_types = named.iter().map(|f| &f.ty); |
| 177 | |
| 178 | quote! { |
| 179 | impl #impl_generics #matrix_pickle::Decode for #name #ty_generics #where_clause { |
| 180 | fn decode(reader: &mut impl std::io::Read) -> Result<Self, #matrix_pickle::DecodeError> { |
| 181 | Ok(Self { |
| 182 | #(#names: <#field_types>::decode(reader)?),* |
| 183 | }) |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | Data::Struct(DataStruct { |
| 189 | fields: Fields::Unnamed(FieldsUnnamed { unnamed, .. }), |
| 190 | .. |
| 191 | }) => { |
| 192 | check_if_boxed(&unnamed); |
| 193 | |
| 194 | let field_types = unnamed.iter().map(|f| &f.ty); |
| 195 | |
| 196 | quote! { |
| 197 | impl #impl_generics #matrix_pickle::Decode for #name #ty_generics #where_clause { |
| 198 | fn decode(reader: &mut impl std::io::Read) -> Result<Self, #matrix_pickle::DecodeError> { |
| 199 | Ok(Self ( |
| 200 | #(<#field_types>::decode(reader)?),* |
| 201 | )) |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | Data::Enum(DataEnum { variants, .. }) => { |
| 207 | let names = variants.iter().map(|v| &v.ident); |
| 208 | let numbers = 0u8..variants.len().try_into().expect("Only enums with up to 256 elements are supported"); |
| 209 | |
| 210 | quote! { |
| 211 | impl #impl_generics #matrix_pickle::Decode for #name #ty_generics #where_clause { |
| 212 | fn decode(reader: &mut impl std::io::Read) -> Result<Self, #matrix_pickle::DecodeError> { |
| 213 | let variant = u8::decode(reader)?; |
| 214 | |
| 215 | match variant { |
| 216 | #(#numbers => { |
| 217 | let x = Decode::decode(reader)?; |
| 218 | Ok(Self::#names(x)) |
| 219 | }),* |
| 220 | |
| 221 | _ => Err(#matrix_pickle::DecodeError::UnknownEnumVariant(variant)) |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | _ => abort_call_site!("`#[derive(Encode)` only supports non-tuple structs"), |
| 228 | }.into() |
| 229 | } |