chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

View File

@@ -0,0 +1 @@
{"files":{".cargo_vcs_info.json":"d5e5fd4e487bac2bfc1cae10cb874a64c6bc91e30a2056aa353f57270fd42574","Cargo.lock":"ffb177649302dc850d931c74f255771966276d302735c7fc09e9e407e715ed13","Cargo.toml":"f40baba6038bc2ebbbe173d602be2679db6ce248590cfd01a136ce42005965d4","Cargo.toml.orig":"5e422ee713bc2f5fc84fce0bb2a4b804725263087ddad8594211f951330228e0","LICENSE":"f367c1b8e1aa262435251e442901da4607b4650e0e63a026f5044473ecfb90f2","README.md":"2ef78913a98fb26c912c47c3c96167b9b57524754dc4857fe18a2122fec4985e","examples/zf_derive.rs":"39342f4658da4c6e475a290028b7cbab161e1fb91ee49c79cda4799a8614bc9b","src/lib.rs":"b06e2bb87ffa35a3eb68c5c3ba71f67279e9a44f4a3ec3168302f01c56f667ee","src/visitor.rs":"6eb54d2e1c4f9211bcaa5d6e768d668063a94411bfbed610b0a0419ac37bf545"},"package":"d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"}

View File

@@ -0,0 +1,6 @@
{
"git": {
"sha1": "f4290a877dfcb0f87cad6de4abdd65f0cbb33c9c"
},
"path_in_vcs": "utils/zerofrom/derive"
}

59
vendor/zerofrom-derive/Cargo.lock generated vendored Normal file
View File

@@ -0,0 +1,59 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "proc-macro2"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "syn"
version = "2.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00e2473a93778eb0bad35909dff6a10d28e63f792f16ed15e404fca9d5eeedbe"
[[package]]
name = "zerofrom-derive"
version = "0.1.6"
dependencies = [
"proc-macro2",
"quote",
"syn",
"synstructure",
]

65
vendor/zerofrom-derive/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,65 @@
# 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 = "2021"
name = "zerofrom-derive"
version = "0.1.6"
authors = ["Manish Goregaokar <manishsmail@gmail.com>"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Custom derive for the zerofrom crate"
readme = "README.md"
keywords = [
"zerocopy",
"serialization",
"lifetime",
"borrow",
]
categories = [
"data-structures",
"memory-management",
"caching",
"no-std",
]
license = "Unicode-3.0"
repository = "https://github.com/unicode-org/icu4x"
[package.metadata.workspaces]
independent = true
[lib]
name = "zerofrom_derive"
path = "src/lib.rs"
proc-macro = true
[[example]]
name = "zf_derive"
path = "examples/zf_derive.rs"
[dependencies.proc-macro2]
version = "1.0.61"
[dependencies.quote]
version = "1.0.28"
[dependencies.syn]
version = "2.0.21"
features = ["fold"]
[dependencies.synstructure]
version = "0.13.0"
[dev-dependencies]

46
vendor/zerofrom-derive/LICENSE vendored Normal file
View File

@@ -0,0 +1,46 @@
UNICODE LICENSE V3
COPYRIGHT AND PERMISSION NOTICE
Copyright © 2020-2024 Unicode, Inc.
NOTICE TO USER: Carefully read the following legal agreement. BY
DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
Permission is hereby granted, free of charge, to any person obtaining a
copy of data files and any associated documentation (the "Data Files") or
software and any associated documentation (the "Software") to deal in the
Data Files or Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, and/or sell
copies of the Data Files or Software, and to permit persons to whom the
Data Files or Software are furnished to do so, provided that either (a)
this copyright and permission notice appear with all copies of the Data
Files or Software, or (b) this copyright and permission notice appear in
associated Documentation.
THE DATA FILES AND SOFTWARE ARE 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 OF
THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall
not be used in advertising or otherwise to promote the sale, use or other
dealings in these Data Files or Software without prior written
authorization of the copyright holder.
SPDX-License-Identifier: Unicode-3.0
Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.

11
vendor/zerofrom-derive/README.md vendored Normal file
View File

@@ -0,0 +1,11 @@
# zerofrom-derive [![crates.io](https://img.shields.io/crates/v/zerofrom-derive)](https://crates.io/crates/zerofrom-derive)
<!-- cargo-rdme start -->
Custom derives for `ZeroFrom` from the `zerofrom` crate.
<!-- cargo-rdme end -->
## More Information
For more information on development, authorship, contributing etc. please visit [`ICU4X home page`](https://github.com/unicode-org/icu4x).

View File

@@ -0,0 +1,115 @@
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
#![allow(unused)]
use std::{borrow::Cow, marker::PhantomData};
use zerofrom::ZeroFrom;
use zerovec::{maps::ZeroMapKV, ule::AsULE, VarZeroVec, ZeroMap, ZeroVec};
#[derive(ZeroFrom, Copy, Clone)]
pub struct IntExample {
x: u32,
}
#[derive(ZeroFrom, Copy, Clone)]
pub struct GenericsExample<T> {
x: u32,
y: T,
}
#[derive(ZeroFrom, Copy, Clone)]
pub struct GenericsExampleWithDefault<T, U = usize> {
x: T,
y: U,
}
#[derive(ZeroFrom)]
pub struct CowExample<'a> {
x: u8,
y: &'a str,
z: Cow<'a, str>,
w: Cow<'a, [u8]>,
}
#[derive(ZeroFrom)]
pub struct ZeroVecExample<'a> {
var: VarZeroVec<'a, str>,
vec: ZeroVec<'a, u16>,
}
#[derive(ZeroFrom)]
pub struct ZeroVecExampleWithGenerics<'a, T: AsULE> {
gen: ZeroVec<'a, T>,
vec: ZeroVec<'a, u16>,
bare: T,
}
#[derive(ZeroFrom)]
pub struct HasTuples<'data> {
pub bar: (&'data str, &'data str),
}
pub fn assert_zf_tuples<'b>(x: &'b HasTuples) -> HasTuples<'b> {
HasTuples::zero_from(x)
}
pub fn assert_zf_generics<'a, 'b>(
x: &'b ZeroVecExampleWithGenerics<'a, u8>,
) -> ZeroVecExampleWithGenerics<'b, u8> {
ZeroVecExampleWithGenerics::<'b, u8>::zero_from(x)
}
#[derive(ZeroFrom)]
pub struct ZeroMapGenericExample<'a, T: for<'b> ZeroMapKV<'b> + ?Sized> {
map: ZeroMap<'a, str, T>,
}
pub fn assert_zf_map<'b>(x: &'b ZeroMapGenericExample<str>) -> ZeroMapGenericExample<'b, str> {
ZeroMapGenericExample::zero_from(x)
}
#[derive(Clone, ZeroFrom)]
pub struct CloningZF1 {
#[zerofrom(clone)] // Vec is not ZeroFrom, so it needs to be cloned
vec: Vec<u8>,
}
#[derive(Clone, ZeroFrom)]
pub struct CloningZF2<'data> {
#[zerofrom(clone)] // Cow is ZeroFrom, but we force a clone
cow: Cow<'data, str>,
}
#[derive(ZeroFrom)]
pub enum CloningZF3<'data> {
Cow(#[zerofrom(clone)] Cow<'data, str>),
}
#[derive(ZeroFrom)]
#[zerofrom(may_borrow(T, Q))] // instead of treating T as a copy type, we want to allow zerofromming T too
pub struct GenericsThatAreAlsoZf<T, Q: ?Sized, Ignored: ?Sized> {
x: T,
y: Option<T>,
ignored: PhantomData<Ignored>,
q: Q,
}
pub fn assert_zf_generics_may_borrow<'a, 'b>(
x: &'b GenericsThatAreAlsoZf<&'a str, usize, str>,
) -> GenericsThatAreAlsoZf<&'b str, usize, str> {
GenericsThatAreAlsoZf::<&'b str, usize, str>::zero_from(x)
}
#[derive(ZeroFrom)]
pub struct UsesGenericsThatAreAlsoZf<'a> {
x: GenericsThatAreAlsoZf<&'a str, usize, str>,
}
// Ensure it works with invariant types too
#[derive(ZeroFrom)]
pub struct UsesGenericsThatAreAlsoZfWithMap<'a> {
x: GenericsThatAreAlsoZf<ZeroMap<'a, str, str>, usize, str>,
}
fn main() {}

309
vendor/zerofrom-derive/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,309 @@
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
//! Custom derives for `ZeroFrom` from the `zerofrom` crate.
// https://github.com/unicode-org/icu4x/blob/main/documents/process/boilerplate.md#library-annotations
#![cfg_attr(
not(test),
deny(
clippy::indexing_slicing,
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::exhaustive_structs,
clippy::exhaustive_enums,
clippy::trivially_copy_pass_by_ref,
missing_debug_implementations,
)
)]
use core::mem;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote;
use std::collections::{HashMap, HashSet};
use syn::fold::{self, Fold};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{
parse_macro_input, parse_quote, DeriveInput, Ident, Lifetime, MetaList, Token,
TraitBoundModifier, Type, TypeParamBound, TypePath, WherePredicate,
};
use synstructure::Structure;
mod visitor;
/// Custom derive for `zerofrom::ZeroFrom`,
///
/// This implements `ZeroFrom<Ty> for Ty` for types
/// without a lifetime parameter, and `ZeroFrom<Ty<'data>> for Ty<'static>`
/// for types with a lifetime parameter.
///
/// Apply the `#[zerofrom(clone)]` attribute to a field if it doesn't implement
/// Copy or ZeroFrom; this data will be cloned when the struct is zero_from'ed.
///
/// Apply the `#[zerofrom(maybe_borrow(T, U, V))]` attribute to the struct to indicate
/// that certain type parameters may themselves contain borrows (by default
/// the derives assume that type parameters perform no borrows and can be copied or cloned).
///
/// In rust versions where [this issue](https://github.com/rust-lang/rust/issues/114393) is fixed,
/// `#[zerofrom(may_borrow)]` can be applied directly to type parameters.
#[proc_macro_derive(ZeroFrom, attributes(zerofrom))]
pub fn zf_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
TokenStream::from(zf_derive_impl(&input))
}
fn has_attr(attrs: &[syn::Attribute], name: &str) -> bool {
attrs.iter().any(|a| {
if let Ok(i) = a.parse_args::<Ident>() {
if i == name {
return true;
}
}
false
})
}
// Collects all idents from #[zerofrom(may_borrow(A, B, C, D))]
// needed since #[zerofrom(may_borrow)] doesn't work yet
// (https://github.com/rust-lang/rust/issues/114393)
fn get_may_borrow_attr(attrs: &[syn::Attribute]) -> Result<HashSet<Ident>, Span> {
let mut params = HashSet::new();
for attr in attrs {
if let Ok(list) = attr.parse_args::<MetaList>() {
if list.path.is_ident("may_borrow") {
if let Ok(list) =
list.parse_args_with(Punctuated::<Ident, Token![,]>::parse_terminated)
{
params.extend(list)
} else {
return Err(attr.span());
}
}
}
}
Ok(params)
}
fn zf_derive_impl(input: &DeriveInput) -> TokenStream2 {
let mut tybounds = input
.generics
.type_params()
.map(|ty| {
// Strip out param defaults, we don't need them in the impl
let mut ty = ty.clone();
ty.eq_token = None;
ty.default = None;
ty
})
.collect::<Vec<_>>();
let typarams = tybounds
.iter()
.map(|ty| ty.ident.clone())
.collect::<Vec<_>>();
let lts = input.generics.lifetimes().count();
let name = &input.ident;
let structure = Structure::new(input);
let may_borrow_attrs = match get_may_borrow_attr(&input.attrs) {
Ok(mb) => mb,
Err(span) => {
return syn::Error::new(
span,
"#[zerofrom(may_borrow)] on the struct takes in a comma separated list of type parameters, like so: `#[zerofrom(may_borrow(A, B, C, D)]`",
).to_compile_error();
}
};
// This contains every generic type introduced in this code.
// If the gneeric type is may_borrow, this additionally contains the identifier corresponding to
// a newly introduced mirror type parameter that we are borrowing from, similar to C in the original trait.
// For convenience, we are calling these "C types"
let generics_env: HashMap<Ident, Option<Ident>> = tybounds
.iter_mut()
.map(|param| {
// First one doesn't work yet https://github.com/rust-lang/rust/issues/114393
let maybe_new_param = if has_attr(&param.attrs, "may_borrow")
|| may_borrow_attrs.contains(&param.ident)
{
// Remove `?Sized`` bound because we need a param to be Sized in order to take a ZeroFrom of it.
// This only applies to fields marked as `may_borrow`.
let mut bounds = core::mem::take(&mut param.bounds);
while let Some(bound_pair) = bounds.pop() {
let bound = bound_pair.into_value();
if let TypeParamBound::Trait(ref trait_bound) = bound {
if trait_bound.path.get_ident().map(|ident| ident == "Sized") == Some(true)
&& matches!(trait_bound.modifier, TraitBoundModifier::Maybe(_))
{
continue;
}
}
param.bounds.push(bound);
}
Some(Ident::new(
&format!("{}ZFParamC", param.ident),
param.ident.span(),
))
} else {
None
};
(param.ident.clone(), maybe_new_param)
})
.collect();
// Do any of the generics potentially borrow?
let generics_may_borrow = generics_env.values().any(|x| x.is_some());
if lts == 0 && !generics_may_borrow {
let has_clone = structure
.variants()
.iter()
.flat_map(|variant| variant.bindings().iter())
.any(|binding| has_attr(&binding.ast().attrs, "clone"));
let (clone, clone_trait) = if has_clone {
(quote!(this.clone()), quote!(Clone))
} else {
(quote!(*this), quote!(Copy))
};
let bounds: Vec<WherePredicate> = typarams
.iter()
.map(|ty| parse_quote!(#ty: #clone_trait + 'static))
.collect();
quote! {
impl<'zf, #(#tybounds),*> zerofrom::ZeroFrom<'zf, #name<#(#typarams),*>> for #name<#(#typarams),*> where #(#bounds),* {
fn zero_from(this: &'zf Self) -> Self {
#clone
}
}
}
} else {
if lts > 1 {
return syn::Error::new(
input.generics.span(),
"derive(ZeroFrom) cannot have multiple lifetime parameters",
)
.to_compile_error();
}
let mut zf_bounds: Vec<WherePredicate> = vec![];
let body = structure.each_variant(|vi| {
vi.construct(|f, i| {
let binding = format!("__binding_{i}");
let field = Ident::new(&binding, Span::call_site());
if has_attr(&f.attrs, "clone") {
quote! {
#field.clone()
}
} else {
// the field type
let fty = replace_lifetime(&f.ty, custom_lt("'zf"));
// the corresponding lifetimey type we are borrowing from (effectively, the C type)
let lifetime_ty =
replace_lifetime_and_type(&f.ty, custom_lt("'zf_inner"), &generics_env);
let (has_ty, has_lt) = visitor::check_type_for_parameters(&f.ty, &generics_env);
if has_ty {
// For types without type parameters, the compiler can figure out that the field implements
// ZeroFrom on its own. However, if there are type parameters, there may be complex preconditions
// to `FieldTy: ZeroFrom` that need to be satisfied. We get them to be satisfied by requiring
// `FieldTy<'zf>: ZeroFrom<'zf, FieldTy<'zf_inner>>`
if has_lt {
zf_bounds
.push(parse_quote!(#fty: zerofrom::ZeroFrom<'zf, #lifetime_ty>));
} else {
zf_bounds.push(parse_quote!(#fty: zerofrom::ZeroFrom<'zf, #fty>));
}
}
if has_ty || has_lt {
// By doing this we essentially require ZF to be implemented
// on all fields
quote! {
<#fty as zerofrom::ZeroFrom<'zf, #lifetime_ty>>::zero_from(#field)
}
} else {
// No lifetimes, so we can just copy
quote! { *#field }
}
}
})
});
// Due to the possibility of generics_may_borrow, we might reach here with no lifetimes on self,
// don't accidentally feed them to self later
let (maybe_zf_lifetime, maybe_zf_inner_lifetime) = if lts == 0 {
(quote!(), quote!())
} else {
(quote!('zf,), quote!('zf_inner,))
};
// Array of C types. Only different if generics are allowed to borrow
let mut typarams_c = typarams.clone();
if generics_may_borrow {
for typaram_c in &mut typarams_c {
if let Some(Some(replacement)) = generics_env.get(typaram_c) {
// we use mem::replace here so we can be really clear about the C vs the T type
let typaram_t = mem::replace(typaram_c, replacement.clone());
zf_bounds
.push(parse_quote!(#typaram_c: zerofrom::ZeroFrom<'zf_inner, #typaram_t>));
tybounds.push(parse_quote!(#typaram_c));
}
}
}
quote! {
impl<'zf, 'zf_inner, #(#tybounds),*> zerofrom::ZeroFrom<'zf, #name<#maybe_zf_inner_lifetime #(#typarams_c),*>> for #name<#maybe_zf_lifetime #(#typarams),*>
where
#(#zf_bounds,)* {
fn zero_from(this: &'zf #name<#maybe_zf_inner_lifetime #(#typarams_c),*>) -> Self {
match *this { #body }
}
}
}
}
}
fn custom_lt(s: &str) -> Lifetime {
Lifetime::new(s, Span::call_site())
}
/// Replace all lifetimes in a type with a specified one
fn replace_lifetime(x: &Type, lt: Lifetime) -> Type {
struct ReplaceLifetime(Lifetime);
impl Fold for ReplaceLifetime {
fn fold_lifetime(&mut self, _: Lifetime) -> Lifetime {
self.0.clone()
}
}
ReplaceLifetime(lt).fold_type(x.clone())
}
/// Replace all lifetimes in a type with a specified one, AND replace all types that have a corresponding C type
/// with the C type
fn replace_lifetime_and_type(
x: &Type,
lt: Lifetime,
generics_env: &HashMap<Ident, Option<Ident>>,
) -> Type {
struct ReplaceLifetimeAndTy<'a>(Lifetime, &'a HashMap<Ident, Option<Ident>>);
impl Fold for ReplaceLifetimeAndTy<'_> {
fn fold_lifetime(&mut self, _: Lifetime) -> Lifetime {
self.0.clone()
}
fn fold_type_path(&mut self, i: TypePath) -> TypePath {
if i.qself.is_none() {
if let Some(ident) = i.path.get_ident() {
if let Some(Some(replacement)) = self.1.get(ident) {
return parse_quote!(#replacement);
}
}
}
fold::fold_type_path(self, i)
}
}
ReplaceLifetimeAndTy(lt, generics_env).fold_type(x.clone())
}

120
vendor/zerofrom-derive/src/visitor.rs vendored Normal file
View File

@@ -0,0 +1,120 @@
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
//! Visitor for determining whether a type has type and non-static lifetime parameters
//! (duplicated in yoke/derive/src/visitor.rs)
use std::collections::HashMap;
use syn::visit::{visit_lifetime, visit_type, visit_type_path, Visit};
use syn::{Ident, Lifetime, Type, TypePath};
struct TypeVisitor<'a> {
/// The type parameters in scope
typarams: &'a HashMap<Ident, Option<Ident>>,
/// Whether we found a type parameter
found_typarams: bool,
/// Whether we found a non-'static lifetime parameter
found_lifetimes: bool,
}
impl<'ast> Visit<'ast> for TypeVisitor<'_> {
fn visit_lifetime(&mut self, lt: &'ast Lifetime) {
if lt.ident != "static" {
self.found_lifetimes = true;
}
visit_lifetime(self, lt)
}
fn visit_type_path(&mut self, ty: &'ast TypePath) {
// We only need to check ty.path.get_ident() and not ty.qself or any
// generics in ty.path because the visitor will eventually visit those
// types on its own
if let Some(ident) = ty.path.get_ident() {
if let Some(maybe_borrowed) = self.typarams.get(ident) {
self.found_typarams = true;
if maybe_borrowed.is_some() {
self.found_lifetimes = true;
}
}
}
visit_type_path(self, ty)
}
}
/// Checks if a type has type or lifetime parameters, given the local context of
/// named type parameters. Returns (has_type_params, has_lifetime_params)
pub fn check_type_for_parameters(
ty: &Type,
typarams: &HashMap<Ident, Option<Ident>>,
) -> (bool, bool) {
let mut visit = TypeVisitor {
typarams,
found_typarams: false,
found_lifetimes: false,
};
visit_type(&mut visit, ty);
(visit.found_typarams, visit.found_lifetimes)
}
#[cfg(test)]
mod tests {
use proc_macro2::Span;
use std::collections::HashMap;
use syn::{parse_quote, Ident};
use super::check_type_for_parameters;
fn make_typarams(params: &[&str]) -> HashMap<Ident, Option<Ident>> {
params
.iter()
.map(|x| (Ident::new(x, Span::call_site()), None))
.collect()
}
#[test]
fn test_simple_type() {
let environment = make_typarams(&["T", "U", "V"]);
let ty = parse_quote!(Foo<'a, T>);
let check = check_type_for_parameters(&ty, &environment);
assert_eq!(check, (true, true));
let ty = parse_quote!(Foo<T>);
let check = check_type_for_parameters(&ty, &environment);
assert_eq!(check, (true, false));
let ty = parse_quote!(Foo<'static, T>);
let check = check_type_for_parameters(&ty, &environment);
assert_eq!(check, (true, false));
let ty = parse_quote!(Foo<'a>);
let check = check_type_for_parameters(&ty, &environment);
assert_eq!(check, (false, true));
let ty = parse_quote!(Foo<'a, Bar<U>, Baz<(V, u8)>>);
let check = check_type_for_parameters(&ty, &environment);
assert_eq!(check, (true, true));
let ty = parse_quote!(Foo<'a, W>);
let check = check_type_for_parameters(&ty, &environment);
assert_eq!(check, (false, true));
}
#[test]
fn test_assoc_types() {
let environment = make_typarams(&["T"]);
let ty = parse_quote!(<Foo as SomeTrait<'a, T>>::Output);
let check = check_type_for_parameters(&ty, &environment);
assert_eq!(check, (true, true));
let ty = parse_quote!(<Foo as SomeTrait<'static, T>>::Output);
let check = check_type_for_parameters(&ty, &environment);
assert_eq!(check, (true, false));
let ty = parse_quote!(<T as SomeTrait<'static, Foo>>::Output);
let check = check_type_for_parameters(&ty, &environment);
assert_eq!(check, (true, false));
}
}

View File

@@ -0,0 +1 @@
{"name":"zerofrom-derive","vers":"0.1.6","deps":[{"name":"proc-macro2","req":"^1.0.61","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"quote","req":"^1.0.28","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"syn","req":"^2.0.21","features":["fold"],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"synstructure","req":"^0.13.0","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false}],"features":{},"features2":null,"cksum":"d3ab4fe26fec702d343e8d7dcb3a59af04cd5d991ccf650c7e71f56362ad7917","yanked":null,"links":null,"rust_version":null,"v":2}

Binary file not shown.