palette_derive-0.7.6/.cargo_vcs_info.json0000644000000001540000000000100140420ustar { "git": { "sha1": "bd08f746ac61006c2448e73d855d885dae233960" }, "path_in_vcs": "palette_derive" }palette_derive-0.7.6/Cargo.toml0000644000000024630000000000100120450ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.60.0" name = "palette_derive" version = "0.7.6" authors = ["Erik Hedvall "] exclude = [] description = "Automatically implement traits from the palette crate." documentation = "https://docs.rs/palette/0.7.6/palette/" readme = "README.md" keywords = [ "palette", "derive", "macros", ] license = "MIT OR Apache-2.0" repository = "https://github.com/Ogeon/palette" resolver = "2" [lib] bench = false proc-macro = true [dependencies.by_address] version = "1.2.1" [dependencies.find-crate] version = "0.6" optional = true [dependencies.proc-macro2] version = "^1.0" [dependencies.quote] version = "^1.0" [dependencies.syn] version = "2.0.13" features = [ "derive", "parsing", "printing", "clone-impls", "extra-traits", "proc-macro", ] default-features = false palette_derive-0.7.6/Cargo.toml.orig000064400000000000000000000014371046102023000155260ustar 00000000000000[package] name = "palette_derive" version = "0.7.6" #automatically updated authors = ["Erik Hedvall "] exclude = [] description = "Automatically implement traits from the palette crate." documentation = "https://docs.rs/palette/0.7.6/palette/" repository = "https://github.com/Ogeon/palette" readme = "README.md" keywords = ["palette", "derive", "macros"] license = "MIT OR Apache-2.0" edition = "2018" resolver = "2" rust-version = "1.60.0" [lib] proc-macro = true bench = false [dependencies] syn = { version = "2.0.13", default-features = false, features = [ "derive", "parsing", "printing", "clone-impls", "extra-traits", "proc-macro", ] } quote = "^1.0" proc-macro2 = "^1.0" by_address = "1.2.1" find-crate = { version = "0.6", optional = true } palette_derive-0.7.6/LICENSE-APACHE000064400000000000000000000251371046102023000145660ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. palette_derive-0.7.6/LICENSE-MIT000064400000000000000000000020701046102023000142650ustar 00000000000000The MIT License (MIT) Copyright (c) 2015 Erik Hedvall Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. palette_derive-0.7.6/README.md000064400000000000000000000017021046102023000141110ustar 00000000000000# palette_derive Contains derive macros for the [`palette`](https://crates.io/crates/palette/) crate. They are all reexported through `palette` and require it to be a dependency, so there is typically no reason to use this crate directly. ## Minimum Supported Rust Version (MSRV) This version of Palette has been automatically tested with Rust version `1.60.0` and the `stable`, `beta`, and `nightly` channels. Future versions of the library may advance the minimum supported version to make use of new language features, but this will normally be considered a breaking change. Exceptions may be made for security patches, dependencies advancing their MSRV in minor or patch releases, and similar changes. ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or ) * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. palette_derive-0.7.6/src/alpha/mod.rs000064400000000000000000000001101046102023000156230ustar 00000000000000pub use self::with_alpha::derive as derive_with_alpha; mod with_alpha; palette_derive-0.7.6/src/alpha/with_alpha.rs000064400000000000000000000104211046102023000171720ustar 00000000000000use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use syn::{parse_quote, DeriveInput, Generics, Ident, Type}; use crate::{ meta::{ parse_field_attributes, parse_namespaced_attributes, FieldAttributes, IdentOrIndex, TypeItemAttributes, }, util, }; pub fn derive(item: TokenStream) -> ::std::result::Result> { let DeriveInput { ident, generics: original_generics, data, attrs, .. } = syn::parse(item).map_err(|error| vec![error])?; let generics = original_generics; let (item_meta, item_errors) = parse_namespaced_attributes::(attrs); let (fields_meta, field_errors) = if let syn::Data::Struct(struct_data) = data { parse_field_attributes::(struct_data.fields) } else { return Err(vec![syn::Error::new( Span::call_site(), "only structs are supported", )]); }; let implementation = if let Some((alpha_property, alpha_type)) = fields_meta.alpha_property { implement_for_internal_alpha(&ident, &generics, &alpha_property, &alpha_type, &item_meta) } else { implement_for_external_alpha(&ident, &generics, &item_meta) }; let item_errors = item_errors .into_iter() .map(|error| error.into_compile_error()); let field_errors = field_errors .into_iter() .map(|error| error.into_compile_error()); Ok(quote! { #(#item_errors)* #(#field_errors)* #implementation } .into()) } fn implement_for_internal_alpha( ident: &Ident, generics: &Generics, alpha_property: &IdentOrIndex, alpha_type: &Type, item_meta: &TypeItemAttributes, ) -> TokenStream2 { let with_alpha_trait_path = util::path(["WithAlpha"], item_meta.internal); let stimulus_trait_path = util::path(["stimulus", "Stimulus"], item_meta.internal); let (impl_generics, type_generics, where_clause) = generics.split_for_impl(); quote! { #[automatically_derived] impl #impl_generics #with_alpha_trait_path<#alpha_type> for #ident #type_generics #where_clause { type Color = Self; type WithAlpha = Self; fn with_alpha(mut self, alpha: #alpha_type) -> Self::WithAlpha { self.#alpha_property = alpha; self } fn without_alpha(mut self) -> Self::Color { self.#alpha_property = #stimulus_trait_path::max_intensity(); self } fn split(mut self) -> (Self::Color, #alpha_type) { let opaque_alpha = #stimulus_trait_path::max_intensity(); let alpha = core::mem::replace(&mut self.#alpha_property, opaque_alpha); (self, alpha) } } } } fn implement_for_external_alpha( ident: &Ident, generics: &Generics, item_meta: &TypeItemAttributes, ) -> TokenStream2 { let with_alpha_trait_path = util::path(["WithAlpha"], item_meta.internal); let stimulus_trait_path = util::path(["stimulus", "Stimulus"], item_meta.internal); let alpha_path = util::path(["Alpha"], item_meta.internal); let (_, type_generics, _) = generics.split_for_impl(); let alpha_type: Type = parse_quote!(_A); let mut impl_generics = generics.clone(); impl_generics.params.push(parse_quote!(_A)); impl_generics .make_where_clause() .predicates .push(parse_quote!(_A: #stimulus_trait_path)); let (impl_generics, _, where_clause) = impl_generics.split_for_impl(); quote! { #[automatically_derived] impl #impl_generics #with_alpha_trait_path<#alpha_type> for #ident #type_generics #where_clause { type Color = Self; type WithAlpha = #alpha_path; fn with_alpha(self, alpha: #alpha_type) -> Self::WithAlpha { #alpha_path { color: self, alpha } } fn without_alpha(self) -> Self::Color { self } fn split(self) -> (Self::Color, #alpha_type) { (self, #stimulus_trait_path::max_intensity()) } } } } palette_derive-0.7.6/src/cast/array_cast.rs000064400000000000000000000126261046102023000170600ustar 00000000000000use proc_macro::TokenStream; use proc_macro2::Span; use quote::{quote, ToTokens}; use syn::{ punctuated::Punctuated, token::Comma, Attribute, Data, DeriveInput, Fields, Meta, Path, Type, }; use crate::meta::{self, FieldAttributes, IdentOrIndex, TypeItemAttributes}; use crate::util; pub fn derive(tokens: TokenStream) -> std::result::Result> { let DeriveInput { ident, attrs, generics, data, .. } = syn::parse(tokens).map_err(|error| vec![error])?; let allowed_repr = is_allowed_repr(&attrs)?; let (item_meta, item_errors) = meta::parse_namespaced_attributes::(attrs); let mut number_of_channels = 0usize; let mut field_type: Option = None; let (all_fields, fields_meta, field_errors) = match data { Data::Struct(struct_item) => { let (fields_meta, field_errors) = meta::parse_field_attributes::(struct_item.fields.clone()); let all_fields = match struct_item.fields { Fields::Named(fields) => fields.named, Fields::Unnamed(fields) => fields.unnamed, Fields::Unit => Default::default(), }; (all_fields, fields_meta, field_errors) } Data::Enum(_) => { return Err(vec![syn::Error::new( Span::call_site(), "`ArrayCast` cannot be derived for enums, because of the discriminant", )]); } Data::Union(_) => { return Err(vec![syn::Error::new( Span::call_site(), "`ArrayCast` cannot be derived for unions", )]); } }; let fields = all_fields .into_iter() .enumerate() .map(|(index, field)| { ( field .ident .map(IdentOrIndex::Ident) .unwrap_or_else(|| IdentOrIndex::Index(index.into())), field.ty, ) }) .filter(|(field, _)| !fields_meta.zero_size_fields.contains(field)); let mut errors = Vec::new(); for (field, ty) in fields { let ty = fields_meta .type_substitutes .get(&field) .cloned() .unwrap_or(ty); number_of_channels += 1; if let Some(field_type) = field_type.clone() { if field_type != ty { errors.push(syn::Error::new_spanned( &field, format!( "expected fields to have type `{}`", field_type.into_token_stream() ), )); } } else { field_type = Some(ty); } } if !allowed_repr { errors.push(syn::Error::new( Span::call_site(), format!( "a `#[repr(C)]` or `#[repr(transparent)]` attribute is required to give `{}` a fixed memory layout", ident ), )); } let array_cast_trait_path = util::path(["cast", "ArrayCast"], item_meta.internal); let mut implementation = if let Some(field_type) = field_type { let (impl_generics, type_generics, where_clause) = generics.split_for_impl(); quote! { #[automatically_derived] unsafe impl #impl_generics #array_cast_trait_path for #ident #type_generics #where_clause { type Array = [#field_type; #number_of_channels]; } } } else { errors.push(syn::Error::new( Span::call_site(), "`ArrayCast` can only be derived for structs with one or more fields".to_string(), )); return Err(errors); }; implementation.extend(errors.iter().map(syn::Error::to_compile_error)); let item_errors = item_errors .into_iter() .map(|error| error.into_compile_error()); let field_errors = field_errors .into_iter() .map(|error| error.into_compile_error()); Ok(quote! { #(#item_errors)* #(#field_errors)* #implementation } .into()) } fn is_allowed_repr(attributes: &[Attribute]) -> std::result::Result> { let mut errors = Vec::new(); for attribute in attributes { let attribute_name = attribute.path().get_ident().map(ToString::to_string); if let Some("repr") = attribute_name.as_deref() { let meta_list = match attribute.meta.require_list() { Ok(list) => list, Err(error) => { errors.push(error); continue; } }; let items = match meta_list.parse_args_with(Punctuated::::parse_terminated) { Ok(items) => items, Err(error) => { errors.push(error); continue; } }; let contains_allowed_repr = items.iter().any(|item| { item.require_path_only() .ok() .and_then(Path::get_ident) .map_or(false, |ident| ident == "C" || ident == "transparent") }); if contains_allowed_repr { return Ok(true); } } } if errors.is_empty() { Ok(false) } else { Err(errors) } } palette_derive-0.7.6/src/cast/mod.rs000064400000000000000000000001101046102023000154700ustar 00000000000000pub use self::array_cast::derive as derive_array_cast; mod array_cast; palette_derive-0.7.6/src/color_types.rs000064400000000000000000000476701046102023000163470ustar 00000000000000use proc_macro2::{Span, TokenStream}; use syn::{parse_quote, GenericParam, Generics, Ident, Type}; use crate::{ convert::util::{InputUser, UsedInput, WhitePointSource}, meta::TypeItemAttributes, util, }; pub(crate) struct ColorGroup { pub(crate) root_type: ColorInfo, pub(crate) colors: &'static [ColorType], } impl ColorGroup { pub(crate) fn check_availability(&self, name: &str) -> Result<(), ColorError> { if name == self.root_type.name { return Ok(()); } for color in self.colors { if name != color.info.name { continue; } return Ok(()); } Err(ColorError::UnknownColor) } pub(crate) fn color_names(&'static self) -> ColorNames { ColorNames { root_type: Some(&self.root_type), colors: self.colors.iter(), } } pub(crate) fn find_type_by_name(&self, name: &str) -> Option<&ColorType> { self.colors.iter().find(|color| color.info.name == name) } pub(crate) fn find_by_name(&self, name: &str) -> Option<&ColorInfo> { if self.root_type.name == name { Some(&self.root_type) } else { self.find_type_by_name(name).map(|ty| &ty.info) } } } pub(crate) struct ColorType { pub(crate) info: ColorInfo, pub(crate) infer_group: bool, pub(crate) preferred_source: &'static str, } type MetaTypeGeneratorFn = fn( self_color: &ColorInfo, meta_type_source: MetaTypeSource, white_point: &Type, used_input: &mut UsedInput, user: InputUser, meta: &TypeItemAttributes, ) -> syn::Result; pub(crate) struct ColorInfo { pub(crate) name: &'static str, pub(crate) module: Option<&'static str>, pub(crate) default_white_point: InternalExternal>, pub(crate) get_meta_type: Option, } impl ColorInfo { pub(crate) fn get_path(&self, internal: bool) -> TokenStream { if let Some(module) = self.module { util::path([module, self.name], internal) } else { util::path([self.name], internal) } } pub(crate) fn get_type( &self, meta_type_source: MetaTypeSource, component: &Type, white_point: &Type, used_input: &mut UsedInput, user: InputUser, meta: &TypeItemAttributes, ) -> syn::Result { let meta_type: Option = self .get_meta_type .map(|get| get(self, meta_type_source, white_point, used_input, user, meta)) .transpose()?; let color_path = self.get_path(meta.internal); if let Some(meta_type) = meta_type { Ok(parse_quote!(#color_path::<#meta_type, #component>)) } else { Ok(parse_quote!(#color_path::<#component>)) } } pub(crate) fn get_default_white_point(&self, internal: bool) -> (Type, WhitePointSource) { let path = if internal { self.default_white_point.internal } else { self.default_white_point.external }; path.map(|path| { ( util::path_type(path, internal), WhitePointSource::ConcreteType, ) }) .unwrap_or_else(|| (parse_quote!(_Wp), WhitePointSource::GeneratedGeneric)) } } pub(crate) struct InternalExternal { pub(crate) internal: T, pub(crate) external: T, } pub(crate) struct ColorNames { root_type: Option<&'static ColorInfo>, colors: std::slice::Iter<'static, ColorType>, } impl Iterator for ColorNames { type Item = &'static ColorInfo; fn next(&mut self) -> Option { if let Some(root_type) = self.root_type.take() { return Some(root_type); } self.colors.next().map(|color| &color.info) } } /// These are the disjoint networks of possible conversions. It's possible to /// convert directly to and from each color within each group, while converting /// between the groups requires additional runtime data. pub(crate) static COLOR_GROUPS: &[&ColorGroup] = &[ &XYZ_COLORS, &CAM16_JCH_COLORS, &CAM16_JMH_COLORS, &CAM16_JSH_COLORS, &CAM16_QCH_COLORS, &CAM16_QMH_COLORS, &CAM16_QSH_COLORS, ]; // The XYZ color group is where most colors should be. All of these have some // connection to `Xyz`. pub(crate) static XYZ_COLORS: ColorGroup = ColorGroup { root_type: ColorInfo { name: "Xyz", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_white_point), }, colors: &[ ColorType { info: ColorInfo { name: "Rgb", module: Some("rgb"), default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_rgb_standard), }, infer_group: true, preferred_source: "Xyz", }, ColorType { info: ColorInfo { name: "Luma", module: Some("luma"), default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_luma_standard), }, infer_group: true, preferred_source: "Xyz", }, ColorType { info: ColorInfo { name: "Hsl", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_rgb_standard), }, infer_group: true, preferred_source: "Rgb", }, ColorType { info: ColorInfo { name: "Hsluv", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_white_point), }, infer_group: true, preferred_source: "Lchuv", }, ColorType { info: ColorInfo { name: "Hsv", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_rgb_standard), }, infer_group: true, preferred_source: "Rgb", }, ColorType { info: ColorInfo { name: "Hwb", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_rgb_standard), }, infer_group: true, preferred_source: "Hsv", }, ColorType { info: ColorInfo { name: "Lab", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_white_point), }, infer_group: true, preferred_source: "Xyz", }, ColorType { info: ColorInfo { name: "Lch", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_white_point), }, infer_group: true, preferred_source: "Lab", }, ColorType { info: ColorInfo { name: "Lchuv", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_white_point), }, infer_group: true, preferred_source: "Luv", }, ColorType { info: ColorInfo { name: "Luv", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_white_point), }, infer_group: true, preferred_source: "Xyz", }, ColorType { info: ColorInfo { name: "Oklab", module: None, default_white_point: InternalExternal { internal: Some(&["white_point", "D65"]), external: Some(&["white_point", "D65"]), }, get_meta_type: None, }, infer_group: true, preferred_source: "Xyz", }, ColorType { info: ColorInfo { name: "Oklch", module: None, default_white_point: InternalExternal { internal: Some(&["white_point", "D65"]), external: Some(&["white_point", "D65"]), }, get_meta_type: None, }, infer_group: true, preferred_source: "Oklab", }, ColorType { info: ColorInfo { name: "Okhsl", module: None, default_white_point: InternalExternal { internal: Some(&["white_point", "D65"]), external: Some(&["white_point", "D65"]), }, get_meta_type: None, }, infer_group: true, preferred_source: "Oklab", }, ColorType { info: ColorInfo { name: "Okhsv", module: None, default_white_point: InternalExternal { internal: Some(&["white_point", "D65"]), external: Some(&["white_point", "D65"]), }, get_meta_type: None, }, infer_group: true, preferred_source: "Oklab", }, ColorType { info: ColorInfo { name: "Okhwb", module: None, default_white_point: InternalExternal { internal: Some(&["white_point", "D65"]), external: Some(&["white_point", "D65"]), }, get_meta_type: None, }, infer_group: true, preferred_source: "Okhsv", }, ColorType { info: ColorInfo { name: "Yxy", module: None, default_white_point: InternalExternal { internal: None, external: Some(&["white_point", "D65"]), }, get_meta_type: Some(get_white_point), }, infer_group: true, preferred_source: "Xyz", }, ], }; // The CAM16 groups are a bit special, since they require information about the // viewing conditions to convert between each other. static CAM16_JCH_COLORS: ColorGroup = ColorGroup { root_type: ColorInfo { name: "Cam16Jch", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, colors: &[ColorType { info: ColorInfo { name: "Cam16", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, infer_group: false, // For generating connections only from `Cam16`, but not to it preferred_source: "Cam16Jch", }], }; static CAM16_JMH_COLORS: ColorGroup = ColorGroup { root_type: ColorInfo { name: "Cam16Jmh", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, colors: &[ ColorType { info: ColorInfo { name: "Cam16", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, infer_group: false, // For generating connections only from `Cam16`, but not to it preferred_source: "Cam16Jmh", }, // CAM16 UCS ColorType { info: ColorInfo { name: "Cam16UcsJmh", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, infer_group: true, preferred_source: "Cam16Jmh", }, ColorType { info: ColorInfo { name: "Cam16UcsJab", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, infer_group: true, preferred_source: "Cam16UcsJmh", }, ], }; static CAM16_JSH_COLORS: ColorGroup = ColorGroup { root_type: ColorInfo { name: "Cam16Jsh", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, colors: &[ColorType { info: ColorInfo { name: "Cam16", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, infer_group: false, // For generating connections only from `Cam16`, but not to it preferred_source: "Cam16Jsh", }], }; static CAM16_QCH_COLORS: ColorGroup = ColorGroup { root_type: ColorInfo { name: "Cam16Qch", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, colors: &[ColorType { info: ColorInfo { name: "Cam16", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, infer_group: false, // For generating connections only from `Cam16`, but not to it preferred_source: "Cam16Qch", }], }; static CAM16_QMH_COLORS: ColorGroup = ColorGroup { root_type: ColorInfo { name: "Cam16Qmh", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, colors: &[ColorType { info: ColorInfo { name: "Cam16", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, infer_group: false, // For generating connections only from `Cam16`, but not to it preferred_source: "Cam16Qmh", }], }; static CAM16_QSH_COLORS: ColorGroup = ColorGroup { root_type: ColorInfo { name: "Cam16Qsh", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, colors: &[ColorType { info: ColorInfo { name: "Cam16", module: Some("cam16"), default_white_point: InternalExternal { internal: None, external: None, }, get_meta_type: None, }, infer_group: false, // For generating connections only from `Cam16`, but not to it preferred_source: "Cam16Qsh", }], }; pub(crate) enum ColorError { UnknownColor, } fn get_rgb_standard( self_color: &ColorInfo, meta_type_source: MetaTypeSource, white_point: &Type, used_input: &mut UsedInput, user: InputUser, meta: &TypeItemAttributes, ) -> syn::Result { if let Some(rgb_standard) = &meta.rgb_standard { Ok(rgb_standard.clone()) } else { match meta_type_source { MetaTypeSource::Generics(generics) => { used_input.white_point.set_used(user); let rgb_standard_path = util::path(["rgb", "RgbStandard"], meta.internal); let rgb_space_path = util::path(["rgb", "RgbSpace"], meta.internal); generics.params.push(GenericParam::Type( Ident::new("_S", Span::call_site()).into(), )); let where_clause = generics.make_where_clause(); where_clause .predicates .push(parse_quote!(_S: #rgb_standard_path)); where_clause .predicates .push(parse_quote!(_S::Space: #rgb_space_path)); Ok(parse_quote!(_S)) } MetaTypeSource::OtherColor(other_color) => { match other_color.name { "Rgb" | "Hsl" | "Hsv" | "Hwb" => Ok(parse_quote!(_S)), _ => Err(syn::parse::Error::new( Span::call_site(), format!( "could not determine which RGB standard to use when converting to and from `{}` via `{}`", other_color.name, self_color.name ), )), } } } } } fn get_luma_standard( _self_color: &ColorInfo, meta_type_source: MetaTypeSource, white_point: &Type, used_input: &mut UsedInput, user: InputUser, meta: &TypeItemAttributes, ) -> syn::Result { if let Some(luma_standard) = meta.luma_standard.as_ref() { return Ok(luma_standard.clone()); } used_input.white_point.set_used(user); match meta_type_source { MetaTypeSource::Generics(generics) => { let luma_standard_path = util::path(["luma", "LumaStandard"], meta.internal); generics.params.push(GenericParam::Type( Ident::new("_S", Span::call_site()).into(), )); generics .make_where_clause() .predicates .push(parse_quote!(_S: #luma_standard_path)); Ok(parse_quote!(_S)) } MetaTypeSource::OtherColor(_) => { let linear_path = util::path(["encoding", "Linear"], meta.internal); Ok(parse_quote!(#linear_path<#white_point>)) } } } fn get_white_point( _self_color: &ColorInfo, _meta_type_source: MetaTypeSource, white_point: &Type, used_input: &mut UsedInput, user: InputUser, _meta: &TypeItemAttributes, ) -> syn::Result { used_input.white_point.set_used(user); Ok(white_point.clone()) } pub(crate) enum MetaTypeSource<'a> { OtherColor(&'a ColorInfo), Generics(&'a mut Generics), } palette_derive-0.7.6/src/convert/from_color_unclamped.rs000064400000000000000000000276421046102023000216530ustar 00000000000000use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use syn::{parse_quote, DeriveInput, Generics, Ident, Result, Type}; use crate::{ color_types::{ColorInfo, MetaTypeSource, XYZ_COLORS}, convert::util::{InputUser, WhitePointSource}, meta::{ parse_field_attributes, parse_namespaced_attributes, FieldAttributes, IdentOrIndex, TypeItemAttributes, }, util, }; use super::util::{component_type, find_nearest_color, get_convert_color_type, white_point_type}; pub fn derive(item: TokenStream) -> ::std::result::Result> { let DeriveInput { ident, generics, data, attrs, .. } = syn::parse(item).map_err(|error| vec![error])?; let (mut item_meta, item_errors) = parse_namespaced_attributes::(attrs); let (fields_meta, field_errors) = if let syn::Data::Struct(struct_data) = data { parse_field_attributes::(struct_data.fields) } else { return Err(vec![syn::Error::new( Span::call_site(), "only structs are supported", )]); }; let component = component_type(item_meta.component.clone()); let white_point = white_point_type( item_meta.white_point.as_ref(), item_meta.rgb_standard.as_ref(), item_meta.luma_standard.as_ref(), item_meta.internal, ); let alpha_field = fields_meta.alpha_property; // Assume conversion from the root type (Xyz for the base group) by default if item_meta.color_groups.is_empty() { item_meta.color_groups.insert((&XYZ_COLORS).into()); } if item_meta.skip_derives.is_empty() { for group in &item_meta.color_groups { item_meta.skip_derives.insert(group.root_type.name.into()); } } let (all_from_impl_params, impl_params_errors) = prepare_from_impl(&component, white_point, &item_meta, &generics); let mut implementations = generate_from_implementations(&ident, &generics, &item_meta, &all_from_impl_params); if let Some((alpha_property, alpha_type)) = alpha_field { implementations.push(generate_from_alpha_implementation_with_internal( &ident, &generics, &item_meta, &alpha_property, &alpha_type, )); } else { implementations.push(generate_from_alpha_implementation( &ident, &generics, &item_meta, )); } let item_errors = item_errors .into_iter() .map(|error| error.into_compile_error()); let field_errors = field_errors .into_iter() .map(|error| error.into_compile_error()); let impl_params_errors = impl_params_errors .into_iter() .map(|error| error.into_compile_error()); Ok(quote! { #(#item_errors)* #(#field_errors)* #(#impl_params_errors)* #(#implementations)* } .into()) } fn prepare_from_impl( component: &Type, white_point: Option<(Type, WhitePointSource)>, meta: &TypeItemAttributes, generics: &Generics, ) -> (Vec, Vec) { let included_colors = meta .color_groups .iter() .flat_map(|group| group.color_names()) .filter(|&color| !meta.skip_derives.contains(color.name)); let mut parameters = Vec::new(); let mut errors = Vec::new(); for color in included_colors { let impl_params = prepare_from_impl_for_pair( color, component, white_point.clone(), meta, generics.clone(), ); match impl_params { Ok(Some(impl_params)) => parameters.push(impl_params), Ok(None) => {} Err(error) => errors.push(error), } } (parameters, errors) } fn prepare_from_impl_for_pair( color: &ColorInfo, component: &Type, white_point: Option<(Type, WhitePointSource)>, meta: &TypeItemAttributes, mut generics: Generics, ) -> Result> { let nearest_color = find_nearest_color(color, meta)?; // Figures out which white point the target type prefers, unless it's specified in `white_point`. let (white_point, white_point_source) = if let Some((white_point, source)) = white_point { (white_point, source) } else { color.get_default_white_point(meta.internal) }; let (color_ty, mut used_input) = get_convert_color_type(color, &white_point, component, meta, &mut generics)?; let nearest_color_ty = nearest_color.get_type( MetaTypeSource::OtherColor(color), component, &white_point, &mut used_input, InputUser::Nearest, meta, )?; // Skip implementing the trait where it wouldn't be able to constrain the // white point. This is only happening when certain optional features are // enabled. if used_input.white_point.is_unconstrained() && matches!(white_point_source, WhitePointSource::GeneratedGeneric) { return Ok(None); } if used_input.white_point.is_used() { match white_point_source { WhitePointSource::WhitePoint => { let white_point_path = util::path(["white_point", "WhitePoint"], meta.internal); generics .make_where_clause() .predicates .push(parse_quote!(#white_point: #white_point_path<#component>)) } WhitePointSource::RgbStandard => { let rgb_standard_path = util::path(["rgb", "RgbStandard"], meta.internal); let rgb_standard = meta.rgb_standard.as_ref(); generics .make_where_clause() .predicates .push(parse_quote!(#rgb_standard: #rgb_standard_path)); } WhitePointSource::LumaStandard => { let luma_standard_path = util::path(["luma", "LumaStandard"], meta.internal); let luma_standard = meta.luma_standard.as_ref(); generics .make_where_clause() .predicates .push(parse_quote!(#luma_standard: #luma_standard_path)); } WhitePointSource::ConcreteType => {} WhitePointSource::GeneratedGeneric => { generics.params.push(parse_quote!(_Wp)); } } } Ok(Some(FromImplParameters { generics, color_ty, nearest_color_ty, })) } struct FromImplParameters { generics: Generics, color_ty: Type, nearest_color_ty: Type, } fn generate_from_implementations( ident: &Ident, generics: &Generics, meta: &TypeItemAttributes, all_parameters: &[FromImplParameters], ) -> Vec { let from_trait_path = util::path(["convert", "FromColorUnclamped"], meta.internal); let into_trait_path = util::path(["convert", "IntoColorUnclamped"], meta.internal); let (_, type_generics, _) = generics.split_for_impl(); let mut implementations = Vec::with_capacity(all_parameters.len()); for parameters in all_parameters { let FromImplParameters { color_ty, generics, nearest_color_ty, } = parameters; { let mut generics = generics.clone(); { let where_clause = generics.make_where_clause(); where_clause .predicates .push(parse_quote!(#nearest_color_ty: #from_trait_path<#color_ty>)); where_clause .predicates .push(parse_quote!(#nearest_color_ty: #into_trait_path)); } let (impl_generics, _, where_clause) = generics.split_for_impl(); implementations.push(quote! { #[automatically_derived] impl #impl_generics #from_trait_path<#color_ty> for #ident #type_generics #where_clause { fn from_color_unclamped(color: #color_ty) -> Self { use #from_trait_path; use #into_trait_path; #nearest_color_ty::from_color_unclamped(color).into_color_unclamped() } } }); } if !meta.internal || meta.internal_not_base_type { let mut generics = generics.clone(); { let where_clause = generics.make_where_clause(); where_clause .predicates .push(parse_quote!(#nearest_color_ty: #from_trait_path<#ident #type_generics>)); where_clause .predicates .push(parse_quote!(#nearest_color_ty: #into_trait_path)); } let (impl_generics, _, where_clause) = generics.split_for_impl(); implementations.push(quote! { #[automatically_derived] impl #impl_generics #from_trait_path<#ident #type_generics> for #color_ty #where_clause { fn from_color_unclamped(color: #ident #type_generics) -> Self { use #from_trait_path; use #into_trait_path; #nearest_color_ty::from_color_unclamped(color).into_color_unclamped() } } }); } } implementations } fn generate_from_alpha_implementation( ident: &Ident, generics: &Generics, meta: &TypeItemAttributes, ) -> TokenStream2 { let from_trait_path = util::path(["convert", "FromColorUnclamped"], meta.internal); let into_trait_path = util::path(["convert", "IntoColorUnclamped"], meta.internal); let alpha_path = util::path(["Alpha"], meta.internal); let mut impl_generics = generics.clone(); impl_generics.params.push(parse_quote!(_C)); impl_generics.params.push(parse_quote!(_A)); { let where_clause = impl_generics.make_where_clause(); where_clause .predicates .push(parse_quote!(_C: #into_trait_path)); } let (_, type_generics, _) = generics.split_for_impl(); let (self_impl_generics, _, self_where_clause) = impl_generics.split_for_impl(); quote! { #[automatically_derived] impl #self_impl_generics #from_trait_path<#alpha_path<_C, _A>> for #ident #type_generics #self_where_clause { fn from_color_unclamped(color: #alpha_path<_C, _A>) -> Self { color.color.into_color_unclamped() } } } } fn generate_from_alpha_implementation_with_internal( ident: &Ident, generics: &Generics, meta: &TypeItemAttributes, alpha_property: &IdentOrIndex, alpha_type: &Type, ) -> TokenStream2 { let from_trait_path = util::path(["convert", "FromColorUnclamped"], meta.internal); let into_trait_path = util::path(["convert", "IntoColorUnclamped"], meta.internal); let alpha_path = util::path(["Alpha"], meta.internal); let (_, type_generics, _) = generics.split_for_impl(); let mut impl_generics = generics.clone(); impl_generics.params.push(parse_quote!(_C)); { let where_clause = impl_generics.make_where_clause(); where_clause .predicates .push(parse_quote!(_C: #into_trait_path)); } let (impl_generics, _, where_clause) = impl_generics.split_for_impl(); quote! { #[automatically_derived] impl #impl_generics #from_trait_path<#alpha_path<_C, #alpha_type>> for #ident #type_generics #where_clause { fn from_color_unclamped(color: #alpha_path<_C, #alpha_type>) -> Self { use #from_trait_path; use #into_trait_path; let #alpha_path { color, alpha } = color; let mut result: Self = color.into_color_unclamped(); result.#alpha_property = alpha; result } } } } palette_derive-0.7.6/src/convert/mod.rs000064400000000000000000000001641046102023000162270ustar 00000000000000pub use self::from_color_unclamped::derive as derive_from_color_unclamped; mod from_color_unclamped; pub mod util; palette_derive-0.7.6/src/convert/util.rs000064400000000000000000000114301046102023000164230ustar 00000000000000use std::collections::HashMap; use proc_macro2::Span; use syn::{parse_quote, Generics, Result, Type}; use crate::{ color_types::{ColorInfo, MetaTypeSource}, meta::TypeItemAttributes, util, }; pub fn white_point_type( white_point: Option<&Type>, rgb_standard: Option<&Type>, luma_standard: Option<&Type>, internal: bool, ) -> Option<(Type, WhitePointSource)> { white_point .map(|white_point| (white_point.clone(), WhitePointSource::WhitePoint)) .or_else(|| { rgb_standard.map(|rgb_standard| { let rgb_standard_path = util::path(["rgb", "RgbStandard"], internal); let rgb_space_path = util::path(["rgb", "RgbSpace"], internal); ( parse_quote!(<<#rgb_standard as #rgb_standard_path>::Space as #rgb_space_path>::WhitePoint), WhitePointSource::RgbStandard, ) }) }) .or_else(|| { luma_standard.map(|luma_standard| { let luma_standard_path = util::path(["luma", "LumaStandard"], internal); ( parse_quote!(<#luma_standard as #luma_standard_path>::WhitePoint), WhitePointSource::LumaStandard, ) }) }) } pub fn component_type(component: Option) -> Type { component.unwrap_or_else(|| parse_quote!(f32)) } pub(crate) fn get_convert_color_type( color: &ColorInfo, white_point: &Type, component: &Type, meta: &TypeItemAttributes, generics: &mut Generics, ) -> syn::Result<(Type, UsedInput)> { let mut used_input = UsedInput::default(); let color_type = color.get_type( MetaTypeSource::Generics(generics), component, white_point, &mut used_input, InputUser::Target, meta, )?; Ok((color_type, used_input)) } pub(crate) fn find_nearest_color<'a>( color: &'a ColorInfo, meta: &TypeItemAttributes, ) -> Result<&'a ColorInfo> { let mut stack = vec![(color, 0)]; let mut found = None; let mut visited = HashMap::new(); // Make sure there is at least one valid color in the skip list assert!(!meta.skip_derives.is_empty()); while let Some((color, distance)) = stack.pop() { if meta.skip_derives.contains(color.name) { if let Some((_, found_distance)) = found { if distance < found_distance { found = Some((color, distance)); continue; } } else { found = Some((color, distance)); continue; } } if let Some(&previous_distance) = visited.get(color.name) { if previous_distance <= distance { continue; } } visited.insert(color.name, distance); // Start by pushing the plan B routes... for group in &meta.color_groups { for candidate in group.colors { if color.name == candidate.preferred_source { stack.push((&candidate.info, distance + 1)); } } } // ...then push the preferred routes. They will be popped first. for group in &meta.color_groups { for candidate in group.colors { if color.name == candidate.info.name { let preferred = group .find_by_name(candidate.preferred_source) .expect("preferred sources have to exist in the group"); stack.push((preferred, distance + 1)); } } } } if let Some((color, _)) = found { Ok(color) } else { Err(::syn::parse::Error::new( Span::call_site(), format!( "none of the skipped colors can be used for converting from {}", color.name ), )) } } #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum WhitePointSource { WhitePoint, RgbStandard, LumaStandard, ConcreteType, GeneratedGeneric, } #[derive(Debug, Default)] pub struct UsedInput { pub white_point: InputUsage, } #[derive(Debug, Default)] pub struct InputUsage { used_by_target: bool, used_by_nearest: bool, } impl InputUsage { pub(crate) fn set_used(&mut self, user: InputUser) { match user { InputUser::Target => self.used_by_target = true, InputUser::Nearest => self.used_by_nearest = true, } } pub(crate) fn is_used(&self) -> bool { self.used_by_target || self.used_by_nearest } pub(crate) fn is_unconstrained(&self) -> bool { !self.used_by_target && self.used_by_nearest } } #[derive(Clone, Copy)] pub enum InputUser { Target, Nearest, } palette_derive-0.7.6/src/lib.rs000064400000000000000000000032111046102023000145320ustar 00000000000000//! Derives traits from the [palette](https://crates.io/crates/palette) crate. use proc_macro::TokenStream; macro_rules! syn_try { ($e:expr) => { match $e { Ok(value) => value, Err(errors) => { trait IntoErrors { fn into_errors(self) -> Vec<::syn::parse::Error>; } impl IntoErrors for Vec<::syn::parse::Error> { fn into_errors(self) -> Vec<::syn::parse::Error> { self } } impl IntoErrors for ::syn::parse::Error { fn into_errors(self) -> Vec<::syn::parse::Error> { vec![self] } } let errors: ::proc_macro2::TokenStream = IntoErrors::into_errors(errors) .iter() .map(::syn::parse::Error::to_compile_error) .collect(); return ::proc_macro::TokenStream::from(errors); } } }; } mod alpha; mod cast; mod color_types; mod convert; mod meta; mod util; #[proc_macro_derive(WithAlpha, attributes(palette))] pub fn derive_with_alpha(tokens: TokenStream) -> TokenStream { syn_try!(alpha::derive_with_alpha(tokens)) } #[proc_macro_derive(FromColorUnclamped, attributes(palette))] pub fn derive_from_color_unclamped(tokens: TokenStream) -> TokenStream { syn_try!(convert::derive_from_color_unclamped(tokens)) } #[proc_macro_derive(ArrayCast, attributes(palette))] pub fn derive_array_cast(tokens: TokenStream) -> TokenStream { syn_try!(cast::derive_array_cast(tokens)) } palette_derive-0.7.6/src/meta/field_attributes.rs000064400000000000000000000041471046102023000202540ustar 00000000000000use std::collections::{HashMap, HashSet}; use syn::{spanned::Spanned, Expr, ExprLit}; use syn::{Lit, Meta, MetaNameValue, Type}; use super::{assert_path_meta, FieldAttributeArgumentParser, IdentOrIndex}; #[derive(Default)] pub struct FieldAttributes { pub alpha_property: Option<(IdentOrIndex, Type)>, pub zero_size_fields: HashSet, pub type_substitutes: HashMap, } impl FieldAttributeArgumentParser for FieldAttributes { fn argument( &mut self, field_name: &IdentOrIndex, ty: &Type, argument: Meta, ) -> Result<(), Vec> { let argument_name = argument.path().get_ident().map(ToString::to_string); match argument_name.as_deref() { Some("alpha") => { assert_path_meta(&argument).map_err(|error| vec![error])?; self.alpha_property = Some((field_name.clone(), ty.clone())); } Some("unsafe_same_layout_as") => { let substitute = if let Meta::NameValue(MetaNameValue { value: Expr::Lit(ExprLit { lit: Lit::Str(string), .. }), .. }) = argument { string.parse().map_err(|error| vec![error])? } else { return Err(vec![::syn::parse::Error::new( argument.span(), "expected `unsafe_same_layout_as = \"SomeType\"`", )]); }; self.type_substitutes.insert(field_name.clone(), substitute); } Some("unsafe_zero_sized") => { assert_path_meta(&argument).map_err(|error| vec![error])?; self.zero_size_fields.insert(field_name.clone()); } _ => { return Err(vec![::syn::parse::Error::new( argument.span(), "unknown field attribute", )]); } } Ok(()) } } palette_derive-0.7.6/src/meta/mod.rs000064400000000000000000000131401046102023000154730ustar 00000000000000use proc_macro2::TokenStream; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ parse::{Parse, ParseStream, Parser, Result}, token::Comma, }; use syn::{Attribute, Fields, Ident, Index, LitStr, Meta, Token, Type}; pub use self::field_attributes::*; pub use self::type_item_attributes::*; mod field_attributes; mod type_item_attributes; pub fn parse_namespaced_attributes( attributes: Vec, ) -> (T, Vec<::syn::parse::Error>) { let mut result = T::default(); let mut errors = Vec::new(); for attribute in attributes { let is_palette_attribute = attribute .meta .path() .get_ident() .map(|name| name == "palette") .unwrap_or(false); if !is_palette_attribute { continue; } let meta_list = match attribute.meta.require_list() { Ok(list) => list, Err(error) => { errors.push(error); continue; } }; if meta_list.tokens.is_empty() { errors.push(::syn::parse::Error::new( attribute.path().span(), "expected `palette(...)`", )); continue; } let parse_result = Punctuated::<_, Comma>::parse_terminated.parse2(meta_list.tokens.clone()); match parse_result { Ok(meta) => { for argument in meta { if let Err(new_error) = result.argument(argument) { errors.extend(new_error); } } } Err(error) => errors.push(error), } } (result, errors) } pub fn parse_field_attributes( fields: Fields, ) -> (T, Vec<::syn::parse::Error>) { let mut result = T::default(); let mut errors = Vec::new(); let attributes = fields.into_iter().enumerate().flat_map(|(index, field)| { let field_name = field .ident .map(IdentOrIndex::Ident) .unwrap_or_else(|| IdentOrIndex::Index(index.into())); let ty = field.ty; field .attrs .into_iter() .map(move |attribute| (field_name.clone(), ty.clone(), attribute)) }); for (field_name, ty, attribute) in attributes { let is_palette_attribute = attribute .path() .get_ident() .map(|name| name == "palette") .unwrap_or(false); if !is_palette_attribute { continue; } let meta_list = match attribute.meta.require_list() { Ok(list) => list, Err(error) => { errors.push(error); continue; } }; if meta_list.tokens.is_empty() { errors.push(::syn::parse::Error::new( attribute.path().span(), "expected `palette(...)`", )); continue; } let parse_result = Punctuated::<_, Comma>::parse_terminated.parse2(meta_list.tokens.clone()); match parse_result { Ok(meta) => { for argument in meta { if let Err(new_errors) = result.argument(&field_name, &ty, argument) { errors.extend(new_errors); } } } Err(error) => errors.push(error), } } (result, errors) } pub fn assert_path_meta(meta: &Meta) -> Result<()> { if !matches!(meta, Meta::Path(_)) { return Err(::syn::parse::Error::new( meta.span(), "expected the attribute to be just an identifier or a path", )); } Ok(()) } #[derive(PartialEq)] pub struct KeyValuePair { pub key: Ident, pub value: Ident, } impl Parse for KeyValuePair { fn parse(input: ParseStream) -> Result { let key: Ident = input.parse()?; input.parse::()?; let value = input.parse::()?.parse::()?; Ok(KeyValuePair { key, value }) } } impl PartialEq for KeyValuePair { fn eq(&self, other: &str) -> bool { self.key == other } } #[derive(Clone)] pub enum IdentOrIndex { Index(Index), Ident(Ident), } impl PartialEq for IdentOrIndex { fn eq(&self, other: &IdentOrIndex) -> bool { match (self, other) { (IdentOrIndex::Index(this), IdentOrIndex::Index(other)) => this.index == other.index, (IdentOrIndex::Ident(this), IdentOrIndex::Ident(other)) => this == other, _ => false, } } } impl Eq for IdentOrIndex {} impl ::std::hash::Hash for IdentOrIndex { fn hash(&self, hasher: &mut H) { ::std::mem::discriminant(self).hash(hasher); match *self { IdentOrIndex::Index(ref index) => index.index.hash(hasher), IdentOrIndex::Ident(ref ident) => ident.hash(hasher), } } } impl ::quote::ToTokens for IdentOrIndex { fn to_tokens(&self, tokens: &mut TokenStream) { match *self { IdentOrIndex::Index(ref index) => index.to_tokens(tokens), IdentOrIndex::Ident(ref ident) => ident.to_tokens(tokens), } } } pub trait AttributeArgumentParser: Default { fn argument(&mut self, argument: Meta) -> std::result::Result<(), Vec>; } pub trait FieldAttributeArgumentParser: Default { fn argument( &mut self, field_name: &IdentOrIndex, ty: &Type, argument: Meta, ) -> std::result::Result<(), Vec>; } palette_derive-0.7.6/src/meta/type_item_attributes.rs000064400000000000000000000124501046102023000211640ustar 00000000000000use std::collections::HashSet; use by_address::ByAddress; use quote::quote; use syn::{punctuated::Punctuated, spanned::Spanned, token::Comma, Expr, ExprLit}; use syn::{Ident, Lit, Meta, MetaNameValue, Type}; use crate::color_types::{ColorGroup, COLOR_GROUPS}; use super::AttributeArgumentParser; #[derive(Default)] pub struct TypeItemAttributes { pub skip_derives: HashSet, pub internal: bool, pub internal_not_base_type: bool, pub component: Option, pub white_point: Option, pub rgb_standard: Option, pub luma_standard: Option, pub(crate) color_groups: HashSet>, } impl AttributeArgumentParser for TypeItemAttributes { fn argument(&mut self, argument: Meta) -> Result<(), Vec> { let argument_name = argument.path().get_ident().map(ToString::to_string); match argument_name.as_deref() { Some("skip_derives") => { if let Meta::List(list) = argument { let skipped = list .parse_args_with(Punctuated::::parse_terminated) .map_err(|error| vec![error])?; let mut errors = Vec::new(); for skipped_color in skipped { let color_name = skipped_color.to_string(); self.skip_derives.insert(color_name.clone()); let color_group = COLOR_GROUPS .iter() .find(|group| group.check_availability(&color_name).is_ok()); let group = if let Some(&group) = color_group { group } else { errors.push(syn::Error::new( skipped_color.span(), format!("`{}` is not a valid color type", skipped_color), )); continue; }; let infer_group = group .find_type_by_name(&color_name) .map_or(true, |ty| ty.infer_group); if infer_group { self.color_groups.insert(group.into()); } } if !errors.is_empty() { return Err(errors); } } else { return Err(vec![syn::Error::new( argument.span(), "expected `skip_derives` to have a list of color type names, like `skip_derives(Xyz, Luma, Rgb)`", )]); } } Some("component") => { get_meta_type_argument(argument, &mut self.component)?; } Some("white_point") => { get_meta_type_argument(argument, &mut self.white_point)?; } Some("rgb_standard") => { get_meta_type_argument(argument, &mut self.rgb_standard)?; } Some("luma_standard") => { get_meta_type_argument(argument, &mut self.luma_standard)?; } Some("palette_internal") => { if let Meta::Path(_) = argument { self.internal = true; } else { return Err(vec![syn::Error::new( argument.span(), "expected `palette_internal` to a literal without value", )]); } } Some("palette_internal_not_base_type") => { if let Meta::Path(_) = argument { self.internal_not_base_type = true; } else { return Err(vec![syn::Error::new( argument.span(), "expected `palette_internal` to a literal without value", )]); } } _ => { return Err(vec![syn::Error::new( argument.span(), format!("`{}` is not a known type item attribute", quote!(#argument)), )]); } } Ok(()) } } fn get_meta_type_argument( argument: Meta, attribute: &mut Option, ) -> Result<(), Vec> { if attribute.is_none() { let result = if let Meta::NameValue(MetaNameValue { value: Expr::Lit(ExprLit { lit: Lit::Str(ty), .. }), .. }) = argument { *attribute = Some(ty.parse().map_err(|error| vec![error])?); Ok(()) } else { Err((argument.span(), argument.path())) }; if let Err((span, path)) = result { let name = path.get_ident().unwrap(); let message = format!("expected `{name}` to be a type or type parameter in a string, like `{name} = \"T\"`"); Err(vec![syn::Error::new(span, message)]) } else { Ok(()) } } else { let name = argument.path().get_ident().unwrap(); Err(vec![syn::Error::new( argument.span(), format!("`{name}` appears more than once"), )]) } } palette_derive-0.7.6/src/util.rs000064400000000000000000000024701046102023000147470ustar 00000000000000use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{parse_quote, Ident, Type}; pub fn path<'a, P: AsRef<[&'a str]>>(path: P, internal: bool) -> TokenStream { let path = path .as_ref() .iter() .map(|&ident| Ident::new(ident, Span::call_site())); if internal { quote! {crate::#(#path)::*} } else { let crate_name = find_crate_name(); quote! {#crate_name::#(#path)::*} } } pub fn path_type(path: &[&str], internal: bool) -> Type { let path = path .iter() .map(|&ident| Ident::new(ident, Span::call_site())); if internal { parse_quote! {crate::#(#path)::*} } else { let crate_name = find_crate_name(); parse_quote! {#crate_name::#(#path)::*} } } #[cfg(feature = "find-crate")] fn find_crate_name() -> Ident { use find_crate::Error; match find_crate::find_crate(|name| name == "palette") { Ok(package) => Ident::new(&package.name, Span::call_site()), Err(Error::NotFound) => Ident::new("palette", Span::call_site()), Err(error) => panic!( "error when trying to find the name of the `palette` crate: {}", error ), } } #[cfg(not(feature = "find-crate"))] fn find_crate_name() -> Ident { Ident::new("palette", Span::call_site()) }