diff --git a/pkg/installer/.cargo/config.toml b/pkg/installer/.cargo/config.toml index 02369289646..bdcd95328d6 100644 --- a/pkg/installer/.cargo/config.toml +++ b/pkg/installer/.cargo/config.toml @@ -2,4 +2,4 @@ replace-with = "vendored-sources" [source.vendored-sources] -directory = "vendor" +directory = "vendor/" diff --git a/pkg/installer/Cargo.lock b/pkg/installer/Cargo.lock index 7126bb3f5e5..d9646419e1e 100644 --- a/pkg/installer/Cargo.lock +++ b/pkg/installer/Cargo.lock @@ -283,7 +283,7 @@ dependencies = [ "ident_case", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.87", ] [[package]] @@ -294,14 +294,14 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.74", + "syn 2.0.87", ] [[package]] name = "deranged" -version = "0.3.11" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" dependencies = [ "powerfmt", ] @@ -323,7 +323,7 @@ checksum = "f282cfdfe92516eb26c2af8589c274c7c17681f5ecc03c18255fe741c6aa64eb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.87", ] [[package]] @@ -344,7 +344,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.87", ] [[package]] @@ -541,9 +541,9 @@ dependencies = [ [[package]] name = "num-conv" -version = "0.1.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" [[package]] name = "num-integer" @@ -757,22 +757,32 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "serde" -version = "1.0.207" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5665e14a49a4ea1b91029ba7d3bca9f299e1f7cfa194388ccc20f14743e784f2" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.207" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aea2634c86b0e8ef2cfdc0c340baede54ec27b1e46febd7f80dffb2aa44a00e" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.87", ] [[package]] @@ -887,9 +897,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.74" +version = "2.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fceb41e3d546d0bd83421d3409b1460cc7444cd389341a4c880fe7a042cb3d7" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" dependencies = [ "proc-macro2", "quote", @@ -907,9 +917,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.36" +version = "0.3.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ "deranged", "itoa", @@ -917,22 +927,22 @@ dependencies = [ "num-conv", "num_threads", "powerfmt", - "serde", + "serde_core", "time-core", "time-macros", ] [[package]] name = "time-core" -version = "0.1.2" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" [[package]] name = "time-macros" -version = "0.2.18" +version = "0.2.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" dependencies = [ "num-conv", "time-core", @@ -996,7 +1006,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.87", "wasm-bindgen-shared", ] @@ -1018,7 +1028,7 @@ checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.87", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -1222,5 +1232,5 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.87", ] diff --git a/pkg/installer/Dockerfile b/pkg/installer/Dockerfile index aa91c3eac2f..1a6159ded15 100644 --- a/pkg/installer/Dockerfile +++ b/pkg/installer/Dockerfile @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # Interactive mode for the installer -FROM --platform=$BUILDPLATFORM lfedge/eve-rust:1.85.1-2 AS rust-host +FROM --platform=$BUILDPLATFORM lfedge/eve-rust:1.93.1 AS rust-host ARG TARGETARCH # map Docker's $TARGETARCH to Rust target diff --git a/pkg/installer/vendor/deranged/.cargo-checksum.json b/pkg/installer/vendor/deranged/.cargo-checksum.json index 84a71bfa005..a8aeef82141 100644 --- a/pkg/installer/vendor/deranged/.cargo-checksum.json +++ b/pkg/installer/vendor/deranged/.cargo-checksum.json @@ -1 +1 @@ -{"files":{".cargo_vcs_info.json":"e59452737395a49fa649614ad4be15946a50fd8d6c11e2e76aa9112cba06c67c","Cargo.toml":"d1ee03b7033e382279ff580d89a70a9aaf163f977400f0899ad9624e24744e6f","Cargo.toml.orig":"1d9113a5d7fbde3a832e62f192098f67f493e26e9cd2b3f8c76c3fe63c6651b5","LICENSE-Apache":"b8929fea28678da67251fb2daf9438f67503814211051861612441806d8edb05","LICENSE-MIT":"04620bf27e4a643dd47bf27652320c205acdb776c1f9f24bb8c3bfaba10804c5","README.md":"fc4c9482d9e5225630da44e5371d6fa3f37220e2f4da2dac076cf4cd4f9592e7","src/lib.rs":"bc4b045c160d6f28726831d83f8389d9231410ae289a99950f63436219488dbb","src/tests.rs":"235e4f158084d12b0bfe85745c444d38bb134ebe584396d0a43154260f6576a7","src/traits.rs":"e3984e763afaa23dcf8ea686b473336472953b05abebc433acb26ab5f2237257","src/unsafe_wrapper.rs":"6e57697c2cd484cd60c1a50c4f4d32cb17526447c0f387d8ea3d89a2a89db688"},"package":"b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4"} \ No newline at end of file +{"files":{".cargo_vcs_info.json":"1ff84e3dd07cfa9cf852b305d813c9faf37630b47b1da1da2b52387cff9200f9","Cargo.lock":"34be0e41ca1808f3e2d06ea2e219f0c7623a67eeef15f9779835bba6de8619df","Cargo.toml":"11c43ed884a6ab8426824a5387a4f06cb4489894b6baf02c0de3410ed5f62646","Cargo.toml.orig":"60931aefce3df7be0efb6c5d619e3913417fb6381cd8d5eacb0b69fabd7459af","LICENSE-Apache":"edd65bdd88957a205c47d53fa499eed8865a70320f0f03f6391668cb304ea376","LICENSE-MIT":"231c837c45eb53f108fb48929e488965bc4fcc14e9ea21d35f50e6b99d98685b","README.md":"fc4c9482d9e5225630da44e5371d6fa3f37220e2f4da2dac076cf4cd4f9592e7","src/lib.rs":"e3b3073e6e4b7a0c1fcb08e4b0872cf39d3951b89d29e283237f3a765da7edbe","src/tests.rs":"875c96ef671c2ed549d1e52f7a077bc8b0659eb7a2e539e58bb64ae6f7135196","src/unsafe_wrapper.rs":"76e67ff03b31f0b97849f0e6c3131f1cb213fc25a11ed259664f48a6901c623e"},"package":"7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"} \ No newline at end of file diff --git a/pkg/installer/vendor/deranged/.cargo_vcs_info.json b/pkg/installer/vendor/deranged/.cargo_vcs_info.json index 707035f1337..69d5b25dd5d 100644 --- a/pkg/installer/vendor/deranged/.cargo_vcs_info.json +++ b/pkg/installer/vendor/deranged/.cargo_vcs_info.json @@ -1,6 +1,6 @@ { "git": { - "sha1": "c25ef2cefe36d92ebf3de6df2faaf293881f7349" + "sha1": "7d0c671e8c806b96d582af197df3c620e09cb33b" }, - "path_in_vcs": "" + "path_in_vcs": "deranged" } \ No newline at end of file diff --git a/pkg/installer/vendor/deranged/Cargo.lock b/pkg/installer/vendor/deranged/Cargo.lock new file mode 100644 index 00000000000..840db3c235c --- /dev/null +++ b/pkg/installer/vendor/deranged/Cargo.lock @@ -0,0 +1,645 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "anyhow" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea" + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "bitflags" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chacha20" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.0", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "deranged" +version = "0.5.8" +dependencies = [ + "deranged-macros", + "num-traits", + "powerfmt", + "quickcheck", + "rand 0.10.0", + "rand 0.8.5", + "rand 0.9.0", + "serde_core", + "serde_json", +] + +[[package]] +name = "deranged-macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8952b6aa444b5338b25807ef3ccfc4082637d28bd77e2305dc60d6cae04af6c1" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "getrandom" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.13.3+wasi-0.2.2", + "windows-targets", +] + +[[package]] +name = "getrandom" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core 0.10.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.170" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875b3680cb2f8f71bdcf9a30f38d48282f5d3c95cbf9b3fa57269bb5d5c06828" + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "num-traits" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quickcheck" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6" +dependencies = [ + "rand 0.8.5", +] + +[[package]] +name = "quote" +version = "1.0.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.2", + "zerocopy", +] + +[[package]] +name = "rand" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8" +dependencies = [ + "chacha20", + "getrandom 0.4.1", + "rand_core 0.10.0", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.2", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.12", +] + +[[package]] +name = "rand_core" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a509b1a2ffbe92afab0e55c8fd99dea1c280e8171bd2d88682bb20bc41cbc2c" +dependencies = [ + "getrandom 0.3.1", + "zerocopy", +] + +[[package]] +name = "rand_core" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba" + +[[package]] +name = "ryu" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[package]] +name = "serde" +version = "1.0.226" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dca6411025b24b60bfa7ec1fe1f8e710ac09782dca409ee8237ba74b51295fd" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.226" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba2ba63999edb9dac981fb34b3e5c0d111a69b0924e253ed29d83f7c99e966a4" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.226" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasi" +version = "0.13.3+wasi-0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" +dependencies = [ + "wit-bindgen-rt", +] + +[[package]] +name = "wasip2" +version = "1.0.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dde3bb8c68a8f3f1ed4ac9221aad6b10cece3e60a8e2ea54a6a2dec806d0084c" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eea57037071898bf96a6da35fd626f4f27e9cee3ead2a6c703cf09d472b2e700" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/pkg/installer/vendor/deranged/Cargo.toml b/pkg/installer/vendor/deranged/Cargo.toml index ff660b538c7..076f32f1d2e 100644 --- a/pkg/installer/vendor/deranged/Cargo.toml +++ b/pkg/installer/vendor/deranged/Cargo.toml @@ -11,15 +11,21 @@ [package] edition = "2021" -rust-version = "1.67.0" +rust-version = "1.85.0" name = "deranged" -version = "0.3.11" +version = "0.5.8" authors = ["Jacob Pratt "] +build = false include = [ "src/**/*", "LICENSE-*", "README.md", ] +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false description = "Ranged integers" readme = "README.md" keywords = [ @@ -32,11 +38,39 @@ repository = "https://github.com/jhpratt/deranged" [package.metadata.docs.rs] all-features = true +targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = [ - "--cfg", - "docs_rs", + "--generate-link-to-definition", + "--generate-macro-expansion", ] -targets = ["x86_64-unknown-linux-gnu"] + +[features] +alloc = [] +default = [] +macros = ["dep:deranged-macros"] +num = ["dep:num-traits"] +powerfmt = ["dep:powerfmt"] +quickcheck = [ + "dep:quickcheck", + "alloc", +] +rand = [ + "rand08", + "rand09", + "rand010", +] +rand010 = ["dep:rand010"] +rand08 = ["dep:rand08"] +rand09 = ["dep:rand09"] +serde = ["dep:serde_core"] + +[lib] +name = "deranged" +path = "src/lib.rs" + +[dependencies.deranged-macros] +version = "=0.3.0" +optional = true [dependencies.num-traits] version = "0.2.15" @@ -53,31 +87,131 @@ version = "1.0.3" optional = true default-features = false -[dependencies.rand] +[dependencies.rand010] +version = "0.10.0" +optional = true +default-features = false +package = "rand" + +[dependencies.rand08] version = "0.8.4" optional = true default-features = false +package = "rand" -[dependencies.serde] -version = "1.0.126" +[dependencies.rand09] +version = "0.9.0" optional = true default-features = false +package = "rand" -[dev-dependencies.rand] +[dependencies.serde_core] +version = "1.0.220" +optional = true +default-features = false + +[dev-dependencies.rand010] +version = "0.10.0" +package = "rand" + +[dev-dependencies.rand08] version = "0.8.4" +package = "rand" + +[dev-dependencies.rand09] +version = "0.9.0" +package = "rand" [dev-dependencies.serde_json] version = "1.0.86" -[features] -alloc = [] -default = ["std"] -num = ["dep:num-traits"] -powerfmt = ["dep:powerfmt"] -quickcheck = [ - "dep:quickcheck", - "alloc", -] -rand = ["dep:rand"] -serde = ["dep:serde"] -std = ["alloc"] +[lints.clippy] +alloc-instead-of-core = "deny" +dbg-macro = "warn" +decimal-literal-representation = "warn" +explicit-auto-deref = "warn" +get-unwrap = "warn" +manual-let-else = "warn" +missing-docs-in-private-items = "warn" +missing-enforced-import-renames = "warn" +obfuscated-if-else = "warn" +option-if-let-else = "allow" +print-stdout = "warn" +redundant-pub-crate = "allow" +semicolon-outside-block = "warn" +std-instead-of-core = "deny" +todo = "warn" +undocumented-unsafe-blocks = "deny" +unimplemented = "warn" +uninlined-format-args = "warn" +unnested-or-patterns = "warn" +unwrap-in-result = "warn" +unwrap-used = "warn" +use-debug = "warn" + +[lints.clippy.all] +level = "warn" +priority = -1 + +[lints.clippy.nursery] +level = "warn" +priority = -1 + +[lints.rust] +ambiguous-glob-reexports = "deny" +clashing-extern-declarations = "deny" +const-item-mutation = "deny" +dangling-pointers-from-temporaries = "deny" +deref-nullptr = "deny" +drop-bounds = "deny" +future-incompatible = "deny" +hidden-glob-reexports = "deny" +improper-ctypes = "deny" +improper-ctypes-definitions = "deny" +invalid-from-utf8 = "deny" +invalid-macro-export-arguments = "deny" +invalid-nan-comparisons = "deny" +invalid-reference-casting = "deny" +invalid-value = "deny" +keyword-idents = "warn" +let-underscore = "warn" +macro-use-extern-crate = "warn" +meta-variable-misuse = "warn" +missing-abi = "warn" +missing-copy-implementations = "warn" +missing-debug-implementations = "warn" +missing-docs = "warn" +named-arguments-used-positionally = "deny" +non-ascii-idents = "deny" +noop-method-call = "warn" +opaque-hidden-inferred-bound = "deny" +overlapping-range-endpoints = "deny" +single-use-lifetimes = "warn" +suspicious-double-ref-op = "deny" +trivial-casts = "warn" +trivial-numeric-casts = "warn" +unconditional-recursion = "deny" +unnameable-test-items = "deny" +unreachable-pub = "warn" +unsafe-op-in-unsafe-fn = "deny" +unstable-syntax-pre-expansion = "deny" +unused-import-braces = "warn" +unused-lifetimes = "warn" +unused-qualifications = "warn" +variant-size-differences = "warn" + +[lints.rust.path-statements] +level = "allow" +priority = 1 + +[lints.rust.unstable-name-collisions] +level = "warn" +priority = 1 + +[lints.rust.unused] +level = "warn" +priority = -1 + +[lints.rustdoc] +private-doc-tests = "warn" +unescaped-backticks = "warn" diff --git a/pkg/installer/vendor/deranged/Cargo.toml.orig b/pkg/installer/vendor/deranged/Cargo.toml.orig index dc46b028542..bc8d4474024 100644 --- a/pkg/installer/vendor/deranged/Cargo.toml.orig +++ b/pkg/installer/vendor/deranged/Cargo.toml.orig @@ -1,38 +1,49 @@ [package] name = "deranged" -version = "0.3.11" +version = "0.5.8" authors = ["Jacob Pratt "] edition = "2021" -rust-version = "1.67.0" +rust-version = "1.85.0" repository = "https://github.com/jhpratt/deranged" keywords = ["integer", "int", "range"] -readme = "README.md" +readme = "../README.md" license = "MIT OR Apache-2.0" description = "Ranged integers" include = ["src/**/*", "LICENSE-*", "README.md"] [features] -default = ["std"] +default = [] alloc = [] +macros = ["dep:deranged-macros"] num = ["dep:num-traits"] powerfmt = ["dep:powerfmt"] quickcheck = ["dep:quickcheck", "alloc"] -rand = ["dep:rand"] -serde = ["dep:serde"] -std = ["alloc"] +rand = ["rand08", "rand09", "rand010"] +rand08 = ["dep:rand08"] +rand09 = ["dep:rand09"] +rand010 = ["dep:rand010"] +serde = ["dep:serde_core"] + +[lints] +workspace = true [package.metadata.docs.rs] all-features = true targets = ["x86_64-unknown-linux-gnu"] -rustdoc-args = ["--cfg", "docs_rs"] +rustdoc-args = ["--generate-link-to-definition", "--generate-macro-expansion"] [dependencies] +deranged-macros = { workspace = true, optional = true } num-traits = { version = "0.2.15", optional = true, default-features = false } powerfmt = { version = "0.2.0", optional = true, default-features = false } quickcheck = { version = "1.0.3", default-features = false, optional = true } -rand = { version = "0.8.4", optional = true, default-features = false } -serde = { version = "1.0.126", optional = true, default-features = false } +rand08 = { package = "rand", version = "0.8.4", optional = true, default-features = false } +rand09 = { package = "rand", version = "0.9.0", optional = true, default-features = false } +rand010 = { package = "rand", version = "0.10.0", optional = true, default-features = false } +serde_core = { version = "1.0.220", optional = true, default-features = false } [dev-dependencies] -rand = "0.8.4" +rand08 = { package = "rand", version = "0.8.4" } +rand09 = { package = "rand", version = "0.9.0" } +rand010 = { package = "rand", version = "0.10.0" } serde_json = "1.0.86" diff --git a/pkg/installer/vendor/deranged/LICENSE-Apache b/pkg/installer/vendor/deranged/LICENSE-Apache index 7646f21e37e..c763a0c9dea 100644 --- a/pkg/installer/vendor/deranged/LICENSE-Apache +++ b/pkg/installer/vendor/deranged/LICENSE-Apache @@ -187,7 +187,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2022 Jacob Pratt et al. + Copyright 2024 Jacob Pratt et al. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/pkg/installer/vendor/deranged/LICENSE-MIT b/pkg/installer/vendor/deranged/LICENSE-MIT index a11a755732c..5cc097f1c02 100644 --- a/pkg/installer/vendor/deranged/LICENSE-MIT +++ b/pkg/installer/vendor/deranged/LICENSE-MIT @@ -1,4 +1,4 @@ -Copyright (c) 2022 Jacob Pratt et al. +Copyright (c) 2024 Jacob Pratt et al. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/pkg/installer/vendor/deranged/src/lib.rs b/pkg/installer/vendor/deranged/src/lib.rs index aee3ea99f6c..105cbba703d 100644 --- a/pkg/installer/vendor/deranged/src/lib.rs +++ b/pkg/installer/vendor/deranged/src/lib.rs @@ -1,67 +1,80 @@ -#![cfg_attr(docs_rs, feature(doc_auto_cfg))] -#![cfg_attr(not(feature = "std"), no_std)] -#![deny( - anonymous_parameters, - clippy::all, - clippy::missing_safety_doc, - clippy::missing_safety_doc, - clippy::undocumented_unsafe_blocks, - illegal_floating_point_literal_pattern, - late_bound_lifetime_arguments, - patterns_in_fns_without_body, - rust_2018_idioms, - trivial_casts, - trivial_numeric_casts, - unreachable_pub, - unsafe_op_in_unsafe_fn, - unused_extern_crates -)] -#![warn( - clippy::dbg_macro, - clippy::decimal_literal_representation, - clippy::get_unwrap, - clippy::nursery, - clippy::pedantic, - clippy::todo, - clippy::unimplemented, - clippy::unwrap_used, - clippy::use_debug, - missing_copy_implementations, - missing_debug_implementations, - unused_qualifications, - variant_size_differences -)] -#![allow( - path_statements, // used for static assertions - clippy::inline_always, - clippy::missing_errors_doc, - clippy::must_use_candidate, - clippy::redundant_pub_crate, -)] +//! `deranged` is a proof-of-concept implementation of ranged integers. + +#![cfg_attr(docsrs, feature(doc_cfg))] +#![no_std] #![doc(test(attr(deny(warnings))))] +#[cfg(all(feature = "alloc", any(feature = "serde", feature = "quickcheck")))] +extern crate alloc; + #[cfg(test)] mod tests; -mod traits; mod unsafe_wrapper; -#[cfg(feature = "alloc")] -#[allow(unused_extern_crates)] -extern crate alloc; - use core::borrow::Borrow; use core::cmp::Ordering; +use core::error::Error; use core::fmt; -use core::num::IntErrorKind; +use core::hint::assert_unchecked; +use core::num::{IntErrorKind, NonZero}; use core::str::FromStr; -#[cfg(feature = "std")] -use std::error::Error; +/// A macro to define a ranged integer with an automatically computed inner type. +/// +/// The minimum and maximum values are provided as integer literals, and the macro will compute an +/// appropriate inner type to represent the range. This will be the smallest integer type that can +/// store both the minimum and maximum values, with a preference for unsigned types if both are +/// possible. To specifically request a signed or unsigned type, you can append a `i` or `u` suffix +/// to either or both of the minimum and maximum values, respectively. +/// +/// # Examples +/// +/// ```rust,ignore +/// int!(0, 100); // RangedU8<0, 100> +/// int!(0i, 100); // RangedI8<0, 100> +/// int!(-5, 5); // RangedI8<-5, 5> +/// int!(-5u, 5); // compile error (-5 cannot be unsigned) +/// ``` +#[cfg(docsrs)] +#[doc(cfg(feature = "macros"))] +#[macro_export] +macro_rules! int { + ($min:literal, $max:literal) => {}; +} + +/// A macro to define an optional ranged integer with an automatically computed inner type. +/// +/// The minimum and maximum values are provided as integer literals, and the macro will compute an +/// appropriate inner type to represent the range. This will be the smallest integer type that can +/// store both the minimum and maximum values, with a preference for unsigned types if both are +/// possible. To specifically request a signed or unsigned type, you can append a `i` or `u` suffix +/// to either or both of the minimum and maximum values, respectively. +/// +/// # Examples +/// +/// ```rust,ignore +/// opt_int!(0, 100); // OptionRangedU8<0, 100> +/// opt_int!(0i, 100); // OptionRangedI8<0, 100> +/// opt_int!(-5, 5); // OptionRangedI8<-5, 5> +/// opt_int!(-5u, 5); // compile error (-5 cannot be unsigned) +/// ``` +#[cfg(docsrs)] +#[doc(cfg(feature = "macros"))] +#[macro_export] +macro_rules! opt_int { + ($min:literal, $max:literal) => {}; +} + +#[cfg(all(not(docsrs), feature = "macros"))] +pub use deranged_macros::int; +#[cfg(all(not(docsrs), feature = "macros"))] +pub use deranged_macros::opt_int; #[cfg(feature = "powerfmt")] use powerfmt::smart_display; use crate::unsafe_wrapper::Unsafe; +/// The error type returned when a checked integral type conversion fails. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TryFromIntError; @@ -71,11 +84,31 @@ impl fmt::Display for TryFromIntError { f.write_str("out of range integral type conversion attempted") } } -#[cfg(feature = "std")] impl Error for TryFromIntError {} +/// An error which can be returned when parsing an integer. +/// +/// This error is used as the error type for the `from_str_radix()` functions on ranged integer +/// types, such as [`RangedI8::from_str_radix`]. +/// +/// # Potential causes +/// +/// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace +/// in the string e.g., when it is obtained from the standard input. +/// Using the [`str::trim()`] method ensures that no whitespace remains before parsing. +/// +/// # Example +/// +/// ```rust +/// # use deranged::RangedI32; +/// if let Err(e) = RangedI32::<0, 10>::from_str_radix("a12", 10) { +/// println!("Failed conversion to RangedI32: {e}"); +/// } +/// ``` +#[allow(missing_copy_implementations)] // same as `std` #[derive(Debug, Clone, PartialEq, Eq)] pub struct ParseIntError { + #[allow(clippy::missing_docs_in_private_items)] kind: IntErrorKind, } @@ -90,6 +123,7 @@ impl ParseIntError { } impl fmt::Display for ParseIntError { + #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.kind { IntErrorKind::Empty => "cannot parse integer from empty string", @@ -103,9 +137,9 @@ impl fmt::Display for ParseIntError { } } -#[cfg(feature = "std")] impl Error for ParseIntError {} +/// `?` for `Option` types, usable in `const` contexts. macro_rules! const_try_opt { ($e:expr) => { match $e { @@ -115,16 +149,19 @@ macro_rules! const_try_opt { }; } +/// Output the given tokens if the type is signed, otherwise output nothing. macro_rules! if_signed { (true $($x:tt)*) => { $($x)*}; (false $($x:tt)*) => {}; } +/// Output the given tokens if the type is unsigned, otherwise output nothing. macro_rules! if_unsigned { (true $($x:tt)*) => {}; (false $($x:tt)*) => { $($x)* }; } +/// `"A"` if `true`, `"An"` if `false`. macro_rules! article { (true) => { "An" @@ -134,42 +171,54 @@ macro_rules! article { }; } -macro_rules! unsafe_unwrap_unchecked { - ($e:expr) => {{ - let opt = $e; - debug_assert!(opt.is_some()); - match $e { - Some(value) => value, - None => core::hint::unreachable_unchecked(), - } - }}; +/// Output the provided code if and only if the list does not include `rand_09`. +#[allow(unused_macro_rules)] +macro_rules! if_not_manual_rand_09 { + ([rand_09 $($rest:ident)*] $($output:tt)*) => {}; + ([] $($output:tt)*) => { + $($output)* + }; + ([$first:ident $($rest:ident)*] $($output:tt)*) => { + if_not_manual_rand_09!([$($rest)*] $($output)*); + }; } -/// Informs the optimizer that a condition is always true. If the condition is false, the behavior -/// is undefined. -/// -/// # Safety -/// -/// `b` must be `true`. -#[inline] -const unsafe fn assume(b: bool) { - debug_assert!(b); - if !b { - // Safety: The caller must ensure that `b` is true. - unsafe { core::hint::unreachable_unchecked() } - } +/// Output the provided code if and only if the list does not include `rand_010`. +#[allow(unused_macro_rules)] +macro_rules! if_not_manual_rand_010 { + ([rand_010 $($rest:ident)*] $($output:tt)*) => {}; + ([] $($output:tt)*) => { + $($output)* + }; + ([$first:ident $($rest:ident)*] $($output:tt)*) => { + if_not_manual_rand_010!([$($rest)*] $($output)*); + }; } +/// Implement a ranged integer type. macro_rules! impl_ranged { ($( $type:ident { mod_name: $mod_name:ident + alias: $alias:ident internal: $internal:ident signed: $is_signed:ident unsigned: $unsigned_type:ident optional: $optional_type:ident + optional_alias: $optional_alias:ident + from: [$($from:ident($from_internal:ident))+] + $(manual: [$($skips:ident)+])? } )*) => {$( + #[doc = concat!("Equivalent to `", stringify!($type), "`")] + #[expect(non_camel_case_types, reason = "symmetry with primitives")] + pub type $alias = $type; + + #[doc = concat!("Equivalent to `", stringify!($optional_type), "`")] + #[expect(non_camel_case_types, reason = "closest visually to `Option`")] + pub type $optional_alias + = $optional_type; + #[doc = concat!( article!($is_signed), " `", @@ -183,11 +232,11 @@ macro_rules! impl_ranged { ); #[doc = concat!( - "A `", + "An optional `", stringify!($type), - "` that is optional. Equivalent to [`Option<", + "`; similar to `Option<", stringify!($type), - ">`] with niche value optimization.", + ">` with better optimization.", )] /// #[doc = concat!( @@ -211,6 +260,7 @@ macro_rules! impl_ranged { ); impl $type<0, 0> { + #[doc = concat!("A ", stringify!($type), " that is always `VALUE`.")] #[inline(always)] pub const fn exact() -> $type { // Safety: The value is the only one in range. @@ -218,6 +268,23 @@ macro_rules! impl_ranged { } } + if_unsigned! { $is_signed + impl $type<1, { $internal::MAX }> { + /// Creates a ranged integer from a non-zero value. + #[inline(always)] + pub const fn from_nonzero(value: NonZero<$internal>) -> Self { + // Safety: The value is non-zero, so it is in range. + unsafe { Self::new_unchecked(value.get()) } + } + + /// Creates a non-zero value from a ranged integer. + #[inline(always)] + pub const fn to_nonzero(self) -> NonZero<$internal> { + // Safety: The value is in range, so it is non-zero. + unsafe { NonZero::new_unchecked(self.get()) } + } + }} + impl $type { /// The smallest value that can be represented by this type. // Safety: `MIN` is in range by definition. @@ -232,38 +299,58 @@ macro_rules! impl_ranged { /// # Safety /// /// The value must be within the range `MIN..=MAX`. + #[track_caller] #[inline(always)] pub const unsafe fn new_unchecked(value: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the value is in range. unsafe { - $crate::assume(MIN <= value && value <= MAX); + assert_unchecked(MIN <= value && value <= MAX); Self(Unsafe::new(value)) } } /// Returns the value as a primitive type. + /// + /// A call to this function will output a hint to the compiler that the value is in + /// range. In general this will help the optimizer to generate better code, but in edge + /// cases this may lead to worse code generation. To avoid outputting the hint, you can + #[doc = concat!("use [`", stringify!($type), "::get_without_hint`].")] + #[track_caller] #[inline(always)] pub const fn get(self) -> $internal { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: A stored value is always in range. - unsafe { $crate::assume(MIN <= *self.0.get() && *self.0.get() <= MAX) }; + unsafe { assert_unchecked(MIN <= *self.0.get() && *self.0.get() <= MAX) }; *self.0.get() } + /// Returns the value as a primitive type. + /// + #[doc = concat!("The returned value is identical to [`", stringify!($type), "::get`].")] + /// Unlike `get`, no hints are output to the compiler indicating the range that the + /// value is in. Depending on the scenario, this may with be helpful or harmful to + /// optimization. + #[inline(always)] + pub const fn get_without_hint(self) -> $internal { + const { assert!(MIN <= MAX); } + *self.0.get() + } + + #[track_caller] #[inline(always)] pub(crate) const fn get_ref(&self) -> &$internal { - ::ASSERT; + const { assert!(MIN <= MAX); } let value = self.0.get(); // Safety: A stored value is always in range. - unsafe { $crate::assume(MIN <= *value && *value <= MAX) }; + unsafe { assert_unchecked(MIN <= *value && *value <= MAX) }; value } /// Creates a ranged integer if the given value is in the range `MIN..=MAX`. #[inline(always)] pub const fn new(value: $internal) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } if value < MIN || value > MAX { None } else { @@ -276,7 +363,10 @@ macro_rules! impl_ranged { /// value is not in range. #[inline(always)] pub const fn new_static() -> Self { - <($type, $type) as $crate::traits::StaticIsValid>::ASSERT; + const { + assert!(MIN <= VALUE); + assert!(VALUE <= MAX); + } // Safety: The value is in range. unsafe { Self::new_unchecked(VALUE) } } @@ -284,7 +374,7 @@ macro_rules! impl_ranged { /// Creates a ranged integer with the given value, saturating if it is out of range. #[inline] pub const fn new_saturating(value: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } if value < MIN { Self::MIN } else if value > MAX { @@ -295,15 +385,36 @@ macro_rules! impl_ranged { } } + /// Emit a hint to the compiler that the value is in range. + /// + /// In some situations, this can help the optimizer to generate better code. In edge + /// cases this may lead to **worse** code generation. If you are unsure whether this is + /// helpful, harmful, or neutral, you should use [`cargo-show-asm`] to compare the + /// generated assembly. + /// + /// Aside from potentially affecting optimization, this function is a no-op. + /// + /// [`cargo-show-asm`]: https://crates.io/crates/cargo-show-asm + #[inline(always)] + pub const fn emit_range_hint(self) { + const { assert!(MIN <= MAX); } + let value = self.0.get(); + // Safety: A stored value is always in range. + unsafe { assert_unchecked(MIN <= *value && *value <= MAX) }; + } + /// Expand the range that the value may be in. **Fails to compile** if the new range is /// not a superset of the current range. + #[inline(always)] pub const fn expand( self, ) -> $type { - <$type as $crate::traits::RangeIsValid>::ASSERT; - <$type as $crate::traits::RangeIsValid>::ASSERT; - <($type, $type) as $crate::traits::ExpandIsValid> - ::ASSERT; + const { + assert!(MIN <= MAX); + assert!(NEW_MIN <= NEW_MAX); + assert!(NEW_MIN <= MIN); + assert!(NEW_MAX >= MAX); + } // Safety: The range is widened. unsafe { $type::new_unchecked(self.get()) } } @@ -311,17 +422,41 @@ macro_rules! impl_ranged { /// Attempt to narrow the range that the value may be in. Returns `None` if the value /// is outside the new range. **Fails to compile** if the new range is not a subset of /// the current range. + #[inline(always)] pub const fn narrow< const NEW_MIN: $internal, const NEW_MAX: $internal, >(self) -> Option<$type> { - <$type as $crate::traits::RangeIsValid>::ASSERT; - <$type as $crate::traits::RangeIsValid>::ASSERT; - <($type, $type) as $crate::traits::NarrowIsValid> - ::ASSERT; + const { + assert!(MIN <= MAX); + assert!(NEW_MIN <= NEW_MAX); + assert!(NEW_MIN >= MIN); + assert!(NEW_MAX <= MAX); + } $type::::new(self.get()) } + /// Narrow the range that the value may be in. **Fails to compile** if the new range is + /// not a subset of the current range. + /// + /// # Safety + /// + /// The value must in the range `NEW_MIN..=NEW_MAX`. + #[inline(always)] + pub const unsafe fn narrow_unchecked< + const NEW_MIN: $internal, + const NEW_MAX: $internal, + >(self) -> $type { + const { + assert!(MIN <= MAX); + assert!(NEW_MIN <= NEW_MAX); + assert!(NEW_MIN >= MIN); + assert!(NEW_MAX <= MAX); + } + // Safety: The caller must ensure that the value is in the new range. + unsafe { $type::new_unchecked(self.get()) } + } + /// Converts a string slice in a given base to an integer. /// /// The string is expected to be an optional `+` or `-` sign followed by digits. Leading @@ -352,7 +487,7 @@ macro_rules! impl_ranged { /// ``` #[inline] pub fn from_str_radix(src: &str, radix: u32) -> Result { - ::ASSERT; + const { assert!(MIN <= MAX); } match $internal::from_str_radix(src, radix) { Ok(value) if value > MAX => { Err(ParseIntError { kind: IntErrorKind::PosOverflow }) @@ -372,7 +507,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_add(self, rhs: $internal) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_add(rhs))) } @@ -383,12 +518,13 @@ macro_rules! impl_ranged { /// /// The result of `self + rhs` must be in the range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_add(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range. unsafe { - Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_add(rhs))) + Self::new_unchecked(self.get().unchecked_add(rhs)) } } @@ -397,7 +533,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_sub(self, rhs: $internal) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_sub(rhs))) } @@ -408,12 +544,13 @@ macro_rules! impl_ranged { /// /// The result of `self - rhs` must be in the range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_sub(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range. unsafe { - Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_sub(rhs))) + Self::new_unchecked(self.get().unchecked_sub(rhs)) } } @@ -422,7 +559,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_mul(self, rhs: $internal) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_mul(rhs))) } @@ -433,12 +570,13 @@ macro_rules! impl_ranged { /// /// The result of `self * rhs` must be in the range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_mul(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range. unsafe { - Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_mul(rhs))) + Self::new_unchecked(self.get().unchecked_mul(rhs)) } } @@ -447,7 +585,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_div(self, rhs: $internal) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_div(rhs))) } @@ -459,13 +597,14 @@ macro_rules! impl_ranged { /// `self` must not be zero and the result of `self / rhs` must be in the range /// `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_div(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range and that `rhs` is not // zero. unsafe { - Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_div(rhs))) + Self::new_unchecked(self.get().checked_div(rhs).unwrap_unchecked()) } } @@ -474,7 +613,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_div_euclid(self, rhs: $internal) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_div_euclid(rhs))) } @@ -486,14 +625,15 @@ macro_rules! impl_ranged { /// `self` must not be zero and the result of `self.div_euclid(rhs)` must be in the /// range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_div_euclid(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range and that `rhs` is not // zero. unsafe { Self::new_unchecked( - unsafe_unwrap_unchecked!(self.get().checked_div_euclid(rhs)) + self.get().checked_div_euclid(rhs).unwrap_unchecked() ) } } @@ -502,12 +642,13 @@ macro_rules! impl_ranged { /// Remainder. Computes `self % rhs`, statically guaranteeing that the returned value /// is in range. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline] pub const fn rem( self, rhs: $type, ) -> $type<0, RHS_VALUE> { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The result is guaranteed to be in range due to the nature of remainder on // unsigned integers. unsafe { $type::new_unchecked(self.get() % rhs.get()) } @@ -518,7 +659,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_rem(self, rhs: $internal) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_rem(rhs))) } @@ -530,13 +671,14 @@ macro_rules! impl_ranged { /// `self` must not be zero and the result of `self % rhs` must be in the range /// `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_rem(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range and that `rhs` is not // zero. unsafe { - Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_rem(rhs))) + Self::new_unchecked(self.get().checked_rem(rhs).unwrap_unchecked()) } } @@ -545,7 +687,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_rem_euclid(self, rhs: $internal) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_rem_euclid(rhs))) } @@ -557,14 +699,15 @@ macro_rules! impl_ranged { /// `self` must not be zero and the result of `self.rem_euclid(rhs)` must be in the /// range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_rem_euclid(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range and that `rhs` is not // zero. unsafe { Self::new_unchecked( - unsafe_unwrap_unchecked!(self.get().checked_rem_euclid(rhs)) + self.get().checked_rem_euclid(rhs).unwrap_unchecked() ) } } @@ -574,7 +717,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_neg(self) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_neg())) } @@ -584,11 +727,13 @@ macro_rules! impl_ranged { /// /// The result of `-self` must be in the range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_neg(self) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range. - unsafe { Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_neg())) } + // TODO(MSRV 1.93) use `unchecked_neg` + unsafe { Self::new_unchecked(self.get().checked_neg().unwrap_unchecked()) } } /// Negation. Computes `self.neg()`, **failing to compile** if the result is not @@ -596,8 +741,17 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline(always)] pub const fn neg(self) -> Self { - ::ASSERT; - ::ASSERT; + const { + assert!(MIN <= MAX); + if_signed! { $is_signed + assert!(MIN != $internal::MIN); + assert!(-MIN <= MAX); + assert!(-MAX >= MIN); + } + if_unsigned! { $is_signed + assert!(MAX == 0); + } + } // Safety: The compiler asserts that the result is in range. unsafe { self.unchecked_neg() } } @@ -607,7 +761,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_shl(self, rhs: u32) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_shl(rhs))) } @@ -617,12 +771,14 @@ macro_rules! impl_ranged { /// /// The result of `self << rhs` must be in the range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range. unsafe { - Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_shl(rhs))) + // TOD(MSRV 1.93) use `unchecked_shl` + Self::new_unchecked(self.get().checked_shl(rhs).unwrap_unchecked()) } } @@ -631,7 +787,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_shr(self, rhs: u32) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_shr(rhs))) } @@ -641,12 +797,14 @@ macro_rules! impl_ranged { /// /// The result of `self >> rhs` must be in the range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range. unsafe { - Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_shr(rhs))) + // TODO(MSRV 1.93) use `unchecked_shr` + Self::new_unchecked(self.get().checked_shr(rhs).unwrap_unchecked()) } } @@ -656,7 +814,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_abs(self) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_abs())) } @@ -667,11 +825,12 @@ macro_rules! impl_ranged { /// /// The result of `self.abs()` must be in the range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_abs(self) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range. - unsafe { Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_abs())) } + unsafe { Self::new_unchecked(self.get().checked_abs().unwrap_unchecked()) } } /// Absolute value. Computes `self.abs()`, **failing to compile** if the result is not @@ -679,8 +838,12 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline(always)] pub const fn abs(self) -> Self { - ::ASSERT; - ::ASSERT; + const { + assert!(MIN <= MAX); + assert!(MIN != $internal::MIN); + assert!(-MIN <= MAX); + } + // ::ASSERT; // Safety: The compiler asserts that the result is in range. unsafe { self.unchecked_abs() } }); @@ -690,7 +853,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn checked_pow(self, exp: u32) -> Option { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(const_try_opt!(self.get().checked_pow(exp))) } @@ -701,12 +864,13 @@ macro_rules! impl_ranged { /// /// The result of `self.pow(exp)` must be in the range `MIN..=MAX`. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline(always)] pub const unsafe fn unchecked_pow(self, exp: u32) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the result is in range. unsafe { - Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_pow(exp))) + Self::new_unchecked(self.get().checked_pow(exp).unwrap_unchecked()) } } @@ -715,7 +879,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn saturating_add(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new_saturating(self.get().saturating_add(rhs)) } @@ -724,7 +888,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn saturating_sub(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new_saturating(self.get().saturating_sub(rhs)) } @@ -734,7 +898,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn saturating_neg(self) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new_saturating(self.get().saturating_neg()) }); @@ -743,7 +907,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn saturating_abs(self) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new_saturating(self.get().saturating_abs()) }); @@ -752,7 +916,7 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn saturating_mul(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new_saturating(self.get().saturating_mul(rhs)) } @@ -761,15 +925,33 @@ macro_rules! impl_ranged { #[must_use = "this returns the result of the operation, without modifying the original"] #[inline] pub const fn saturating_pow(self, exp: u32) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new_saturating(self.get().saturating_pow(exp)) } + if_signed! { $is_signed + /// Returns `true` if the number is positive and `false` if the number is zero or + /// negative. + #[inline] + pub const fn is_positive(self) -> bool { + const { assert!(MIN <= MAX); } + self.get().is_positive() + } + + /// Returns `true` if the number is negative and `false` if the number is zero or + /// positive. + #[inline] + pub const fn is_negative(self) -> bool { + const { assert!(MIN <= MAX); } + self.get().is_negative() + } + } + /// Compute the `rem_euclid` of this type with its unsigned type equivalent // Not public because it doesn't match stdlib's "method_unsigned implemented only for signed type" tradition. // Also because this isn't implemented for normal types in std. - // TODO maybe make public anyway? It is useful. #[must_use = "this returns the result of the operation, without modifying the original"] + #[track_caller] #[inline] #[allow(trivial_numeric_casts)] // needed since some casts have to send unsigned -> unsigned to handle signed -> unsigned const fn rem_euclid_unsigned( @@ -800,7 +982,7 @@ macro_rules! impl_ranged { #[inline] #[allow(trivial_numeric_casts)] // needed since some casts have to send unsigned -> unsigned to handle signed -> unsigned pub const fn wrapping_add(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Forward to internal type's impl if same as type. if MIN == $internal::MIN && MAX == $internal::MAX { // Safety: std's wrapping methods match ranged arithmetic when the range is the internal datatype's range. @@ -850,7 +1032,7 @@ macro_rules! impl_ranged { #[inline] #[allow(trivial_numeric_casts)] // needed since some casts have to send unsigned -> unsigned to handle signed -> unsigned pub const fn wrapping_sub(self, rhs: $internal) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Forward to internal type's impl if same as type. if MIN == $internal::MIN && MAX == $internal::MAX { // Safety: std's wrapping methods match ranged arithmetic when the range is the internal datatype's range. @@ -911,14 +1093,14 @@ macro_rules! impl_ranged { #[allow(non_snake_case)] #[inline(always)] pub const fn Some(value: $type) -> Self { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } Self(value.get()) } /// Returns the value as the standard library's [`Option`] type. #[inline(always)] pub const fn get(self) -> Option<$type> { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } if self.0 == Self::NICHE { None } else { @@ -935,37 +1117,61 @@ macro_rules! impl_ranged { /// value optimization is unspecified, the provided value must not be the niche /// value. #[inline(always)] + #[track_caller] pub const unsafe fn some_unchecked(value: $internal) -> Self { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The caller must ensure that the value is in range. - unsafe { $crate::assume(MIN <= value && value <= MAX) }; + unsafe { assert_unchecked(MIN <= value && value <= MAX) }; Self(value) } /// Obtain the inner value of the struct. This is useful for comparisons. #[inline(always)] pub(crate) const fn inner(self) -> $internal { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } self.0 } + /// Obtain the value of the struct as an `Option` of the primitive type. + /// + /// A call to this function will output a hint to the compiler that the value is in + /// range. In general this will help the optimizer to generate better code, but in edge + /// cases this may lead to worse code generation. To avoid outputting the hint, you can + #[doc = concat!( + "use [`", stringify!($optional_type), "::get_primitive_without_hint`]." + )] #[inline(always)] pub const fn get_primitive(self) -> Option<$internal> { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } Some(const_try_opt!(self.get()).get()) } + /// Obtain the value of the struct as an `Option` of the primitive type. + /// + #[doc = concat!( + "The returned value is identical to [`", stringify!($optional_type), "::", + "get_primitive`]." + )] + /// Unlike `get_primitive`, no hints are output to the compiler indicating the range + /// that the value is in. Depending on the scenario, this may with be helpful or harmful + /// to optimization. + #[inline(always)] + pub const fn get_primitive_without_hint(self) -> Option<$internal> { + const { assert!(MIN <= MAX); } + Some(const_try_opt!(self.get()).get_without_hint()) + } + /// Returns `true` if the value is the niche value. #[inline(always)] - pub const fn is_none(self) -> bool { - <$type as $crate::traits::RangeIsValid>::ASSERT; + pub const fn is_none(&self) -> bool { + const { assert!(MIN <= MAX); } self.get().is_none() } /// Returns `true` if the value is not the niche value. #[inline(always)] - pub const fn is_some(self) -> bool { - <$type as $crate::traits::RangeIsValid>::ASSERT; + pub const fn is_some(&self) -> bool { + const { assert!(MIN <= MAX); } self.get().is_some() } } @@ -973,7 +1179,7 @@ macro_rules! impl_ranged { impl fmt::Debug for $type { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt(f) } } @@ -981,7 +1187,7 @@ macro_rules! impl_ranged { impl fmt::Debug for $optional_type { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt(f) } } @@ -989,7 +1195,7 @@ macro_rules! impl_ranged { impl fmt::Display for $type { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt(f) } } @@ -1006,7 +1212,7 @@ macro_rules! impl_ranged { &self, f: smart_display::FormatterOptions, ) -> smart_display::Metadata<'_, Self> { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get_ref().metadata(f).reuse() } @@ -1016,7 +1222,7 @@ macro_rules! impl_ranged { f: &mut fmt::Formatter<'_>, metadata: smart_display::Metadata<'_, Self>, ) -> fmt::Result { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt_with_metadata(f, metadata.reuse()) } } @@ -1024,7 +1230,7 @@ macro_rules! impl_ranged { impl Default for $optional_type { #[inline(always)] fn default() -> Self { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } Self::None } } @@ -1032,7 +1238,7 @@ macro_rules! impl_ranged { impl AsRef<$internal> for $type { #[inline(always)] fn as_ref(&self) -> &$internal { - ::ASSERT; + const { assert!(MIN <= MAX); } &self.get_ref() } } @@ -1040,7 +1246,7 @@ macro_rules! impl_ranged { impl Borrow<$internal> for $type { #[inline(always)] fn borrow(&self) -> &$internal { - ::ASSERT; + const { assert!(MIN <= MAX); } &self.get_ref() } } @@ -1053,8 +1259,10 @@ macro_rules! impl_ranged { > PartialEq<$type> for $type { #[inline(always)] fn eq(&self, other: &$type) -> bool { - ::ASSERT; - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { + assert!(MIN_A <= MAX_A); + assert!(MIN_B <= MAX_B); + } self.get() == other.get() } } @@ -1067,8 +1275,10 @@ macro_rules! impl_ranged { > PartialEq<$optional_type> for $optional_type { #[inline(always)] fn eq(&self, other: &$optional_type) -> bool { - <$type as $crate::traits::RangeIsValid>::ASSERT; - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { + assert!(MIN_A <= MAX_A); + assert!(MIN_B <= MAX_B); + } self.inner() == other.inner() } } @@ -1081,8 +1291,10 @@ macro_rules! impl_ranged { > PartialOrd<$type> for $type { #[inline(always)] fn partial_cmp(&self, other: &$type) -> Option { - ::ASSERT; - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { + assert!(MIN_A <= MAX_A); + assert!(MIN_B <= MAX_B); + } self.get().partial_cmp(&other.get()) } } @@ -1095,8 +1307,10 @@ macro_rules! impl_ranged { > PartialOrd<$optional_type> for $optional_type { #[inline] fn partial_cmp(&self, other: &$optional_type) -> Option { - <$type as $crate::traits::RangeIsValid>::ASSERT; - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { + assert!(MIN_A <= MAX_A); + assert!(MIN_B <= MAX_B); + } if self.is_none() && other.is_none() { Some(Ordering::Equal) } else if self.is_none() { @@ -1115,7 +1329,7 @@ macro_rules! impl_ranged { > Ord for $optional_type { #[inline] fn cmp(&self, other: &Self) -> Ordering { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } if self.is_none() && other.is_none() { Ordering::Equal } else if self.is_none() { @@ -1131,7 +1345,7 @@ macro_rules! impl_ranged { impl fmt::Binary for $type { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt(f) } } @@ -1139,7 +1353,7 @@ macro_rules! impl_ranged { impl fmt::LowerHex for $type { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt(f) } } @@ -1147,7 +1361,7 @@ macro_rules! impl_ranged { impl fmt::UpperHex for $type { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt(f) } } @@ -1155,7 +1369,7 @@ macro_rules! impl_ranged { impl fmt::LowerExp for $type { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt(f) } } @@ -1163,7 +1377,7 @@ macro_rules! impl_ranged { impl fmt::UpperExp for $type { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt(f) } } @@ -1171,15 +1385,31 @@ macro_rules! impl_ranged { impl fmt::Octal for $type { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - ::ASSERT; + const { assert!(MIN <= MAX); } self.get().fmt(f) } } + if_unsigned! { $is_signed + impl From> for $type<1, { $internal::MAX }> { + #[inline(always)] + fn from(value: NonZero<$internal>) -> Self { + Self::from_nonzero(value) + } + } + + impl From<$type<1, { $internal::MAX }>> for NonZero<$internal> { + #[inline(always)] + fn from(value: $type<1, { $internal::MAX }>) -> Self { + value.to_nonzero() + } + } + } + impl From<$type> for $internal { #[inline(always)] fn from(value: $type) -> Self { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } value.get() } } @@ -1190,7 +1420,7 @@ macro_rules! impl_ranged { > From<$type> for $optional_type { #[inline(always)] fn from(value: $type) -> Self { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } Self::Some(value) } } @@ -1201,7 +1431,7 @@ macro_rules! impl_ranged { > From>> for $optional_type { #[inline(always)] fn from(value: Option<$type>) -> Self { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } match value { Some(value) => Self::Some(value), None => Self::None, @@ -1215,7 +1445,7 @@ macro_rules! impl_ranged { > From<$optional_type> for Option<$type> { #[inline(always)] fn from(value: $optional_type) -> Self { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } value.get() } } @@ -1225,7 +1455,7 @@ macro_rules! impl_ranged { #[inline] fn try_from(value: $internal) -> Result { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::new(value).ok_or(TryFromIntError) } } @@ -1235,7 +1465,7 @@ macro_rules! impl_ranged { #[inline] fn from_str(s: &str) -> Result { - ::ASSERT; + const { assert!(MIN <= MAX); } let value = s.parse::<$internal>().map_err(|e| ParseIntError { kind: e.kind().clone() })?; @@ -1250,11 +1480,81 @@ macro_rules! impl_ranged { } } + $(impl< + const MIN_SRC: $from_internal, + const MAX_SRC: $from_internal, + const MIN_DST: $internal, + const MAX_DST: $internal, + > From<$from> for $type + { + #[inline(always)] + #[allow(trivial_numeric_casts, unused_comparisons)] + fn from(value: $from) -> Self { + const { + assert!(MIN_SRC <= MAX_SRC, "source range is invalid"); + assert!(MIN_DST <= MAX_DST, "target range is invalid"); + + match ($from_internal::MIN == 0, $internal::MIN == 0) { + // unsigned -> unsigned + (true, true) => { + assert!( + MIN_SRC as u128 >= MIN_DST as u128, + "minimum value cannot be represented in the target range" + ); + assert!( + MAX_SRC as u128 <= MAX_DST as u128, + "maximum value cannot be represented in the target range" + ); + } + // signed -> signed + (false, false) => { + assert!( + MIN_SRC as i128 >= MIN_DST as i128, + "minimum value cannot be represented in the target range" + ); + assert!( + MAX_SRC as i128 <= MAX_DST as i128, + "maximum value cannot be represented in the target range" + ); + } + // unsigned -> signed + (true, false) => { + assert!( + MIN_DST < 0 || MIN_SRC as u128 >= MIN_DST as u128, + "minimum value cannot be represented in the target range" + ); + assert!( + MAX_DST >= 0 + && MAX_SRC as u128 <= i128::MAX as u128 + && MAX_SRC as i128 <= MAX_DST as i128, + "maximum value cannot be represented in the target range" + ); + } + // signed -> unsigned + (false, true) => { + assert!( + MIN_SRC >= 0 && MIN_SRC as u128 >= MIN_DST as u128, + "minimum value cannot be represented in the target range" + ); + assert!( + MAX_SRC >= 0 && MAX_SRC as u128 <= MAX_DST as u128, + "maximum value cannot be represented in the target range" + ); + } + } + } + + // Safety: The source range is a subset of the destination range. + unsafe { $type::new_unchecked(value.get() as $internal) } + } + })+ + #[cfg(feature = "serde")] - impl serde::Serialize for $type { + impl serde_core::Serialize for $type { #[inline(always)] - fn serialize(&self, serializer: S) -> Result { - ::ASSERT; + fn serialize(&self, serializer: S) -> Result + { + const { assert!(MIN <= MAX); } self.get().serialize(serializer) } } @@ -1263,10 +1563,11 @@ macro_rules! impl_ranged { impl< const MIN: $internal, const MAX: $internal, - > serde::Serialize for $optional_type { + > serde_core::Serialize for $optional_type { #[inline(always)] - fn serialize(&self, serializer: S) -> Result { - <$type as $crate::traits::RangeIsValid>::ASSERT; + fn serialize(&self, serializer: S) -> Result + { + const { assert!(MIN <= MAX); } self.get().serialize(serializer) } } @@ -1276,20 +1577,24 @@ macro_rules! impl_ranged { 'de, const MIN: $internal, const MAX: $internal, - > serde::Deserialize<'de> for $type { + > serde_core::Deserialize<'de> for $type { #[inline] - fn deserialize>(deserializer: D) -> Result { - ::ASSERT; + fn deserialize>(deserializer: D) + -> Result + { + const { assert!(MIN <= MAX); } let internal = <$internal>::deserialize(deserializer)?; - Self::new(internal).ok_or_else(|| ::invalid_value( - serde::de::Unexpected::Other("integer"), - #[cfg(feature = "std")] { - &format!("an integer in the range {}..={}", MIN, MAX).as_ref() - }, - #[cfg(not(feature = "std"))] { - &"an integer in the valid range" - } - )) + Self::new(internal).ok_or_else(|| + ::invalid_value( + serde_core::de::Unexpected::Other("integer"), + #[cfg(feature = "alloc")] { + &alloc::format!("an integer in the range {}..={}", MIN, MAX).as_ref() + }, + #[cfg(not(feature = "alloc"))] { + &"an integer in the valid range" + } + ) + ) } } @@ -1298,36 +1603,104 @@ macro_rules! impl_ranged { 'de, const MIN: $internal, const MAX: $internal, - > serde::Deserialize<'de> for $optional_type { + > serde_core::Deserialize<'de> for $optional_type { #[inline] - fn deserialize>(deserializer: D) -> Result { - <$type as $crate::traits::RangeIsValid>::ASSERT; + fn deserialize>(deserializer: D) + -> Result + { + const { assert!(MIN <= MAX); } Ok(Self::Some($type::::deserialize(deserializer)?)) } } - #[cfg(feature = "rand")] + #[cfg(feature = "rand08")] impl< const MIN: $internal, const MAX: $internal, - > rand::distributions::Distribution<$type> for rand::distributions::Standard { + > rand08::distributions::Distribution<$type> for rand08::distributions::Standard { #[inline] - fn sample(&self, rng: &mut R) -> $type { - <$type as $crate::traits::RangeIsValid>::ASSERT; + fn sample(&self, rng: &mut R) -> $type { + const { assert!(MIN <= MAX); } $type::new(rng.gen_range(MIN..=MAX)).expect("rand failed to generate a valid value") } } - #[cfg(feature = "rand")] + if_not_manual_rand_09! { + [$($($skips)+)?] + #[cfg(feature = "rand09")] + impl< + const MIN: $internal, + const MAX: $internal, + > rand09::distr::Distribution<$type> for rand09::distr::StandardUniform { + #[inline] + fn sample(&self, rng: &mut R) -> $type { + const { assert!(MIN <= MAX); } + $type::new(rng.random_range(MIN..=MAX)).expect("rand failed to generate a valid value") + } + } + } + + if_not_manual_rand_010! { + [$($($skips)+)?] + #[cfg(feature = "rand010")] + impl< + const MIN: $internal, + const MAX: $internal, + > rand010::distr::Distribution<$type> for rand010::distr::StandardUniform { + #[inline] + fn sample(&self, rng: &mut R) -> $type { + const { assert!(MIN <= MAX); } + use rand010::RngExt as _; + $type::new(rng.random_range(MIN..=MAX)).expect("rand failed to generate a valid value") + } + } + } + + #[cfg(feature = "rand08")] + impl< + const MIN: $internal, + const MAX: $internal, + > rand08::distributions::Distribution<$optional_type> + for rand08::distributions::Standard { + #[inline] + fn sample(&self, rng: &mut R) -> $optional_type { + const { assert!(MIN <= MAX); } + rng.r#gen::>>().into() + } + } + + #[cfg(feature = "rand09")] + impl< + const MIN: $internal, + const MAX: $internal, + > rand09::distr::Distribution<$optional_type> + for rand09::distr::StandardUniform { + #[inline] + fn sample(&self, rng: &mut R) -> $optional_type { + const { assert!(MIN <= MAX); } + if rng.random() { + $optional_type::None + } else { + $optional_type::Some(rng.random::<$type>()) + } + } + } + + #[cfg(feature = "rand010")] impl< const MIN: $internal, const MAX: $internal, - > rand::distributions::Distribution<$optional_type> - for rand::distributions::Standard { + > rand010::distr::Distribution<$optional_type> + for rand010::distr::StandardUniform { #[inline] - fn sample(&self, rng: &mut R) -> $optional_type { - <$type as $crate::traits::RangeIsValid>::ASSERT; - rng.gen::>>().into() + fn sample(&self, rng: &mut R) -> $optional_type { + const { assert!(MIN <= MAX); } + use rand010::RngExt as _; + if rng.random() { + $optional_type::None + } else { + $optional_type::Some(rng.random::<$type>()) + } } } @@ -1335,13 +1708,13 @@ macro_rules! impl_ranged { impl num_traits::Bounded for $type { #[inline(always)] fn min_value() -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::MIN } #[inline(always)] fn max_value() -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } Self::MAX } } @@ -1350,7 +1723,7 @@ macro_rules! impl_ranged { impl quickcheck::Arbitrary for $type { #[inline] fn arbitrary(g: &mut quickcheck::Gen) -> Self { - ::ASSERT; + const { assert!(MIN <= MAX); } // Safety: The `rem_euclid` call and addition ensure that the value is in range. unsafe { Self::new_unchecked($internal::arbitrary(g).rem_euclid(MAX - MIN + 1) + MIN) @@ -1374,7 +1747,7 @@ macro_rules! impl_ranged { > quickcheck::Arbitrary for $optional_type { #[inline] fn arbitrary(g: &mut quickcheck::Gen) -> Self { - <$type as $crate::traits::RangeIsValid>::ASSERT; + const { assert!(MIN <= MAX); } Option::<$type>::arbitrary(g).into() } @@ -1389,86 +1762,380 @@ macro_rules! impl_ranged { impl_ranged! { RangedU8 { mod_name: ranged_u8 + alias: ru8 internal: u8 signed: false unsigned: u8 optional: OptionRangedU8 + optional_alias: Option_ru8 + from: [ + RangedU16(u16) + RangedU32(u32) + RangedU64(u64) + RangedU128(u128) + RangedUsize(usize) + RangedI8(i8) + RangedI16(i16) + RangedI32(i32) + RangedI64(i64) + RangedI128(i128) + RangedIsize(isize) + ] } RangedU16 { mod_name: ranged_u16 + alias: ru16 internal: u16 signed: false unsigned: u16 optional: OptionRangedU16 + optional_alias: Option_ru16 + from: [ + RangedU8(u8) + RangedU32(u32) + RangedU64(u64) + RangedU128(u128) + RangedUsize(usize) + RangedI8(i8) + RangedI16(i16) + RangedI32(i32) + RangedI64(i64) + RangedI128(i128) + RangedIsize(isize) + ] } RangedU32 { mod_name: ranged_u32 + alias: ru32 internal: u32 signed: false unsigned: u32 optional: OptionRangedU32 + optional_alias: Option_ru32 + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU64(u64) + RangedU128(u128) + RangedUsize(usize) + RangedI8(i8) + RangedI16(i16) + RangedI32(i32) + RangedI64(i64) + RangedI128(i128) + RangedIsize(isize) + ] } RangedU64 { mod_name: ranged_u64 + alias: ru64 internal: u64 signed: false unsigned: u64 optional: OptionRangedU64 + optional_alias: Option_ru64 + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU32(u32) + RangedU128(u128) + RangedUsize(usize) + RangedI8(i8) + RangedI16(i16) + RangedI32(i32) + RangedI64(i64) + RangedI128(i128) + RangedIsize(isize) + ] } RangedU128 { mod_name: ranged_u128 + alias: ru128 internal: u128 signed: false unsigned: u128 optional: OptionRangedU128 + optional_alias: Option_ru128 + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU32(u32) + RangedU64(u64) + RangedUsize(usize) + RangedI8(i8) + RangedI16(i16) + RangedI32(i32) + RangedI64(i64) + RangedI128(i128) + RangedIsize(isize) + ] } RangedUsize { mod_name: ranged_usize + alias: rusize internal: usize signed: false unsigned: usize optional: OptionRangedUsize + optional_alias: Option_rusize + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU32(u32) + RangedU64(u64) + RangedU128(u128) + RangedI8(i8) + RangedI16(i16) + RangedI32(i32) + RangedI64(i64) + RangedI128(i128) + RangedIsize(isize) + ] + manual: [rand_09 rand_010] } RangedI8 { mod_name: ranged_i8 + alias: ri8 internal: i8 signed: true unsigned: u8 optional: OptionRangedI8 + optional_alias: Option_ri8 + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU32(u32) + RangedU64(u64) + RangedU128(u128) + RangedUsize(usize) + RangedI16(i16) + RangedI32(i32) + RangedI64(i64) + RangedI128(i128) + RangedIsize(isize) + ] } RangedI16 { mod_name: ranged_i16 + alias: ri16 internal: i16 signed: true unsigned: u16 optional: OptionRangedI16 + optional_alias: Option_ri16 + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU32(u32) + RangedU64(u64) + RangedU128(u128) + RangedUsize(usize) + RangedI8(i8) + RangedI32(i32) + RangedI64(i64) + RangedI128(i128) + RangedIsize(isize) + ] } RangedI32 { mod_name: ranged_i32 + alias: ri32 internal: i32 signed: true unsigned: u32 optional: OptionRangedI32 + optional_alias: Option_ri32 + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU32(u32) + RangedU64(u64) + RangedU128(u128) + RangedUsize(usize) + RangedI8(i8) + RangedI16(i16) + RangedI64(i64) + RangedI128(i128) + RangedIsize(isize) + ] } RangedI64 { mod_name: ranged_i64 + alias: ri64 internal: i64 signed: true unsigned: u64 optional: OptionRangedI64 + optional_alias: Option_ri64 + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU32(u32) + RangedU64(u64) + RangedU128(u128) + RangedUsize(usize) + RangedI8(i8) + RangedI16(i16) + RangedI32(i32) + RangedI128(i128) + RangedIsize(isize) + ] } RangedI128 { mod_name: ranged_i128 + alias: ri128 internal: i128 signed: true unsigned: u128 optional: OptionRangedI128 + optional_alias: Option_ri128 + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU32(u32) + RangedU64(u64) + RangedU128(u128) + RangedUsize(usize) + RangedI8(i8) + RangedI16(i16) + RangedI32(i32) + RangedI64(i64) + RangedIsize(isize) + ] } RangedIsize { mod_name: ranged_isize + alias: risize internal: isize signed: true unsigned: usize optional: OptionRangedIsize + optional_alias: Option_risize + from: [ + RangedU8(u8) + RangedU16(u16) + RangedU32(u32) + RangedU64(u64) + RangedU128(u128) + RangedUsize(usize) + RangedI8(i8) + RangedI16(i16) + RangedI32(i32) + RangedI64(i64) + RangedI128(i128) + ] + manual: [rand_09 rand_010] + } +} + +#[cfg(feature = "rand09")] +impl rand09::distr::Distribution> + for rand09::distr::StandardUniform +{ + #[inline] + fn sample(&self, rng: &mut R) -> RangedUsize { + const { + assert!(MIN <= MAX); + } + + #[cfg(target_pointer_width = "16")] + let value = rng.random_range(MIN as u16..=MAX as u16) as usize; + #[cfg(target_pointer_width = "32")] + let value = rng.random_range(MIN as u32..=MAX as u32) as usize; + #[cfg(target_pointer_width = "64")] + let value = rng.random_range(MIN as u64..=MAX as u64) as usize; + #[cfg(not(any( + target_pointer_width = "16", + target_pointer_width = "32", + target_pointer_width = "64" + )))] + compile_error("platform has unusual (and unsupported) pointer width"); + + RangedUsize::new(value).expect("rand failed to generate a valid value") + } +} + +#[cfg(feature = "rand09")] +impl rand09::distr::Distribution> + for rand09::distr::StandardUniform +{ + #[inline] + fn sample(&self, rng: &mut R) -> RangedIsize { + const { + assert!(MIN <= MAX); + } + + #[cfg(target_pointer_width = "16")] + let value = rng.random_range(MIN as i16..=MAX as i16) as isize; + #[cfg(target_pointer_width = "32")] + let value = rng.random_range(MIN as i32..=MAX as i32) as isize; + #[cfg(target_pointer_width = "64")] + let value = rng.random_range(MIN as i64..=MAX as i64) as isize; + #[cfg(not(any( + target_pointer_width = "16", + target_pointer_width = "32", + target_pointer_width = "64" + )))] + compile_error("platform has unusual (and unsupported) pointer width"); + + RangedIsize::new(value).expect("rand failed to generate a valid value") + } +} + +#[cfg(feature = "rand010")] +impl rand010::distr::Distribution> + for rand010::distr::StandardUniform +{ + #[inline] + fn sample(&self, rng: &mut R) -> RangedUsize { + const { + assert!(MIN <= MAX); + } + + use rand010::RngExt as _; + + #[cfg(target_pointer_width = "16")] + let value = rng.random_range(MIN as u16..=MAX as u16) as usize; + #[cfg(target_pointer_width = "32")] + let value = rng.random_range(MIN as u32..=MAX as u32) as usize; + #[cfg(target_pointer_width = "64")] + let value = rng.random_range(MIN as u64..=MAX as u64) as usize; + #[cfg(not(any( + target_pointer_width = "16", + target_pointer_width = "32", + target_pointer_width = "64" + )))] + compile_error("platform has unusual (and unsupported) pointer width"); + + RangedUsize::new(value).expect("rand failed to generate a valid value") + } +} + +#[cfg(feature = "rand010")] +impl rand010::distr::Distribution> + for rand010::distr::StandardUniform +{ + #[inline] + fn sample(&self, rng: &mut R) -> RangedIsize { + const { + assert!(MIN <= MAX); + } + + use rand010::RngExt as _; + + #[cfg(target_pointer_width = "16")] + let value = rng.random_range(MIN as i16..=MAX as i16) as isize; + #[cfg(target_pointer_width = "32")] + let value = rng.random_range(MIN as i32..=MAX as i32) as isize; + #[cfg(target_pointer_width = "64")] + let value = rng.random_range(MIN as i64..=MAX as i64) as isize; + #[cfg(not(any( + target_pointer_width = "16", + target_pointer_width = "32", + target_pointer_width = "64" + )))] + compile_error("platform has unusual (and unsupported) pointer width"); + + RangedIsize::new(value).expect("rand failed to generate a valid value") } } diff --git a/pkg/installer/vendor/deranged/src/tests.rs b/pkg/installer/vendor/deranged/src/tests.rs index e9a6ff78274..32637bff0a0 100644 --- a/pkg/installer/vendor/deranged/src/tests.rs +++ b/pkg/installer/vendor/deranged/src/tests.rs @@ -1,4 +1,8 @@ -use std::hash::Hash; +extern crate std; + +use core::hash::Hash; +use std::format; +use std::prelude::rust_2021::*; use crate::{ IntErrorKind, OptionRangedI128, OptionRangedI16, OptionRangedI32, OptionRangedI64, @@ -8,6 +12,18 @@ use crate::{ RangedU8, RangedUsize, TryFromIntError, }; +#[test] +fn test_ranged_conversion() { + // equal range + let _: RangedI8<-5, 5> = RangedI16::<-5, 5>::new_static::<3>().into(); + + // wider range + let _: RangedI8<-6, 6> = RangedI16::<-5, 5>::new_static::<3>().into(); + + // the following fails to compile because the source range is wider than the destination range + // let _ : RangedI8<-4, 4> = RangedI16::<-5, 5>::new_static::<3>().into(); +} + macro_rules! if_signed { (signed $($x:tt)*) => { $($x)* }; (unsigned $($x:tt)*) => {}; @@ -98,7 +114,7 @@ macro_rules! tests { $t::<5, 10>::MIN.hash(&mut hasher); assert_eq!( $t::<5, 10>::MIN.cmp(&$t::<5, 10>::MAX), - std::cmp::Ordering::Less + core::cmp::Ordering::Less ); assert_eq!($opt::<5, 10>::None.clone(), $opt::<5, 10>::None); @@ -147,6 +163,18 @@ macro_rules! tests { assert!($opt::<5, 10>::None.is_none()); )*} + #[test] + fn is_some_by_ref() {$( + let value = $opt::<5, 10>::Some($t::<5, 10>::MAX); + assert!($opt::is_some(&value)); + )*} + + #[test] + fn is_none_by_ref() {$( + let value = $opt::<5, 10>::None; + assert!($opt::is_none(&value)); + )*} + #[test] fn default() {$( assert_eq!($opt::<5, 10>::default(), $opt::<5, 10>::None); @@ -514,7 +542,7 @@ macro_rules! tests { #[test] fn borrow() { - use std::borrow::Borrow; + use core::borrow::Borrow; $( assert_eq!(Borrow::<$inner>::borrow(&$t::<5, 10>::MIN), &5); assert_eq!(Borrow::<$inner>::borrow(&$t::<5, 10>::MAX), &10); @@ -548,23 +576,23 @@ macro_rules! tests { let five = $opt::Some($t::<5, 10>::MIN); let ten = $opt::Some($t::<5, 10>::MAX); - assert_eq!(none.cmp(&none), std::cmp::Ordering::Equal); - assert_eq!(five.cmp(&five), std::cmp::Ordering::Equal); - assert_eq!(ten.cmp(&ten), std::cmp::Ordering::Equal); - assert_eq!(none.cmp(&five), std::cmp::Ordering::Less); - assert_eq!(five.cmp(&ten), std::cmp::Ordering::Less); - assert_eq!(none.cmp(&ten), std::cmp::Ordering::Less); - assert_eq!(ten.cmp(&none), std::cmp::Ordering::Greater); + assert_eq!(none.cmp(&none), core::cmp::Ordering::Equal); + assert_eq!(five.cmp(&five), core::cmp::Ordering::Equal); + assert_eq!(ten.cmp(&ten), core::cmp::Ordering::Equal); + assert_eq!(none.cmp(&five), core::cmp::Ordering::Less); + assert_eq!(five.cmp(&ten), core::cmp::Ordering::Less); + assert_eq!(none.cmp(&ten), core::cmp::Ordering::Less); + assert_eq!(ten.cmp(&none), core::cmp::Ordering::Greater); let none = $opt::<0, 10>::None; let zero = $opt::Some($t::<0, 10>::MIN); let ten = $opt::Some($t::<0, 10>::MAX); - assert_eq!(none.partial_cmp(&none), Some(std::cmp::Ordering::Equal)); - assert_eq!(none.partial_cmp(&zero), Some(std::cmp::Ordering::Less)); - assert_eq!(zero.partial_cmp(&ten), Some(std::cmp::Ordering::Less)); - assert_eq!(none.partial_cmp(&ten), Some(std::cmp::Ordering::Less)); - assert_eq!(ten.partial_cmp(&none), Some(std::cmp::Ordering::Greater)); + assert_eq!(none.partial_cmp(&none), Some(core::cmp::Ordering::Equal)); + assert_eq!(none.partial_cmp(&zero), Some(core::cmp::Ordering::Less)); + assert_eq!(zero.partial_cmp(&ten), Some(core::cmp::Ordering::Less)); + assert_eq!(none.partial_cmp(&ten), Some(core::cmp::Ordering::Less)); + assert_eq!(ten.partial_cmp(&none), Some(core::cmp::Ordering::Greater)); )*} #[test] @@ -631,14 +659,42 @@ macro_rules! tests { Ok(()) } - #[cfg(feature = "rand")] + #[cfg(feature = "rand08")] + #[test] + fn rand08() {$( + let rand_val: $t<5, 10> = rand08::random(); + assert!(rand_val >= $t::<5, 10>::MIN); + assert!(rand_val <= $t::<5, 10>::MAX); + + let rand: $opt<5, 10> = rand08::random(); + if let Some(rand) = rand.get() { + assert!(rand >= $t::<5, 10>::MIN); + assert!(rand <= $t::<5, 10>::MAX); + } + )*} + + #[cfg(feature = "rand09")] + #[test] + fn rand09() {$( + let rand_val: $t<5, 10> = rand09::random(); + assert!(rand_val >= $t::<5, 10>::MIN); + assert!(rand_val <= $t::<5, 10>::MAX); + + let rand: $opt<5, 10> = rand09::random(); + if let Some(rand) = rand.get() { + assert!(rand >= $t::<5, 10>::MIN); + assert!(rand <= $t::<5, 10>::MAX); + } + )*} + + #[cfg(feature = "rand010")] #[test] - fn rand() {$( - let rand_val: $t<5, 10> = rand::random(); + fn rand010() {$( + let rand_val: $t<5, 10> = rand010::random(); assert!(rand_val >= $t::<5, 10>::MIN); assert!(rand_val <= $t::<5, 10>::MAX); - let rand: $opt<5, 10> = rand::random(); + let rand: $opt<5, 10> = rand010::random(); if let Some(rand) = rand.get() { assert!(rand >= $t::<5, 10>::MIN); assert!(rand <= $t::<5, 10>::MAX); diff --git a/pkg/installer/vendor/deranged/src/traits.rs b/pkg/installer/vendor/deranged/src/traits.rs deleted file mode 100644 index d1b69ac01f9..00000000000 --- a/pkg/installer/vendor/deranged/src/traits.rs +++ /dev/null @@ -1,117 +0,0 @@ -use crate::{ - RangedI128, RangedI16, RangedI32, RangedI64, RangedI8, RangedIsize, RangedU128, RangedU16, - RangedU32, RangedU64, RangedU8, RangedUsize, -}; - -macro_rules! declare_traits { - ($($trait_name:ident),* $(,)?) => {$( - pub(crate) trait $trait_name { - const ASSERT: (); - } - )*}; -} - -macro_rules! impl_traits_for_all { - ($($ranged_ty:ident $inner_ty:ident),* $(,)?) => {$( - impl RangeIsValid for $ranged_ty { - const ASSERT: () = assert!(MIN <= MAX); - } - - impl< - const CURRENT_MIN: $inner_ty, - const CURRENT_MAX: $inner_ty, - const NEW_MIN: $inner_ty, - const NEW_MAX: $inner_ty, - > ExpandIsValid for ($ranged_ty, $ranged_ty) { - const ASSERT: () = { - assert!(NEW_MIN <= CURRENT_MIN); - assert!(NEW_MAX >= CURRENT_MAX); - }; - } - - impl< - const CURRENT_MIN: $inner_ty, - const CURRENT_MAX: $inner_ty, - const NEW_MIN: $inner_ty, - const NEW_MAX: $inner_ty, - > NarrowIsValid for ($ranged_ty, $ranged_ty) { - const ASSERT: () = { - assert!(NEW_MIN >= CURRENT_MIN); - assert!(NEW_MAX <= CURRENT_MAX); - }; - } - - impl< - const VALUE: $inner_ty, - const MIN: $inner_ty, - const MAX: $inner_ty, - > StaticIsValid for ($ranged_ty, $ranged_ty) { - const ASSERT: () = { - assert!(VALUE >= MIN); - assert!(VALUE <= MAX); - }; - } - )*}; -} - -macro_rules! impl_traits_for_signed { - ($($ranged_ty:ident $inner_ty:ident),* $(,)?) => {$( - impl AbsIsSafe for $ranged_ty { - const ASSERT: () = { - assert!(MIN != <$inner_ty>::MIN); - assert!(-MIN <= MAX); - }; - } - - impl NegIsSafe for $ranged_ty { - const ASSERT: () = { - assert!(MIN != <$inner_ty>::MIN); - assert!(-MIN <= MAX); - assert!(-MAX >= MIN); - }; - } - - impl_traits_for_all!($ranged_ty $inner_ty); - )*}; -} - -macro_rules! impl_traits_for_unsigned { - ($($ranged_ty:ident $inner_ty:ident),* $(,)?) => {$( - impl AbsIsSafe for $ranged_ty { - const ASSERT: () = (); - } - - impl NegIsSafe for $ranged_ty { - const ASSERT: () = assert!(MAX == 0); - } - - impl_traits_for_all!($ranged_ty $inner_ty); - )*}; -} - -declare_traits![ - RangeIsValid, - AbsIsSafe, - NegIsSafe, - ExpandIsValid, - NarrowIsValid, - StaticIsValid, -]; - -impl_traits_for_signed! { - RangedI8 i8, - RangedI16 i16, - RangedI32 i32, - RangedI64 i64, - RangedI128 i128, - RangedIsize isize, -} - -impl_traits_for_unsigned! { - RangedU8 u8, - RangedU16 u16, - RangedU32 u32, - RangedU64 u64, - RangedU128 u128, - RangedUsize usize, -} diff --git a/pkg/installer/vendor/deranged/src/unsafe_wrapper.rs b/pkg/installer/vendor/deranged/src/unsafe_wrapper.rs index 8620e121765..6b2304c168e 100644 --- a/pkg/installer/vendor/deranged/src/unsafe_wrapper.rs +++ b/pkg/installer/vendor/deranged/src/unsafe_wrapper.rs @@ -1,17 +1,26 @@ +//! Declaration and implementation of `Unsafe`, which ensures all unsafe operations are correctly +//! placed in unsafe blocks. + +/// A value that is safe to use, but is unsafe to construct or mutate. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) struct Unsafe(T); impl core::fmt::Debug for Unsafe { + #[inline] fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.0.fmt(f) } } impl Unsafe { + /// Create a new `Unsafe`, asserting that all invariants are upheld. + #[inline(always)] pub(crate) const unsafe fn new(value: T) -> Self { Self(value) } + /// Get a reference to the inner value. + #[inline(always)] pub(crate) const fn get(&self) -> &T { &self.0 } @@ -20,6 +29,7 @@ impl Unsafe { impl core::ops::Deref for Unsafe { type Target = T; + #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } diff --git a/pkg/installer/vendor/num-conv/.cargo-checksum.json b/pkg/installer/vendor/num-conv/.cargo-checksum.json index 5b0fde59373..c7fd6f6c0d0 100644 --- a/pkg/installer/vendor/num-conv/.cargo-checksum.json +++ b/pkg/installer/vendor/num-conv/.cargo-checksum.json @@ -1 +1 @@ -{"files":{".cargo_vcs_info.json":"9d07ec3e10af67b4752a03a676e5f2a38198b09bcf0c49bea746a7075033c459","Cargo.toml":"c1d8999190f493d43b84b07eaffd2a9144e16be197bb3ef13eb69305e2f23047","Cargo.toml.orig":"93898318a8e671e7b324de151b1b262f4ae77413753ac7b7ce377ceda5cc57b7","LICENSE-Apache":"c0fd5f9df8d17e13587f8fe403d2326b835e60d532817d0b42ae4aea44209251","LICENSE-MIT":"af85fff507d80e6c7ff242acfc4b0a7f5de9a72286bb3c883c782772ca4b4402","README.md":"081b57a3244bd2d42ae1c9592c90556bf50fc2155a53760d9049c9dacbe92354","src/lib.rs":"ab6c4b28902164204179f5c31473753fbe5220a4b23082e227478e19c2aa47ca"},"package":"51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"} \ No newline at end of file +{"files":{".cargo_vcs_info.json":"6becb85ebecec0de0ad1580593000f3c920939eafd52707799403645a36a059a","Cargo.lock":"0761cb38fffefd4118ba3d7c12bbabe37c1552fde772adb88d35f3e31050b206","Cargo.toml":"c6d982b10de304bce8e85b8682a7074f8d697c2410bca7644fecc018f4c39b34","Cargo.toml.orig":"bf02eb348d29d448ad35e35c17145418c4267ce01238c68526b1e0ff980919c8","LICENSE-Apache":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"e2e245f2b566d0bfafb0f6a04c16b82d710c4e6e7d799e39bb4ef6e541b85b98","README.md":"081b57a3244bd2d42ae1c9592c90556bf50fc2155a53760d9049c9dacbe92354","src/lib.rs":"9c7e451a50cc22348eba76ebc40f27a67d4bfe6a271af17c5379f02a95b8f323"},"package":"c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967"} \ No newline at end of file diff --git a/pkg/installer/vendor/num-conv/.cargo_vcs_info.json b/pkg/installer/vendor/num-conv/.cargo_vcs_info.json index a986b369624..b21cd831280 100644 --- a/pkg/installer/vendor/num-conv/.cargo_vcs_info.json +++ b/pkg/installer/vendor/num-conv/.cargo_vcs_info.json @@ -1,6 +1,6 @@ { "git": { - "sha1": "b6606e5c451f5fb2bffc085a6d8d9530f3d44a48" + "sha1": "b9371fe8891cc474a321a5c2e78c7368abf27cc1" }, "path_in_vcs": "" } \ No newline at end of file diff --git a/pkg/installer/vendor/num-conv/Cargo.lock b/pkg/installer/vendor/num-conv/Cargo.lock new file mode 100644 index 00000000000..777227239fd --- /dev/null +++ b/pkg/installer/vendor/num-conv/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "num-conv" +version = "0.2.1" diff --git a/pkg/installer/vendor/num-conv/Cargo.toml b/pkg/installer/vendor/num-conv/Cargo.toml index 0b8a9a6c01f..c18757456fa 100644 --- a/pkg/installer/vendor/num-conv/Cargo.toml +++ b/pkg/installer/vendor/num-conv/Cargo.toml @@ -13,12 +13,18 @@ edition = "2021" rust-version = "1.57.0" name = "num-conv" -version = "0.1.0" +version = "0.2.1" authors = ["Jacob Pratt "] +build = false include = [ "src/**/*", "LICENSE-*", ] +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false description = """ `num_conv` is a crate to convert between integer types without using `as` casts. This provides better certainty when refactoring, makes the exact behavior of code more explicit, and allows using @@ -45,6 +51,10 @@ rustdoc-args = ["--generate-link-to-definition"] [features] +[lib] +name = "num_conv" +path = "src/lib.rs" + [lints.clippy] alloc-instead-of-core = "deny" std-instead-of-core = "deny" diff --git a/pkg/installer/vendor/num-conv/Cargo.toml.orig b/pkg/installer/vendor/num-conv/Cargo.toml.orig index 1c9f4dc1a7e..98a1f3c8a5f 100644 --- a/pkg/installer/vendor/num-conv/Cargo.toml.orig +++ b/pkg/installer/vendor/num-conv/Cargo.toml.orig @@ -1,6 +1,6 @@ [package] name = "num-conv" -version = "0.1.0" +version = "0.2.1" authors = ["Jacob Pratt "] edition = "2021" rust-version = "1.57.0" diff --git a/pkg/installer/vendor/num-conv/LICENSE-Apache b/pkg/installer/vendor/num-conv/LICENSE-Apache index d8bca8b9f1d..f433b1a53f5 100644 --- a/pkg/installer/vendor/num-conv/LICENSE-Apache +++ b/pkg/installer/vendor/num-conv/LICENSE-Apache @@ -175,28 +175,3 @@ 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 2023 Jacob Pratt - - 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. diff --git a/pkg/installer/vendor/num-conv/LICENSE-MIT b/pkg/installer/vendor/num-conv/LICENSE-MIT index 7c7f78a5ed8..3738d287a7f 100644 --- a/pkg/installer/vendor/num-conv/LICENSE-MIT +++ b/pkg/installer/vendor/num-conv/LICENSE-MIT @@ -1,4 +1,4 @@ -Copyright (c) 2023 Jacob Pratt +Copyright (c) Jacob Pratt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/pkg/installer/vendor/num-conv/src/lib.rs b/pkg/installer/vendor/num-conv/src/lib.rs index cbf3ff21d63..a7e94b28a38 100644 --- a/pkg/installer/vendor/num-conv/src/lib.rs +++ b/pkg/installer/vendor/num-conv/src/lib.rs @@ -13,7 +13,7 @@ /// use num_conv::prelude::*; /// ``` pub mod prelude { - pub use crate::{CastSigned as _, CastUnsigned as _, Extend as _, Truncate as _}; + pub use crate::{Extend as _, Truncate as _}; } mod sealed { @@ -36,73 +36,11 @@ mod sealed { pub trait TruncateTargetSealed { fn truncate(self) -> T; + fn saturating_truncate(self) -> T; + fn checked_truncate(self) -> Option; } } -/// Cast to a signed integer of the same size. -/// -/// This trait is implemented for all integers. Unsigned to signed casts are equivalent to -/// `0.wrapping_add_signed(value)`, while signed to signed casts are an identity conversion. -/// -/// ```rust -/// # use num_conv::CastSigned; -/// assert_eq!(u8::MAX.cast_signed(), -1_i8); -/// assert_eq!(u16::MAX.cast_signed(), -1_i16); -/// assert_eq!(u32::MAX.cast_signed(), -1_i32); -/// assert_eq!(u64::MAX.cast_signed(), -1_i64); -/// assert_eq!(u128::MAX.cast_signed(), -1_i128); -/// assert_eq!(usize::MAX.cast_signed(), -1_isize); -/// ``` -/// -/// ```rust -/// # use num_conv::CastSigned; -/// assert_eq!(0_i8.cast_signed(), 0_i8); -/// assert_eq!(0_i16.cast_signed(), 0_i16); -/// assert_eq!(0_i32.cast_signed(), 0_i32); -/// assert_eq!(0_i64.cast_signed(), 0_i64); -/// assert_eq!(0_i128.cast_signed(), 0_i128); -/// assert_eq!(0_isize.cast_signed(), 0_isize); -/// ``` -pub trait CastSigned: sealed::Integer { - /// The signed integer type with the same size as `Self`. - type Signed; - - /// Cast an integer to the signed integer of the same size. - fn cast_signed(self) -> Self::Signed; -} - -/// Cast to an unsigned integer of the same size. -/// -/// This trait is implemented for all integers. Signed to unsigned casts are equivalent to -/// `0.wrapping_add_unsigned(value)`, while unsigned to unsigned casts are an identity conversion. -/// -/// ```rust -/// # use num_conv::CastUnsigned; -/// assert_eq!((-1_i8).cast_unsigned(), u8::MAX); -/// assert_eq!((-1_i16).cast_unsigned(), u16::MAX); -/// assert_eq!((-1_i32).cast_unsigned(), u32::MAX); -/// assert_eq!((-1_i64).cast_unsigned(), u64::MAX); -/// assert_eq!((-1_i128).cast_unsigned(), u128::MAX); -/// assert_eq!((-1_isize).cast_unsigned(), usize::MAX); -/// ``` -/// -/// ```rust -/// # use num_conv::CastUnsigned; -/// assert_eq!(0_u8.cast_unsigned(), 0_u8); -/// assert_eq!(0_u16.cast_unsigned(), 0_u16); -/// assert_eq!(0_u32.cast_unsigned(), 0_u32); -/// assert_eq!(0_u64.cast_unsigned(), 0_u64); -/// assert_eq!(0_u128.cast_unsigned(), 0_u128); -/// assert_eq!(0_usize.cast_unsigned(), 0_usize); -/// ``` -pub trait CastUnsigned: sealed::Integer { - /// The unsigned integer type with the same size as `Self`. - type Unsigned; - - /// Cast an integer to the unsigned integer of the same size. - fn cast_unsigned(self) -> Self::Unsigned; -} - /// A type that can be used with turbofish syntax in [`Extend::extend`]. /// /// It is unlikely that you will want to use this trait directly. You are probably looking for the @@ -148,7 +86,9 @@ impl Extend for T { } } -/// Truncate to an integer of the same size or smaller, preserving the least significant bits. +/// Truncate to an integer of the same size or smaller. +/// +/// Preserve the least significant bits with `.truncate()`: /// /// ```rust /// # use num_conv::Truncate; @@ -165,12 +105,60 @@ impl Extend for T { /// assert_eq!((-1_i64).truncate::(), -1_i32); /// assert_eq!((-1_i128).truncate::(), -1_i64); /// ``` +/// +/// Saturate to the numeric bounds with `.saturating_truncate()`: +/// +/// ```rust +/// # use num_conv::Truncate; +/// assert_eq!(500_u16.saturating_truncate::(), u8::MAX); +/// assert_eq!(u32::MAX.saturating_truncate::(), u16::MAX); +/// assert_eq!(u64::MAX.saturating_truncate::(), u32::MAX); +/// assert_eq!(u128::MAX.saturating_truncate::(), u64::MAX); +/// ``` +/// +/// ```rust +/// # use num_conv::Truncate; +/// assert_eq!((-500_i16).saturating_truncate::(), i8::MIN); +/// assert_eq!(i32::MIN.saturating_truncate::(), i16::MIN); +/// assert_eq!(i64::MIN.saturating_truncate::(), i32::MIN); +/// assert_eq!(i128::MIN.saturating_truncate::(), i64::MIN); +/// ``` +/// +/// Checked with `.checked_truncate()`, returning `None` if the value is out of range: +/// +/// ```rust +/// # use num_conv::Truncate; +/// assert_eq!(u16::MAX.checked_truncate::(), None); +/// assert_eq!(u32::MAX.checked_truncate::(), None); +/// assert_eq!(u64::MAX.checked_truncate::(), None); +/// assert_eq!(u128::MAX.checked_truncate::(), None); +/// ``` +/// +/// ```rust +/// # use num_conv::Truncate; +/// assert_eq!(i16::MIN.checked_truncate::(), None); +/// assert_eq!(i32::MIN.checked_truncate::(), None); +/// assert_eq!(i64::MIN.checked_truncate::(), None); +/// assert_eq!(i128::MIN.checked_truncate::(), None); +/// ``` pub trait Truncate: sealed::Integer { /// Truncate an integer to an integer of the same size or smaller, preserving the least /// significant bits. fn truncate(self) -> T where Self: TruncateTarget; + + /// Truncate an integer to an integer of the same size or smaller, saturating to the numeric + /// bounds instead of wrapping. + fn saturating_truncate(self) -> T + where + Self: TruncateTarget; + + /// Truncate an integer to an integer of the same size or smaller, returning `None` if the value + /// is out of range. + fn checked_truncate(self) -> Option + where + Self: TruncateTarget; } impl Truncate for T { @@ -180,50 +168,20 @@ impl Truncate for T { { sealed::TruncateTargetSealed::truncate(self) } -} - -macro_rules! impl_cast_signed { - ($($($from:ty),+ => $to:ty;)*) => {$($( - const _: () = assert!( - core::mem::size_of::<$from>() == core::mem::size_of::<$to>(), - concat!( - "cannot cast ", - stringify!($from), - " to ", - stringify!($to), - " because they are different sizes" - ) - ); - - impl CastSigned for $from { - type Signed = $to; - fn cast_signed(self) -> Self::Signed { - self as _ - } - } - )+)*}; -} -macro_rules! impl_cast_unsigned { - ($($($from:ty),+ => $to:ty;)*) => {$($( - const _: () = assert!( - core::mem::size_of::<$from>() == core::mem::size_of::<$to>(), - concat!( - "cannot cast ", - stringify!($from), - " to ", - stringify!($to), - " because they are different sizes" - ) - ); + fn saturating_truncate(self) -> U + where + T: TruncateTarget, + { + sealed::TruncateTargetSealed::saturating_truncate(self) + } - impl CastUnsigned for $from { - type Unsigned = $to; - fn cast_unsigned(self) -> Self::Unsigned { - self as _ - } - } - )+)*}; + fn checked_truncate(self) -> Option + where + T: TruncateTarget, + { + sealed::TruncateTargetSealed::checked_truncate(self) + } } macro_rules! impl_extend { @@ -243,6 +201,7 @@ macro_rules! impl_extend { ); impl sealed::ExtendTargetSealed<$to> for $from { + #[inline] fn extend(self) -> $to { self as _ } @@ -269,33 +228,36 @@ macro_rules! impl_truncate { ); impl sealed::TruncateTargetSealed<$to> for $from { + #[inline] fn truncate(self) -> $to { self as _ } + + #[inline] + fn saturating_truncate(self) -> $to { + if self > <$to>::MAX as _ { + <$to>::MAX + } else if self < <$to>::MIN as _ { + <$to>::MIN + } else { + self as _ + } + } + + #[inline] + fn checked_truncate(self) -> Option<$to> { + if self > <$to>::MAX as _ || self < <$to>::MIN as _ { + None + } else { + Some(self as _) + } + } } impl TruncateTarget<$to> for $from {} )+)*}; } -impl_cast_signed! { - u8, i8 => i8; - u16, i16 => i16; - u32, i32 => i32; - u64, i64 => i64; - u128, i128 => i128; - usize, isize => isize; -} - -impl_cast_unsigned! { - u8, i8 => u8; - u16, i16 => u16; - u32, i32 => u32; - u64, i64 => u64; - u128, i128 => u128; - usize, isize => usize; -} - impl_extend! { u8 => u8, u16, u32, u64, u128, usize; u16 => u16, u32, u64, u128, usize; diff --git a/pkg/installer/vendor/serde/.cargo-checksum.json b/pkg/installer/vendor/serde/.cargo-checksum.json index cd27c9400d3..ebd8bb821f8 100644 --- a/pkg/installer/vendor/serde/.cargo-checksum.json +++ b/pkg/installer/vendor/serde/.cargo-checksum.json @@ -1 +1 @@ -{"files":{".cargo_vcs_info.json":"551bcc8700d2eaef6fc49064c4a6c30918d6ca9a060244afa861f697046a5ed1","Cargo.toml":"207990d0c817927f6a206cffd1c63b5cf23e69df431372874bd73ebf38185e8e","Cargo.toml.orig":"03d75d1ac89f4eca76981fab025ed349997456ef4bc6dff2488d08856b2dfce1","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"731c044fc5f98b37a89e9049c9214267db98763309cb63146b45c029640f82a3","build.rs":"8653bc5c754a533b55849c29ccb0e75f06758d415cd768c94c3e08e790c2e953","crates-io.md":"407d92b2932923f8708aaf31db266fd7db32e2b0afa6c569d134b680b74a1920","src/de/format.rs":"c85071b016df643b161859682d21ce34fa0ebf2a3bdbeeea69859da48f5d934f","src/de/ignored_any.rs":"6480f2b2a83dc4764d01b2eec7309729eef2492eede2e5ee98d23a60b05198eb","src/de/impls.rs":"f1d691a1bd4f0404c590eb217bab1d07c7d56ff9e874da6ab28d4affa7fef94c","src/de/mod.rs":"14880617db97f5bd68f991248051c0327098730e6e0f15c763fc0f0048ce3dbe","src/de/seed.rs":"045d890712a04eb33ffc5a021e5d948a63c89402b8ffeea749df2171b7484f8f","src/de/size_hint.rs":"fff83dc39d30e75e8e611991f9c5399188a1aad23a6462dbca2c8b62655cfedb","src/de/value.rs":"0c485908b1f755e4750af0aefa2132460dadbcf30919c15c06ca795a92d96430","src/integer128.rs":"29ef30b7d94507b34807090e68173767cdc7aff62edccd38affe69e75338dddc","src/lib.rs":"7f5d3abc6dab861431e49e7a13f0248241d9643a92a594f16f3434738f61c93a","src/macros.rs":"0d4b392ed6fe529fda2c5439c8547fe9717e64f528bfd01f633bb725f98b53cd","src/private/de.rs":"9255ecf2d5c52f0f52b4e0dbf85bdd8c140bc2c1ac96086ee395589e0521aeb4","src/private/doc.rs":"b222decb40321190155209e1b8a5a52e3adfaa470047e379e664b71e0320655a","src/private/mod.rs":"b8f0c348621d91dd9da3db83d8877e70bc61ad0a2dc2d6fb57c6fc2c2cbafa26","src/private/ser.rs":"b11543e304f793a1436a50c51cf27100ad39e1148467a7d256aa02b838ff4dd3","src/ser/fmt.rs":"d1cfd9623605413e45a23ef778d97f0ac4da4adaed23739f1f9d7414b30e384b","src/ser/impls.rs":"585908d859fc89adcc1c6a7acc8f12467feba7daeb8c44ae28d25fd40d140f2c","src/ser/impossible.rs":"5c325da8e0370ab22abe1e15d8af1dc7a1707b127508f61e720cd7f0caa80593","src/ser/mod.rs":"eee3a4ecfc09993677df0be4772c1c7edde43ec9591be0b5595cb113a548a8a2","src/std_error.rs":"25a07149e2e468747ffa5a58051c7f93d7b3c0fa0372f012a96c97ec8ab03b97"},"package":"5665e14a49a4ea1b91029ba7d3bca9f299e1f7cfa194388ccc20f14743e784f2"} \ No newline at end of file +{"files":{".cargo_vcs_info.json":"399aaf38fec4939d8009dbb5e40edd613aefad660ded89ad5040a22b1f7140f9","Cargo.lock":"4c5bf070ad8c1c8beee68d9c477e909332e942aac79cfdc8a6b1f0de572c9073","Cargo.toml":"d7fc24e39691a0831eaa0eac677b46ecbae407a40fa816b904759822d10f42e8","Cargo.toml.orig":"0b7df7944cba2a0646daa431efdc9f8b200bc6beb586cd71e302a102d17c4c60","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"d40eb47c3c6e3780359df6fe40d40a35725c843df0e3b845e10ecf2a15048664","build.rs":"c99c25e1a11f3e51b61dd8c25bdbfbd090e43e5f1f2014f41f28e214dd8310d5","crates-io.md":"00b72e63d4f3393e28f9a219c8cb8c122013d82f0d10d6d551e239b13c5ba9e4","src/core/crate_root.rs":"157ca402e23c32f11a4f1797c81afb5e9f08df96768012cf3e3199153aafb2dd","src/core/de/ignored_any.rs":"6480f2b2a83dc4764d01b2eec7309729eef2492eede2e5ee98d23a60b05198eb","src/core/de/impls.rs":"9fb7a0322af51971fe1fa8f5b56c7ca3716622a6e9127b86bddfc0742c11383c","src/core/de/mod.rs":"5ec8602d593915e0cf480b0ce67b02f6ab066dac34725237d2c7b4a6ef12a845","src/core/de/value.rs":"fb6fef6d23d95d516c6e1d6b5cefd8b98ba3881214a82a8a7e0a8ffbb0a12083","src/core/format.rs":"c85071b016df643b161859682d21ce34fa0ebf2a3bdbeeea69859da48f5d934f","src/core/lib.rs":"5789fbaa20497111e3efa2af8a3c1d18bb41c0c0480b542d26a2573e8ff5cf5c","src/core/macros.rs":"a61c9d19b210697304328e6bb9380a1de713e21042256df90a2b4553f178b0be","src/core/private/content.rs":"5fdfb2bb95ecc80375507acb813a4c640496385e56fc99ab448f6b19e01fcc01","src/core/private/doc.rs":"abe656c015267555ca26ebbcf2f4dcc52c719a0b9ade3a5ed4635b2784699b8c","src/core/private/mod.rs":"3bb3427ec80077b9df1853aa17681de796de0179d74871a96b88b72469de6cfc","src/core/private/seed.rs":"3f6e098c5bd314788370dcaf3ab0152fcd7feb6bcf36a9c51808938cd58071eb","src/core/private/size_hint.rs":"350694a2abaad94ca5d33958710a5bb8973a2ea1a3dcc50a41405c943761b81f","src/core/private/string.rs":"c1500fd4b64c24a5e45fa5f48c85c802816d6954a2999a72fc5a8861687212d4","src/core/ser/fmt.rs":"bd129d9f085933b76dafef6eb43ffac893c1f6484a3064dcd82faeeebc3b203c","src/core/ser/impls.rs":"5ee7efc439345e8665da0bd79bc06c02a0506e5fd0f3a4cf11af0c7197eaa643","src/core/ser/impossible.rs":"283f628d5107aa030d2e96eeb1dee187f0ac18c24d517edeb51738ab15dfb871","src/core/ser/mod.rs":"ec097d92c8545356961e977a4c9650361cadd1d3a243d805ae7b0e0e589ae803","src/core/std_error.rs":"b36fd6a2b6898770b9f1c51517eb362af115767d0f7cb4a713e1b949530ffa8a","src/integer128.rs":"a5ca321ace6b11b71f637397cf4ea41992545a9c297a23230c8a9e8b92db71fa","src/lib.rs":"2e01b1191da5bc6be5ca1f208c362bc5b4e5f9fefc0b097433b9aef19a0af926","src/private/de.rs":"68ee17774d3bbc693d9f19803747fa2c3afdb7046482e6d94ac6cf7db5a4fe20","src/private/mod.rs":"52cc5b33364b13724ea4c2989f3ccd8ba02a2ef903761499e15264835ff76388","src/private/ser.rs":"bea364a6199b57c2aa5a96a6bb0530176850dbeaaee908a6307fe610c873c8e3"},"package":"9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"} \ No newline at end of file diff --git a/pkg/installer/vendor/serde/.cargo_vcs_info.json b/pkg/installer/vendor/serde/.cargo_vcs_info.json index 9993c8cf758..710a3aa5686 100644 --- a/pkg/installer/vendor/serde/.cargo_vcs_info.json +++ b/pkg/installer/vendor/serde/.cargo_vcs_info.json @@ -1,6 +1,6 @@ { "git": { - "sha1": "1b4da41f970555e111f471633205bbcb4dadbc63" + "sha1": "a866b336f14aa57a07f0d0be9f8762746e64ecb4" }, "path_in_vcs": "serde" } \ No newline at end of file diff --git a/pkg/installer/vendor/serde/Cargo.lock b/pkg/installer/vendor/serde/Cargo.lock new file mode 100644 index 00000000000..5ecd8d01338 --- /dev/null +++ b/pkg/installer/vendor/serde/Cargo.lock @@ -0,0 +1,66 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.228" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" diff --git a/pkg/installer/vendor/serde/Cargo.toml b/pkg/installer/vendor/serde/Cargo.toml index 144e969c8eb..6ce71c7b6eb 100644 --- a/pkg/installer/vendor/serde/Cargo.toml +++ b/pkg/installer/vendor/serde/Cargo.toml @@ -10,15 +10,16 @@ # See Cargo.toml.orig for the original contents. [package] -edition = "2018" -rust-version = "1.31" +edition = "2021" +rust-version = "1.56" name = "serde" -version = "1.0.207" +version = "1.0.228" authors = [ "Erick Tryzelaar ", "David Tolnay ", ] build = "build.rs" +autolib = false autobins = false autoexamples = false autotests = false @@ -40,40 +41,44 @@ categories = [ license = "MIT OR Apache-2.0" repository = "https://github.com/serde-rs/serde" -[package.metadata.docs.rs] +[package.metadata.playground] features = [ "derive", "rc", - "unstable", ] -rustdoc-args = ["--generate-link-to-definition"] -targets = ["x86_64-unknown-linux-gnu"] -[package.metadata.playground] +[package.metadata.docs.rs] features = [ "derive", "rc", + "unstable", +] +targets = ["x86_64-unknown-linux-gnu"] +rustdoc-args = [ + "--generate-link-to-definition", + "--generate-macro-expansion", + "--extern-html-root-url=core=https://doc.rust-lang.org", + "--extern-html-root-url=alloc=https://doc.rust-lang.org", + "--extern-html-root-url=std=https://doc.rust-lang.org", ] +[features] +alloc = ["serde_core/alloc"] +default = ["std"] +derive = ["serde_derive"] +rc = ["serde_core/rc"] +std = ["serde_core/std"] +unstable = ["serde_core/unstable"] + [lib] name = "serde" path = "src/lib.rs" -doc-scrape-examples = false + +[dependencies.serde_core] +version = "=1.0.228" +features = ["result"] +default-features = false [dependencies.serde_derive] version = "1" optional = true - -[dev-dependencies.serde_derive] -version = "1" - -[features] -alloc = [] -default = ["std"] -derive = ["serde_derive"] -rc = [] -std = [] -unstable = [] - -[target."cfg(any())".dependencies.serde_derive] -version = "=1.0.207" diff --git a/pkg/installer/vendor/serde/Cargo.toml.orig b/pkg/installer/vendor/serde/Cargo.toml.orig index a2f227eb7b0..0bffa22d4fd 100644 --- a/pkg/installer/vendor/serde/Cargo.toml.orig +++ b/pkg/installer/vendor/serde/Cargo.toml.orig @@ -1,43 +1,36 @@ [package] name = "serde" -version = "1.0.207" +version = "1.0.228" authors = ["Erick Tryzelaar ", "David Tolnay "] build = "build.rs" categories = ["encoding", "no-std", "no-std::no-alloc"] description = "A generic serialization/deserialization framework" documentation = "https://docs.rs/serde" -edition = "2018" +edition = "2021" homepage = "https://serde.rs" keywords = ["serde", "serialization", "no_std"] license = "MIT OR Apache-2.0" readme = "crates-io.md" repository = "https://github.com/serde-rs/serde" -rust-version = "1.31" +rust-version = "1.56" [dependencies] +serde_core = { version = "=1.0.228", path = "../serde_core", default-features = false, features = ["result"] } serde_derive = { version = "1", optional = true, path = "../serde_derive" } -[dev-dependencies] -serde_derive = { version = "1", path = "../serde_derive" } - -[lib] -doc-scrape-examples = false - [package.metadata.playground] features = ["derive", "rc"] [package.metadata.docs.rs] features = ["derive", "rc", "unstable"] targets = ["x86_64-unknown-linux-gnu"] -rustdoc-args = ["--generate-link-to-definition"] - -# This cfg cannot be enabled, but it still forces Cargo to keep serde_derive's -# version in lockstep with serde's, even if someone depends on the two crates -# separately with serde's "derive" feature disabled. Every serde_derive release -# is compatible with exactly one serde release because the generated code -# involves nonpublic APIs which are not bound by semver. -[target.'cfg(any())'.dependencies] -serde_derive = { version = "=1.0.207", path = "../serde_derive" } +rustdoc-args = [ + "--generate-link-to-definition", + "--generate-macro-expansion", + "--extern-html-root-url=core=https://doc.rust-lang.org", + "--extern-html-root-url=alloc=https://doc.rust-lang.org", + "--extern-html-root-url=std=https://doc.rust-lang.org", +] ### FEATURES ################################################################# @@ -50,20 +43,20 @@ derive = ["serde_derive"] # Provide impls for common standard library types like Vec and HashMap. # Requires a dependency on the Rust standard library. -std = [] +std = ["serde_core/std"] # Provide impls for types that require unstable functionality. For tracking and # discussion of unstable functionality please refer to this issue: # # https://github.com/serde-rs/serde/issues/812 -unstable = [] +unstable = ["serde_core/unstable"] # Provide impls for types in the Rust core allocation and collections library # including String, Box, Vec, and Cow. This is a subset of std but may # be enabled without depending on all of std. -alloc = [] +alloc = ["serde_core/alloc"] # Opt into impls for Rc and Arc. Serializing and deserializing these types # does not preserve identity and may result in multiple copies of the same data. # Be sure that this is what you want before enabling this feature. -rc = [] +rc = ["serde_core/rc"] diff --git a/pkg/installer/vendor/serde/README.md b/pkg/installer/vendor/serde/README.md index 31292944af0..bf83d766272 100644 --- a/pkg/installer/vendor/serde/README.md +++ b/pkg/installer/vendor/serde/README.md @@ -1,4 +1,4 @@ -# Serde   [![Build Status]][actions] [![Latest Version]][crates.io] [![serde msrv]][Rust 1.31] [![serde_derive msrv]][Rust 1.56] +# Serde   [![Build Status]][actions] [![Latest Version]][crates.io] [![serde msrv]][Rust 1.56] [![serde_derive msrv]][Rust 1.61] [Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/serde/ci.yml?branch=master [actions]: https://github.com/serde-rs/serde/actions?query=branch%3Amaster @@ -6,8 +6,8 @@ [crates.io]: https://crates.io/crates/serde [serde msrv]: https://img.shields.io/crates/msrv/serde.svg?label=serde%20msrv&color=lightgray [serde_derive msrv]: https://img.shields.io/crates/msrv/serde_derive.svg?label=serde_derive%20msrv&color=lightgray -[Rust 1.31]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html [Rust 1.56]: https://blog.rust-lang.org/2021/10/21/Rust-1.56.0.html +[Rust 1.61]: https://blog.rust-lang.org/2022/05/19/Rust-1.61.0.html **Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** @@ -15,7 +15,7 @@ You may be looking for: -- [An overview of Serde](https://serde.rs/) +- [An overview of Serde](https://serde.rs) - [Data formats supported by Serde](https://serde.rs/#data-formats) - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) - [Examples](https://serde.rs/examples.html) @@ -27,7 +27,7 @@ You may be looking for:
Click to show Cargo.toml. -Run this code in the playground. +Run this code in the playground. ```toml diff --git a/pkg/installer/vendor/serde/build.rs b/pkg/installer/vendor/serde/build.rs index c32872b95d0..fa0fd5a0d93 100644 --- a/pkg/installer/vendor/serde/build.rs +++ b/pkg/installer/vendor/serde/build.rs @@ -1,6 +1,17 @@ use std::env; +use std::fs; +use std::path::PathBuf; use std::process::Command; -use std::str::{self, FromStr}; +use std::str; + +const PRIVATE: &str = "\ +#[doc(hidden)] +pub mod __private$$ { + #[doc(hidden)] + pub use crate::private::*; +} +use serde_core::__private$$ as serde_core_private; +"; // The rustc-cfg strings below are *not* public API. Please let us know by // opening a GitHub issue if your build environment requires some way to enable @@ -8,84 +19,37 @@ use std::str::{self, FromStr}; fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rustc-cfg=if_docsrs_then_no_serde_core"); + + let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); + let patch_version = env::var("CARGO_PKG_VERSION_PATCH").unwrap(); + let module = PRIVATE.replace("$$", &patch_version); + fs::write(out_dir.join("private.rs"), module).unwrap(); + let minor = match rustc_minor_version() { Some(minor) => minor, None => return, }; if minor >= 77 { + println!("cargo:rustc-check-cfg=cfg(feature, values(\"result\"))"); + println!("cargo:rustc-check-cfg=cfg(if_docsrs_then_no_serde_core)"); println!("cargo:rustc-check-cfg=cfg(no_core_cstr)"); + println!("cargo:rustc-check-cfg=cfg(no_core_error)"); + println!("cargo:rustc-check-cfg=cfg(no_core_net)"); println!("cargo:rustc-check-cfg=cfg(no_core_num_saturating)"); - println!("cargo:rustc-check-cfg=cfg(no_core_try_from)"); println!("cargo:rustc-check-cfg=cfg(no_diagnostic_namespace)"); - println!("cargo:rustc-check-cfg=cfg(no_float_copysign)"); - println!("cargo:rustc-check-cfg=cfg(no_num_nonzero_signed)"); - println!("cargo:rustc-check-cfg=cfg(no_relaxed_trait_bounds)"); println!("cargo:rustc-check-cfg=cfg(no_serde_derive)"); println!("cargo:rustc-check-cfg=cfg(no_std_atomic)"); println!("cargo:rustc-check-cfg=cfg(no_std_atomic64)"); - println!("cargo:rustc-check-cfg=cfg(no_systemtime_checked_add)"); println!("cargo:rustc-check-cfg=cfg(no_target_has_atomic)"); } - let target = env::var("TARGET").unwrap(); - let emscripten = target == "asmjs-unknown-emscripten" || target == "wasm32-unknown-emscripten"; - - // TryFrom, Atomic types, non-zero signed integers, and SystemTime::checked_add - // stabilized in Rust 1.34: - // https://blog.rust-lang.org/2019/04/11/Rust-1.34.0.html#tryfrom-and-tryinto - // https://blog.rust-lang.org/2019/04/11/Rust-1.34.0.html#library-stabilizations - if minor < 34 { - println!("cargo:rustc-cfg=no_core_try_from"); - println!("cargo:rustc-cfg=no_num_nonzero_signed"); - println!("cargo:rustc-cfg=no_systemtime_checked_add"); - println!("cargo:rustc-cfg=no_relaxed_trait_bounds"); - } - - // f32::copysign and f64::copysign stabilized in Rust 1.35. - // https://blog.rust-lang.org/2019/05/23/Rust-1.35.0.html#copy-the-sign-of-a-floating-point-number-onto-another - if minor < 35 { - println!("cargo:rustc-cfg=no_float_copysign"); - } - - // Current minimum supported version of serde_derive crate is Rust 1.56. - if minor < 56 { + // Current minimum supported version of serde_derive crate is Rust 1.61. + if minor < 61 { println!("cargo:rustc-cfg=no_serde_derive"); } - // Support for #[cfg(target_has_atomic = "...")] stabilized in Rust 1.60. - if minor < 60 { - println!("cargo:rustc-cfg=no_target_has_atomic"); - // Allowlist of archs that support std::sync::atomic module. This is - // based on rustc's compiler/rustc_target/src/spec/*.rs. - let has_atomic64 = target.starts_with("x86_64") - || target.starts_with("i686") - || target.starts_with("aarch64") - || target.starts_with("powerpc64") - || target.starts_with("sparc64") - || target.starts_with("mips64el") - || target.starts_with("riscv64"); - let has_atomic32 = has_atomic64 || emscripten; - if minor < 34 || !has_atomic64 { - println!("cargo:rustc-cfg=no_std_atomic64"); - } - if minor < 34 || !has_atomic32 { - println!("cargo:rustc-cfg=no_std_atomic"); - } - } - - // Support for core::ffi::CStr and alloc::ffi::CString stabilized in Rust 1.64. - // https://blog.rust-lang.org/2022/09/22/Rust-1.64.0.html#c-compatible-ffi-types-in-core-and-alloc - if minor < 64 { - println!("cargo:rustc-cfg=no_core_cstr"); - } - - // Support for core::num::Saturating and std::num::Saturating stabilized in Rust 1.74 - // https://blog.rust-lang.org/2023/11/16/Rust-1.74.0.html#stabilized-apis - if minor < 74 { - println!("cargo:rustc-cfg=no_core_num_saturating"); - } - // Support for the `#[diagnostic]` tool attribute namespace // https://blog.rust-lang.org/2024/05/02/Rust-1.78.0.html#diagnostic-attributes if minor < 78 { @@ -94,30 +58,12 @@ fn main() { } fn rustc_minor_version() -> Option { - let rustc = match env::var_os("RUSTC") { - Some(rustc) => rustc, - None => return None, - }; - - let output = match Command::new(rustc).arg("--version").output() { - Ok(output) => output, - Err(_) => return None, - }; - - let version = match str::from_utf8(&output.stdout) { - Ok(version) => version, - Err(_) => return None, - }; - + let rustc = env::var_os("RUSTC")?; + let output = Command::new(rustc).arg("--version").output().ok()?; + let version = str::from_utf8(&output.stdout).ok()?; let mut pieces = version.split('.'); if pieces.next() != Some("rustc 1") { return None; } - - let next = match pieces.next() { - Some(next) => next, - None => return None, - }; - - u32::from_str(next).ok() + pieces.next()?.parse().ok() } diff --git a/pkg/installer/vendor/serde/crates-io.md b/pkg/installer/vendor/serde/crates-io.md index b49a5483b91..e6e7d9fb6d6 100644 --- a/pkg/installer/vendor/serde/crates-io.md +++ b/pkg/installer/vendor/serde/crates-io.md @@ -6,7 +6,7 @@ You may be looking for: -- [An overview of Serde](https://serde.rs/) +- [An overview of Serde](https://serde.rs) - [Data formats supported by Serde](https://serde.rs/#data-formats) - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) - [Examples](https://serde.rs/examples.html) diff --git a/pkg/installer/vendor/serde/src/core/crate_root.rs b/pkg/installer/vendor/serde/src/core/crate_root.rs new file mode 100644 index 00000000000..2cf75a40196 --- /dev/null +++ b/pkg/installer/vendor/serde/src/core/crate_root.rs @@ -0,0 +1,171 @@ +macro_rules! crate_root { + () => { + /// A facade around all the types we need from the `std`, `core`, and `alloc` + /// crates. This avoids elaborate import wrangling having to happen in every + /// module. + mod lib { + mod core { + #[cfg(not(feature = "std"))] + pub use core::*; + #[cfg(feature = "std")] + pub use std::*; + } + + pub use self::core::{f32, f64}; + pub use self::core::{iter, num, str}; + + #[cfg(any(feature = "std", feature = "alloc"))] + pub use self::core::{cmp, mem}; + + pub use self::core::cell::{Cell, RefCell}; + pub use self::core::cmp::Reverse; + pub use self::core::fmt::{self, Debug, Display, Write as FmtWrite}; + pub use self::core::marker::PhantomData; + pub use self::core::num::Wrapping; + pub use self::core::ops::{Bound, Range, RangeFrom, RangeInclusive, RangeTo}; + pub use self::core::result; + pub use self::core::time::Duration; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::borrow::{Cow, ToOwned}; + #[cfg(feature = "std")] + pub use std::borrow::{Cow, ToOwned}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::string::{String, ToString}; + #[cfg(feature = "std")] + pub use std::string::{String, ToString}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::vec::Vec; + #[cfg(feature = "std")] + pub use std::vec::Vec; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::boxed::Box; + #[cfg(feature = "std")] + pub use std::boxed::Box; + + #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] + pub use alloc::rc::{Rc, Weak as RcWeak}; + #[cfg(all(feature = "rc", feature = "std"))] + pub use std::rc::{Rc, Weak as RcWeak}; + + #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] + pub use alloc::sync::{Arc, Weak as ArcWeak}; + #[cfg(all(feature = "rc", feature = "std"))] + pub use std::sync::{Arc, Weak as ArcWeak}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; + #[cfg(feature = "std")] + pub use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; + + #[cfg(all(not(no_core_cstr), not(feature = "std")))] + pub use self::core::ffi::CStr; + #[cfg(feature = "std")] + pub use std::ffi::CStr; + + #[cfg(all(not(no_core_cstr), feature = "alloc", not(feature = "std")))] + pub use alloc::ffi::CString; + #[cfg(feature = "std")] + pub use std::ffi::CString; + + #[cfg(all(not(no_core_net), not(feature = "std")))] + pub use self::core::net; + #[cfg(feature = "std")] + pub use std::net; + + #[cfg(feature = "std")] + pub use std::error; + + #[cfg(feature = "std")] + pub use std::collections::{HashMap, HashSet}; + #[cfg(feature = "std")] + pub use std::ffi::{OsStr, OsString}; + #[cfg(feature = "std")] + pub use std::hash::{BuildHasher, Hash}; + #[cfg(feature = "std")] + pub use std::io::Write; + #[cfg(feature = "std")] + pub use std::path::{Path, PathBuf}; + #[cfg(feature = "std")] + pub use std::sync::{Mutex, RwLock}; + #[cfg(feature = "std")] + pub use std::time::{SystemTime, UNIX_EPOCH}; + + #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic)))] + pub use std::sync::atomic::{ + AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, + AtomicU8, AtomicUsize, Ordering, + }; + #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic64)))] + pub use std::sync::atomic::{AtomicI64, AtomicU64}; + + #[cfg(all(feature = "std", not(no_target_has_atomic)))] + pub use std::sync::atomic::Ordering; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "8"))] + pub use std::sync::atomic::{AtomicBool, AtomicI8, AtomicU8}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "16"))] + pub use std::sync::atomic::{AtomicI16, AtomicU16}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "32"))] + pub use std::sync::atomic::{AtomicI32, AtomicU32}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "64"))] + pub use std::sync::atomic::{AtomicI64, AtomicU64}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "ptr"))] + pub use std::sync::atomic::{AtomicIsize, AtomicUsize}; + + #[cfg(not(no_core_num_saturating))] + pub use self::core::num::Saturating; + } + + // None of this crate's error handling needs the `From::from` error conversion + // performed implicitly by the `?` operator or the standard library's `try!` + // macro. This simplified macro gives a 5.5% improvement in compile time + // compared to standard `try!`, and 9% improvement compared to `?`. + macro_rules! tri { + ($expr:expr) => { + match $expr { + Ok(val) => val, + Err(err) => return Err(err), + } + }; + } + + #[cfg_attr(all(docsrs, if_docsrs_then_no_serde_core), path = "core/de/mod.rs")] + pub mod de; + #[cfg_attr(all(docsrs, if_docsrs_then_no_serde_core), path = "core/ser/mod.rs")] + pub mod ser; + + #[cfg_attr(all(docsrs, if_docsrs_then_no_serde_core), path = "core/format.rs")] + mod format; + + #[doc(inline)] + pub use crate::de::{Deserialize, Deserializer}; + #[doc(inline)] + pub use crate::ser::{Serialize, Serializer}; + + // Used by generated code. Not public API. + #[doc(hidden)] + #[cfg_attr( + all(docsrs, if_docsrs_then_no_serde_core), + path = "core/private/mod.rs" + )] + mod private; + + // Used by declarative macro generated code. Not public API. + #[doc(hidden)] + pub mod __private { + #[doc(hidden)] + pub use crate::private::doc; + #[doc(hidden)] + pub use core::result::Result; + } + + include!(concat!(env!("OUT_DIR"), "/private.rs")); + + #[cfg(all(not(feature = "std"), no_core_error))] + #[cfg_attr(all(docsrs, if_docsrs_then_no_serde_core), path = "core/std_error.rs")] + mod std_error; + }; +} diff --git a/pkg/installer/vendor/serde/src/de/ignored_any.rs b/pkg/installer/vendor/serde/src/core/de/ignored_any.rs similarity index 100% rename from pkg/installer/vendor/serde/src/de/ignored_any.rs rename to pkg/installer/vendor/serde/src/core/de/ignored_any.rs diff --git a/pkg/installer/vendor/serde/src/de/impls.rs b/pkg/installer/vendor/serde/src/core/de/impls.rs similarity index 96% rename from pkg/installer/vendor/serde/src/de/impls.rs rename to pkg/installer/vendor/serde/src/core/de/impls.rs index 02591d98225..ab1a893cc4d 100644 --- a/pkg/installer/vendor/serde/src/de/impls.rs +++ b/pkg/installer/vendor/serde/src/core/de/impls.rs @@ -4,11 +4,10 @@ use crate::de::{ Deserialize, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, Unexpected, VariantAccess, Visitor, }; - -use crate::seed::InPlaceSeed; +use crate::private::{self, InPlaceSeed}; #[cfg(any(feature = "std", feature = "alloc"))] -use crate::de::size_hint; +use crate::private::size_hint; //////////////////////////////////////////////////////////////////////////////// @@ -80,10 +79,9 @@ impl<'de> Deserialize<'de> for bool { //////////////////////////////////////////////////////////////////////////////// macro_rules! impl_deserialize_num { - ($primitive:ident, $nonzero:ident $(cfg($($cfg:tt)*))*, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => { + ($primitive:ident, $nonzero:ident, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => { impl_deserialize_num!($primitive, $deserialize $($method!($($val : $visit)*);)*); - $(#[cfg($($cfg)*)])* impl<'de> Deserialize<'de> for num::$nonzero { fn deserialize(deserializer: D) -> Result where @@ -228,12 +226,12 @@ macro_rules! num_as_copysign_self { where E: Error, { - #[cfg(any(no_float_copysign, not(feature = "std")))] + #[cfg(not(feature = "std"))] { Ok(v as Self::Value) } - #[cfg(all(not(no_float_copysign), feature = "std"))] + #[cfg(feature = "std")] { // Preserve sign of NaN. The `as` produces a nondeterministic sign. let sign = if v.is_sign_positive() { 1.0 } else { -1.0 }; @@ -250,13 +248,8 @@ macro_rules! int_to_int { where E: Error, { - if Self::Value::min_value() as i64 <= v as i64 - && v as i64 <= Self::Value::max_value() as i64 - { - Ok(v as Self::Value) - } else { - Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) - } + Self::Value::try_from(v as i64) + .map_err(|_| Error::invalid_value(Unexpected::Signed(v as i64), &self)) } }; @@ -265,10 +258,8 @@ macro_rules! int_to_int { where E: Error, { - if $primitive::min_value() as i64 <= v as i64 - && v as i64 <= $primitive::max_value() as i64 - { - if let Some(nonzero) = Self::Value::new(v as $primitive) { + if let Ok(v) = $primitive::try_from(v as i64) { + if let Some(nonzero) = Self::Value::new(v) { return Ok(nonzero); } } @@ -299,11 +290,13 @@ macro_rules! int_to_uint { where E: Error, { - if 0 <= v && v as u64 <= Self::Value::max_value() as u64 { - Ok(v as Self::Value) - } else { - Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) + if 0 <= v { + #[allow(irrefutable_let_patterns)] + if let Ok(v) = Self::Value::try_from(v as u64) { + return Ok(v as Self::Value); + } } + Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) } }; @@ -312,9 +305,12 @@ macro_rules! int_to_uint { where E: Error, { - if 0 < v && v as u64 <= $primitive::max_value() as u64 { - if let Some(nonzero) = Self::Value::new(v as $primitive) { - return Ok(nonzero); + if 0 < v { + #[allow(irrefutable_let_patterns)] + if let Ok(v) = $primitive::try_from(v as u64) { + if let Some(nonzero) = Self::Value::new(v) { + return Ok(nonzero); + } } } Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) @@ -344,11 +340,8 @@ macro_rules! uint_to_self { where E: Error, { - if v as u64 <= Self::Value::max_value() as u64 { - Ok(v as Self::Value) - } else { - Err(Error::invalid_value(Unexpected::Unsigned(v as u64), &self)) - } + Self::Value::try_from(v as u64) + .map_err(|_| Error::invalid_value(Unexpected::Unsigned(v as u64), &self)) } }; @@ -357,8 +350,8 @@ macro_rules! uint_to_self { where E: Error, { - if v as u64 <= $primitive::max_value() as u64 { - if let Some(nonzero) = Self::Value::new(v as $primitive) { + if let Ok(v) = $primitive::try_from(v as u64) { + if let Some(nonzero) = Self::Value::new(v) { return Ok(nonzero); } } @@ -371,7 +364,7 @@ macro_rules! uint_to_self { where E: Error, { - if v as u64 <= $primitive::MAX as u64 { + if let Ok(v) = $primitive::try_from(v as u64) { Ok(Saturating(v as $primitive)) } else { Ok(Saturating($primitive::MAX)) @@ -381,14 +374,14 @@ macro_rules! uint_to_self { } impl_deserialize_num! { - i8, NonZeroI8 cfg(not(no_num_nonzero_signed)), deserialize_i8 + i8, NonZeroI8, deserialize_i8 num_self!(i8:visit_i8); int_to_int!(i16:visit_i16 i32:visit_i32 i64:visit_i64); uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); } impl_deserialize_num! { - i16, NonZeroI16 cfg(not(no_num_nonzero_signed)), deserialize_i16 + i16, NonZeroI16, deserialize_i16 num_self!(i16:visit_i16); num_as_self!(i8:visit_i8); int_to_int!(i32:visit_i32 i64:visit_i64); @@ -396,7 +389,7 @@ impl_deserialize_num! { } impl_deserialize_num! { - i32, NonZeroI32 cfg(not(no_num_nonzero_signed)), deserialize_i32 + i32, NonZeroI32, deserialize_i32 num_self!(i32:visit_i32); num_as_self!(i8:visit_i8 i16:visit_i16); int_to_int!(i64:visit_i64); @@ -404,14 +397,14 @@ impl_deserialize_num! { } impl_deserialize_num! { - i64, NonZeroI64 cfg(not(no_num_nonzero_signed)), deserialize_i64 + i64, NonZeroI64, deserialize_i64 num_self!(i64:visit_i64); num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32); uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); } impl_deserialize_num! { - isize, NonZeroIsize cfg(not(no_num_nonzero_signed)), deserialize_i64 + isize, NonZeroIsize, deserialize_i64 num_as_self!(i8:visit_i8 i16:visit_i16); int_to_int!(i32:visit_i32 i64:visit_i64); uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); @@ -476,9 +469,7 @@ macro_rules! num_128 { where E: Error, { - if v as i128 >= Self::Value::min_value() as i128 - && v as u128 <= Self::Value::max_value() as u128 - { + if v as i128 >= Self::Value::MIN as i128 && v as u128 <= Self::Value::MAX as u128 { Ok(v as Self::Value) } else { Err(Error::invalid_value( @@ -494,9 +485,7 @@ macro_rules! num_128 { where E: Error, { - if v as i128 >= $primitive::min_value() as i128 - && v as u128 <= $primitive::max_value() as u128 - { + if v as i128 >= $primitive::MIN as i128 && v as u128 <= $primitive::MAX as u128 { if let Some(nonzero) = Self::Value::new(v as $primitive) { Ok(nonzero) } else { @@ -528,7 +517,7 @@ macro_rules! num_128 { } impl_deserialize_num! { - i128, NonZeroI128 cfg(not(no_num_nonzero_signed)), deserialize_i128 + i128, NonZeroI128, deserialize_i128 num_self!(i128:visit_i128); num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); @@ -1583,12 +1572,9 @@ map_impl! { //////////////////////////////////////////////////////////////////////////////// +#[cfg(any(feature = "std", not(no_core_net)))] macro_rules! parse_ip_impl { - ( - $(#[$attr:meta])* - $ty:ty, $expecting:expr, $size:tt - ) => { - $(#[$attr])* + ($ty:ty, $expecting:expr, $size:tt) => { impl<'de> Deserialize<'de> for $ty { fn deserialize(deserializer: D) -> Result where @@ -1604,7 +1590,7 @@ macro_rules! parse_ip_impl { }; } -#[cfg(feature = "std")] +#[cfg(any(feature = "std", not(no_core_net)))] macro_rules! variant_identifier { ( $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*) @@ -1679,7 +1665,7 @@ macro_rules! variant_identifier { } } -#[cfg(feature = "std")] +#[cfg(any(feature = "std", not(no_core_net)))] macro_rules! deserialize_enum { ( $name:ident $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*) @@ -1716,8 +1702,7 @@ macro_rules! deserialize_enum { } } -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(any(feature = "std", not(no_core_net)))] impl<'de> Deserialize<'de> for net::IpAddr { fn deserialize(deserializer: D) -> Result where @@ -1736,25 +1721,18 @@ impl<'de> Deserialize<'de> for net::IpAddr { } } -parse_ip_impl! { - #[cfg(feature = "std")] - #[cfg_attr(docsrs, doc(cfg(feature = "std")))] - net::Ipv4Addr, "IPv4 address", 4 -} +#[cfg(any(feature = "std", not(no_core_net)))] +parse_ip_impl!(net::Ipv4Addr, "IPv4 address", 4); -parse_ip_impl! { - #[cfg(feature = "std")] - #[cfg_attr(docsrs, doc(cfg(feature = "std")))] - net::Ipv6Addr, "IPv6 address", 16 -} +#[cfg(any(feature = "std", not(no_core_net)))] +parse_ip_impl!(net::Ipv6Addr, "IPv6 address", 16); +#[cfg(any(feature = "std", not(no_core_net)))] macro_rules! parse_socket_impl { ( - $(#[$attr:meta])* $ty:ty, $expecting:tt, $new:expr, ) => { - $(#[$attr])* impl<'de> Deserialize<'de> for $ty { fn deserialize(deserializer: D) -> Result where @@ -1770,8 +1748,7 @@ macro_rules! parse_socket_impl { }; } -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(any(feature = "std", not(no_core_net)))] impl<'de> Deserialize<'de> for net::SocketAddr { fn deserialize(deserializer: D) -> Result where @@ -1790,16 +1767,14 @@ impl<'de> Deserialize<'de> for net::SocketAddr { } } +#[cfg(any(feature = "std", not(no_core_net)))] parse_socket_impl! { - #[cfg(feature = "std")] - #[cfg_attr(docsrs, doc(cfg(feature = "std")))] net::SocketAddrV4, "IPv4 socket address", |(ip, port)| net::SocketAddrV4::new(ip, port), } +#[cfg(any(feature = "std", not(no_core_net)))] parse_socket_impl! { - #[cfg(feature = "std")] - #[cfg_attr(docsrs, doc(cfg(feature = "std")))] net::SocketAddrV6, "IPv6 socket address", |(ip, port)| net::SocketAddrV6::new(ip, port, 0, 0), } @@ -2198,7 +2173,7 @@ impl<'de> Deserialize<'de> for Duration { b"secs" => Ok(Field::Secs), b"nanos" => Ok(Field::Nanos), _ => { - let value = crate::__private::from_utf8_lossy(value); + let value = private::string::from_utf8_lossy(value); Err(Error::unknown_field(&*value, FIELDS)) } } @@ -2429,13 +2404,9 @@ impl<'de> Deserialize<'de> for SystemTime { const FIELDS: &[&str] = &["secs_since_epoch", "nanos_since_epoch"]; let duration = tri!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor)); - #[cfg(not(no_systemtime_checked_add))] - let ret = UNIX_EPOCH + UNIX_EPOCH .checked_add(duration) - .ok_or_else(|| D::Error::custom("overflow deserializing SystemTime")); - #[cfg(no_systemtime_checked_add)] - let ret = Ok(UNIX_EPOCH + duration); - ret + .ok_or_else(|| D::Error::custom("overflow deserializing SystemTime")) } } @@ -2493,6 +2464,7 @@ mod range { use crate::lib::*; use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + use crate::private; pub const FIELDS: &[&str] = &["start", "end"]; @@ -2538,7 +2510,7 @@ mod range { b"start" => Ok(Field::Start), b"end" => Ok(Field::End), _ => { - let value = crate::__private::from_utf8_lossy(value); + let value = private::string::from_utf8_lossy(value); Err(Error::unknown_field(&*value, FIELDS)) } } @@ -2651,6 +2623,7 @@ mod range_from { use crate::lib::*; use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + use crate::private; pub const FIELDS: &[&str] = &["start"]; @@ -2693,7 +2666,7 @@ mod range_from { match value { b"start" => Ok(Field::Start), _ => { - let value = crate::__private::from_utf8_lossy(value); + let value = private::string::from_utf8_lossy(value); Err(Error::unknown_field(&*value, FIELDS)) } } @@ -2789,6 +2762,7 @@ mod range_to { use crate::lib::*; use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + use crate::private; pub const FIELDS: &[&str] = &["end"]; @@ -2831,7 +2805,7 @@ mod range_to { match value { b"end" => Ok(Field::End), _ => { - let value = crate::__private::from_utf8_lossy(value); + let value = private::string::from_utf8_lossy(value); Err(Error::unknown_field(&*value, FIELDS)) } } @@ -3003,6 +2977,8 @@ where //////////////////////////////////////////////////////////////////////////////// +#[cfg(feature = "result")] +#[cfg_attr(docsrs, doc(cfg(feature = "result")))] impl<'de, T, E> Deserialize<'de> for Result where T: Deserialize<'de>, @@ -3160,13 +3136,13 @@ atomic_impl! { AtomicU64 "64" } -#[cfg(feature = "std")] +#[cfg(any(feature = "std", not(no_core_net)))] struct FromStrVisitor { expecting: &'static str, ty: PhantomData, } -#[cfg(feature = "std")] +#[cfg(any(feature = "std", not(no_core_net)))] impl FromStrVisitor { fn new(expecting: &'static str) -> Self { FromStrVisitor { @@ -3176,7 +3152,7 @@ impl FromStrVisitor { } } -#[cfg(feature = "std")] +#[cfg(any(feature = "std", not(no_core_net)))] impl<'de, T> Visitor<'de> for FromStrVisitor where T: str::FromStr, diff --git a/pkg/installer/vendor/serde/src/de/mod.rs b/pkg/installer/vendor/serde/src/core/de/mod.rs similarity index 96% rename from pkg/installer/vendor/serde/src/de/mod.rs rename to pkg/installer/vendor/serde/src/core/de/mod.rs index d6b9f5ab44b..2518ae68274 100644 --- a/pkg/installer/vendor/serde/src/de/mod.rs +++ b/pkg/installer/vendor/serde/src/core/de/mod.rs @@ -101,8 +101,8 @@ //! - SocketAddrV6 //! //! [Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html -//! [`Deserialize`]: ../trait.Deserialize.html -//! [`Deserializer`]: ../trait.Deserializer.html +//! [`Deserialize`]: crate::Deserialize +//! [`Deserializer`]: crate::Deserializer //! [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html //! [`postcard`]: https://github.com/jamesmunns/postcard //! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map @@ -118,17 +118,14 @@ use crate::lib::*; pub mod value; -mod format; mod ignored_any; mod impls; -pub(crate) mod size_hint; pub use self::ignored_any::IgnoredAny; - -#[cfg(not(any(feature = "std", feature = "unstable")))] +#[cfg(all(not(feature = "std"), no_core_error))] #[doc(no_inline)] pub use crate::std_error::Error as StdError; -#[cfg(all(feature = "unstable", not(feature = "std")))] +#[cfg(not(any(feature = "std", no_core_error)))] #[doc(no_inline)] pub use core::error::Error as StdError; #[cfg(feature = "std")] @@ -159,6 +156,12 @@ macro_rules! declare_error_trait { /// type appropriate for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html + #[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::Error` is not satisfied", + ) + )] pub trait Error: Sized $(+ $($supertrait)::+)* { /// Raised when there is general error when deserializing a type. /// @@ -207,7 +210,7 @@ macro_rules! declare_error_trait { /// containing an integer, the unexpected type is the integer and the /// expected type is the string. #[cold] - fn invalid_type(unexp: Unexpected, exp: &Expected) -> Self { + fn invalid_type(unexp: Unexpected, exp: &dyn Expected) -> Self { Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp)) } @@ -225,7 +228,7 @@ macro_rules! declare_error_trait { /// that is not valid UTF-8, the unexpected value is the bytes and the /// expected value is a string. #[cold] - fn invalid_value(unexp: Unexpected, exp: &Expected) -> Self { + fn invalid_value(unexp: Unexpected, exp: &dyn Expected) -> Self { Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp)) } @@ -239,7 +242,7 @@ macro_rules! declare_error_trait { /// expected. For example `exp` might say that a tuple of size 6 was /// expected. #[cold] - fn invalid_length(len: usize, exp: &Expected) -> Self { + fn invalid_length(len: usize, exp: &dyn Expected) -> Self { Error::custom(format_args!("invalid length {}, expected {}", len, exp)) } @@ -472,6 +475,12 @@ impl<'a> fmt::Display for Unexpected<'a> { /// )); /// # } /// ``` +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::Expected` is not satisfied", + ) +)] pub trait Expected { /// Format an explanation of what data was being expected. Same signature as /// the `Display` and `Debug` traits. @@ -487,13 +496,13 @@ where } } -impl<'a> Expected for &'a str { +impl Expected for &str { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(self) } } -impl<'a> Display for Expected + 'a { +impl Display for dyn Expected + '_ { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { Expected::fmt(self, formatter) } @@ -535,6 +544,9 @@ impl<'a> Display for Expected + 'a { #[cfg_attr( not(no_diagnostic_namespace), diagnostic::on_unimplemented( + // Prevents `serde_core::de::Deserialize` appearing in the error message + // in projects with no direct dependency on serde_core. + message = "the trait bound `{Self}: serde::Deserialize<'de>` is not satisfied", note = "for local types consider adding `#[derive(serde::Deserialize)]` to your `{Self}` type", note = "for types from other crates check whether the crate offers a `serde` feature flag", ) @@ -611,6 +623,12 @@ pub trait Deserialize<'de>: Sized { /// lifetimes]. /// /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::DeserializeOwned` is not satisfied", + ) +)] pub trait DeserializeOwned: for<'de> Deserialize<'de> {} impl DeserializeOwned for T where T: for<'de> Deserialize<'de> {} @@ -776,6 +794,12 @@ impl DeserializeOwned for T where T: for<'de> Deserialize<'de> {} /// # Ok(()) /// # } /// ``` +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::DeserializeSeed<'de>` is not satisfied", + ) +)] pub trait DeserializeSeed<'de>: Sized { /// The type produced by using this seed. type Value; @@ -912,6 +936,12 @@ where /// a basic JSON `Deserializer`. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::Deserializer<'de>` is not satisfied", + ) +)] pub trait Deserializer<'de>: Sized { /// The error type that can be returned if some error occurs during /// deserialization. @@ -1227,13 +1257,9 @@ pub trait Deserializer<'de>: Sized { // Not public API. #[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))] #[doc(hidden)] - fn __deserialize_content( - self, - _: crate::actually_private::T, - visitor: V, - ) -> Result, Self::Error> + fn __deserialize_content_v1(self, visitor: V) -> Result where - V: Visitor<'de, Value = crate::__private::de::Content<'de>>, + V: Visitor<'de, Value = crate::private::Content<'de>>, { self.deserialize_any(visitor) } @@ -1282,6 +1308,12 @@ pub trait Deserializer<'de>: Sized { /// } /// } /// ``` +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::Visitor<'de>` is not satisfied", + ) +)] pub trait Visitor<'de>: Sized { /// The value produced by this visitor. type Value; @@ -1374,7 +1406,7 @@ pub trait Visitor<'de>: Sized { E: Error, { let mut buf = [0u8; 58]; - let mut writer = format::Buf::new(&mut buf); + let mut writer = crate::format::Buf::new(&mut buf); fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as i128", v)).unwrap(); Err(Error::invalid_type( Unexpected::Other(writer.as_str()), @@ -1436,7 +1468,7 @@ pub trait Visitor<'de>: Sized { E: Error, { let mut buf = [0u8; 57]; - let mut writer = format::Buf::new(&mut buf); + let mut writer = crate::format::Buf::new(&mut buf); fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as u128", v)).unwrap(); Err(Error::invalid_type( Unexpected::Other(writer.as_str()), @@ -1708,6 +1740,12 @@ pub trait Visitor<'de>: Sized { /// implementation of `SeqAccess` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::SeqAccess<'de>` is not satisfied", + ) +)] pub trait SeqAccess<'de> { /// The error type that can be returned if some error occurs during /// deserialization. @@ -1742,7 +1780,7 @@ pub trait SeqAccess<'de> { } } -impl<'de, 'a, A> SeqAccess<'de> for &'a mut A +impl<'de, A> SeqAccess<'de> for &mut A where A: ?Sized + SeqAccess<'de>, { @@ -1790,6 +1828,12 @@ where /// implementation of `MapAccess` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::MapAccess<'de>` is not satisfied", + ) +)] pub trait MapAccess<'de> { /// The error type that can be returned if some error occurs during /// deserialization. @@ -1895,7 +1939,7 @@ pub trait MapAccess<'de> { } } -impl<'de, 'a, A> MapAccess<'de> for &'a mut A +impl<'de, A> MapAccess<'de> for &mut A where A: ?Sized + MapAccess<'de>, { @@ -1982,6 +2026,12 @@ where /// implementation of `EnumAccess` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::EnumAccess<'de>` is not satisfied", + ) +)] pub trait EnumAccess<'de>: Sized { /// The error type that can be returned if some error occurs during /// deserialization. @@ -2029,6 +2079,12 @@ pub trait EnumAccess<'de>: Sized { /// implementation of `VariantAccess` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::VariantAccess<'de>` is not satisfied", + ) +)] pub trait VariantAccess<'de>: Sized { /// The error type that can be returned if some error occurs during /// deserialization. Must match the error type of our `EnumAccess`. diff --git a/pkg/installer/vendor/serde/src/de/value.rs b/pkg/installer/vendor/serde/src/core/de/value.rs similarity index 93% rename from pkg/installer/vendor/serde/src/de/value.rs rename to pkg/installer/vendor/serde/src/core/de/value.rs index 1ec9477869f..3d5475def12 100644 --- a/pkg/installer/vendor/serde/src/de/value.rs +++ b/pkg/installer/vendor/serde/src/core/de/value.rs @@ -24,7 +24,8 @@ use crate::lib::*; use self::private::{First, Second}; -use crate::de::{self, size_hint, Deserializer, Expected, IntoDeserializer, SeqAccess, Visitor}; +use crate::de::{self, Deserializer, Expected, IntoDeserializer, SeqAccess, Visitor}; +use crate::private::size_hint; use crate::ser; //////////////////////////////////////////////////////////////////////////////// @@ -175,6 +176,17 @@ where } } +impl<'de, E> IntoDeserializer<'de, E> for UnitDeserializer +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + impl Debug for UnitDeserializer { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.debug_struct("UnitDeserializer").finish() @@ -225,6 +237,18 @@ where } } +#[cfg(feature = "unstable")] +impl<'de, E> IntoDeserializer<'de, E> for NeverDeserializer +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + //////////////////////////////////////////////////////////////////////////////// macro_rules! primitive_deserializer { @@ -279,6 +303,17 @@ macro_rules! primitive_deserializer { } } + impl<'de, E> IntoDeserializer<'de, E> for $name + where + E: de::Error, + { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } + } + impl Debug for $name { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter @@ -369,6 +404,17 @@ where } } +impl<'de, E> IntoDeserializer<'de, E> for U32Deserializer +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + impl<'de, E> de::EnumAccess<'de> for U32Deserializer where E: de::Error, @@ -458,6 +504,17 @@ where } } +impl<'de, 'a, E> IntoDeserializer<'de, E> for StrDeserializer<'a, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + impl<'de, 'a, E> de::EnumAccess<'de> for StrDeserializer<'a, E> where E: de::Error, @@ -537,6 +594,17 @@ where } } +impl<'de, E> IntoDeserializer<'de, E> for BorrowedStrDeserializer<'de, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + impl<'de, E> de::EnumAccess<'de> for BorrowedStrDeserializer<'de, E> where E: de::Error, @@ -640,6 +708,18 @@ where } } +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, E> IntoDeserializer<'de, E> for StringDeserializer +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + #[cfg(any(feature = "std", feature = "alloc"))] impl<'de, E> de::EnumAccess<'de> for StringDeserializer where @@ -748,6 +828,18 @@ where } } +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> IntoDeserializer<'de, E> for CowStrDeserializer<'a, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + #[cfg(any(feature = "std", feature = "alloc"))] impl<'de, 'a, E> de::EnumAccess<'de> for CowStrDeserializer<'a, E> where @@ -825,6 +917,17 @@ where } } +impl<'de, 'a, E> IntoDeserializer<'de, E> for BytesDeserializer<'a, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + impl<'a, E> Debug for BytesDeserializer<'a, E> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter @@ -873,6 +976,17 @@ where } } +impl<'de, E> IntoDeserializer<'de, E> for BorrowedBytesDeserializer<'de, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + impl<'de, E> Debug for BorrowedBytesDeserializer<'de, E> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter @@ -952,6 +1066,19 @@ where } } +impl<'de, I, T, E> IntoDeserializer<'de, E> for SeqDeserializer +where + I: Iterator, + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + impl<'de, I, T, E> de::SeqAccess<'de> for SeqDeserializer where I: Iterator, @@ -1083,6 +1210,17 @@ where } } +impl<'de, A> IntoDeserializer<'de, A::Error> for SeqAccessDeserializer +where + A: de::SeqAccess<'de>, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + //////////////////////////////////////////////////////////////////////////////// /// A deserializer that iterates over a map. @@ -1197,6 +1335,21 @@ where } } +impl<'de, I, E> IntoDeserializer<'de, E> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First: IntoDeserializer<'de, E>, + Second: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + impl<'de, I, E> de::MapAccess<'de> for MapDeserializer<'de, I, E> where I: Iterator, @@ -1498,6 +1651,17 @@ where } } +impl<'de, A> IntoDeserializer<'de, A::Error> for MapAccessDeserializer +where + A: de::MapAccess<'de>, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + impl<'de, A> de::EnumAccess<'de> for MapAccessDeserializer where A: de::MapAccess<'de>, @@ -1551,6 +1715,17 @@ where } } +impl<'de, A> IntoDeserializer<'de, A::Error> for EnumAccessDeserializer +where + A: de::EnumAccess<'de>, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + //////////////////////////////////////////////////////////////////////////////// mod private { diff --git a/pkg/installer/vendor/serde/src/de/format.rs b/pkg/installer/vendor/serde/src/core/format.rs similarity index 100% rename from pkg/installer/vendor/serde/src/de/format.rs rename to pkg/installer/vendor/serde/src/core/format.rs diff --git a/pkg/installer/vendor/serde/src/core/lib.rs b/pkg/installer/vendor/serde/src/core/lib.rs new file mode 100644 index 00000000000..58d143d79f7 --- /dev/null +++ b/pkg/installer/vendor/serde/src/core/lib.rs @@ -0,0 +1,121 @@ +//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data +//! structures efficiently and generically. +//! +//! The `serde_core` crate contains Serde's trait definitions with **no support +//! for #\[derive()\]**. +//! +//! In crates that derive an implementation of `Serialize` or `Deserialize`, you +//! must depend on the [`serde`] crate, not `serde_core`. +//! +//! [`serde`]: https://crates.io/crates/serde +//! +//! In crates that handwrite implementations of Serde traits, or only use them +//! as trait bounds, depending on `serde_core` is permitted. But `serde` +//! re-exports all of these traits and can be used for this use case too. If in +//! doubt, disregard `serde_core` and always use `serde`. +//! +//! Crates that depend on `serde_core` instead of `serde` are able to compile in +//! parallel with `serde_derive` even when `serde`'s "derive" feature is turned on, +//! as shown in the following build timings. +//! +//!
+//! +//! +//! +//! +//!
When serde_json depends on serde
+//! +//!
+//! +//! +//! +//! +//!
When serde_json depends on serde_core
+ +//////////////////////////////////////////////////////////////////////////////// + +// Serde types in rustdoc of other crates get linked to here. +#![doc(html_root_url = "https://docs.rs/serde_core/1.0.228")] +// Support using Serde without the standard library! +#![cfg_attr(not(feature = "std"), no_std)] +// Show which crate feature enables conditionally compiled APIs in documentation. +#![cfg_attr(docsrs, feature(doc_cfg, rustdoc_internals))] +#![cfg_attr(docsrs, allow(internal_features))] +// Unstable functionality only if the user asks for it. For tracking and +// discussion of these features please refer to this issue: +// +// https://github.com/serde-rs/serde/issues/812 +#![cfg_attr(feature = "unstable", feature(never_type))] +#![allow(unknown_lints, bare_trait_objects, deprecated)] +// Ignored clippy and clippy_pedantic lints +#![allow( + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704 + clippy::unnested_or_patterns, + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7768 + clippy::semicolon_if_nothing_returned, + // not available in our oldest supported compiler + clippy::empty_enum, + clippy::type_repetition_in_bounds, // https://github.com/rust-lang/rust-clippy/issues/8772 + // integer and float ser/de requires these sorts of casts + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_precision_loss, + clippy::cast_sign_loss, + // things are often more readable this way + clippy::cast_lossless, + clippy::module_name_repetitions, + clippy::single_match_else, + clippy::type_complexity, + clippy::use_self, + clippy::zero_prefixed_literal, + // correctly used + clippy::derive_partial_eq_without_eq, + clippy::enum_glob_use, + clippy::explicit_auto_deref, + clippy::incompatible_msrv, + clippy::let_underscore_untyped, + clippy::map_err_ignore, + clippy::new_without_default, + clippy::result_unit_err, + clippy::wildcard_imports, + // not practical + clippy::needless_pass_by_value, + clippy::similar_names, + clippy::too_many_lines, + // preference + clippy::doc_markdown, + clippy::elidable_lifetime_names, + clippy::needless_lifetimes, + clippy::unseparated_literal_suffix, + // false positive + clippy::needless_doctest_main, + // noisy + clippy::missing_errors_doc, + clippy::must_use_candidate, +)] +// Restrictions +#![deny(clippy::question_mark_used)] +// Rustc lints. +#![deny(missing_docs, unused_imports)] + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "alloc")] +extern crate alloc; + +#[macro_use] +mod crate_root; +#[macro_use] +mod macros; + +crate_root!(); + +#[macro_export] +#[doc(hidden)] +macro_rules! __require_serde_not_serde_core { + () => { + ::core::compile_error!( + "Serde derive requires a dependency on the serde crate, not serde_core" + ); + }; +} diff --git a/pkg/installer/vendor/serde/src/macros.rs b/pkg/installer/vendor/serde/src/core/macros.rs similarity index 97% rename from pkg/installer/vendor/serde/src/macros.rs rename to pkg/installer/vendor/serde/src/core/macros.rs index 9646cb375bf..b9567305005 100644 --- a/pkg/installer/vendor/serde/src/macros.rs +++ b/pkg/installer/vendor/serde/src/core/macros.rs @@ -1,7 +1,6 @@ // Super explicit first paragraph because this shows up at the top level and // trips up people who are just looking for basic Serialize / Deserialize // documentation. -// /// Helper macro when implementing the `Deserializer` part of a new data format /// for Serde. /// @@ -104,9 +103,9 @@ /// # } /// ``` /// -/// [`Deserializer`]: trait.Deserializer.html -/// [`Visitor`]: de/trait.Visitor.html -/// [`Deserializer::deserialize_any`]: trait.Deserializer.html#tymethod.deserialize_any +/// [`Deserializer`]: crate::Deserializer +/// [`Visitor`]: crate::de::Visitor +/// [`Deserializer::deserialize_any`]: crate::Deserializer::deserialize_any #[macro_export(local_inner_macros)] macro_rules! forward_to_deserialize_any { (<$visitor:ident: Visitor<$lifetime:tt>> $($func:ident)*) => { diff --git a/pkg/installer/vendor/serde/src/core/private/content.rs b/pkg/installer/vendor/serde/src/core/private/content.rs new file mode 100644 index 00000000000..f29a9b527d6 --- /dev/null +++ b/pkg/installer/vendor/serde/src/core/private/content.rs @@ -0,0 +1,39 @@ +use crate::lib::*; + +// Used from generated code to buffer the contents of the Deserializer when +// deserializing untagged enums and internally tagged enums. +// +// Not public API. Use serde-value instead. +// +// Obsoleted by format-specific buffer types (https://github.com/serde-rs/serde/pull/2912). +#[doc(hidden)] +pub enum Content<'de> { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Str(&'de str), + ByteBuf(Vec), + Bytes(&'de [u8]), + + None, + Some(Box>), + + Unit, + Newtype(Box>), + Seq(Vec>), + Map(Vec<(Content<'de>, Content<'de>)>), +} diff --git a/pkg/installer/vendor/serde/src/private/doc.rs b/pkg/installer/vendor/serde/src/core/private/doc.rs similarity index 95% rename from pkg/installer/vendor/serde/src/private/doc.rs rename to pkg/installer/vendor/serde/src/core/private/doc.rs index 1f17c8db534..2cc07f0d931 100644 --- a/pkg/installer/vendor/serde/src/private/doc.rs +++ b/pkg/installer/vendor/serde/src/core/private/doc.rs @@ -8,6 +8,7 @@ use crate::ser; #[derive(Debug)] pub struct Error; +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::Error for Error { fn custom(_: T) -> Self where @@ -18,12 +19,14 @@ impl ser::Error for Error { } #[cfg(feature = "std")] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl error::Error for Error { fn description(&self) -> &str { unimplemented!() } } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl Display for Error { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() diff --git a/pkg/installer/vendor/serde/src/core/private/mod.rs b/pkg/installer/vendor/serde/src/core/private/mod.rs new file mode 100644 index 00000000000..dd5f93fe963 --- /dev/null +++ b/pkg/installer/vendor/serde/src/core/private/mod.rs @@ -0,0 +1,21 @@ +#[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))] +mod content; +mod seed; + +// FIXME: #[cfg(doctest)] once https://github.com/rust-lang/rust/issues/67295 is fixed. +#[doc(hidden)] +pub mod doc; + +#[doc(hidden)] +pub mod size_hint; + +#[doc(hidden)] +pub mod string; + +#[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))] +#[doc(hidden)] +pub use self::content::Content; +#[doc(hidden)] +pub use self::seed::InPlaceSeed; +#[doc(hidden)] +pub use crate::lib::result::Result; diff --git a/pkg/installer/vendor/serde/src/de/seed.rs b/pkg/installer/vendor/serde/src/core/private/seed.rs similarity index 88% rename from pkg/installer/vendor/serde/src/de/seed.rs rename to pkg/installer/vendor/serde/src/core/private/seed.rs index 52fb89d8450..bcf267cb09b 100644 --- a/pkg/installer/vendor/serde/src/de/seed.rs +++ b/pkg/installer/vendor/serde/src/core/private/seed.rs @@ -5,6 +5,7 @@ use crate::de::{Deserialize, DeserializeSeed, Deserializer}; /// Wraps a mutable reference and calls deserialize_in_place on it. pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T); +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, 'de, T> DeserializeSeed<'de> for InPlaceSeed<'a, T> where T: Deserialize<'de>, diff --git a/pkg/installer/vendor/serde/src/de/size_hint.rs b/pkg/installer/vendor/serde/src/core/private/size_hint.rs similarity index 93% rename from pkg/installer/vendor/serde/src/de/size_hint.rs rename to pkg/installer/vendor/serde/src/core/private/size_hint.rs index 4a4fe25dc5d..783281b46c4 100644 --- a/pkg/installer/vendor/serde/src/de/size_hint.rs +++ b/pkg/installer/vendor/serde/src/core/private/size_hint.rs @@ -1,3 +1,4 @@ +#[cfg(any(feature = "std", feature = "alloc"))] use crate::lib::*; pub fn from_bounds(iter: &I) -> Option diff --git a/pkg/installer/vendor/serde/src/core/private/string.rs b/pkg/installer/vendor/serde/src/core/private/string.rs new file mode 100644 index 00000000000..c8121a0da71 --- /dev/null +++ b/pkg/installer/vendor/serde/src/core/private/string.rs @@ -0,0 +1,23 @@ +use crate::lib::*; + +#[cfg(any(feature = "std", feature = "alloc"))] +#[doc(hidden)] +pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<'_, str> { + String::from_utf8_lossy(bytes) +} + +// The generated code calls this like: +// +// let value = &_serde::__private::from_utf8_lossy(bytes); +// Err(_serde::de::Error::unknown_variant(value, VARIANTS)) +// +// so it is okay for the return type to be different from the std case as long +// as the above works. +#[cfg(not(any(feature = "std", feature = "alloc")))] +#[doc(hidden)] +pub fn from_utf8_lossy(bytes: &[u8]) -> &str { + // Three unicode replacement characters if it fails. They look like a + // white-on-black question mark. The user will recognize it as invalid + // UTF-8. + str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}") +} diff --git a/pkg/installer/vendor/serde/src/ser/fmt.rs b/pkg/installer/vendor/serde/src/core/ser/fmt.rs similarity index 98% rename from pkg/installer/vendor/serde/src/ser/fmt.rs rename to pkg/installer/vendor/serde/src/core/ser/fmt.rs index 04684aded01..4b1549f0897 100644 --- a/pkg/installer/vendor/serde/src/ser/fmt.rs +++ b/pkg/installer/vendor/serde/src/core/ser/fmt.rs @@ -35,7 +35,7 @@ macro_rules! fmt_primitives { /// } /// } /// ``` -impl<'a, 'b> Serializer for &'a mut fmt::Formatter<'b> { +impl<'a> Serializer for &mut fmt::Formatter<'a> { type Ok = (); type Error = fmt::Error; type SerializeSeq = Impossible<(), fmt::Error>; diff --git a/pkg/installer/vendor/serde/src/ser/impls.rs b/pkg/installer/vendor/serde/src/core/ser/impls.rs similarity index 91% rename from pkg/installer/vendor/serde/src/ser/impls.rs rename to pkg/installer/vendor/serde/src/core/ser/impls.rs index 557b6aa12f9..a7a175db946 100644 --- a/pkg/installer/vendor/serde/src/ser/impls.rs +++ b/pkg/installer/vendor/serde/src/core/ser/impls.rs @@ -185,11 +185,10 @@ where } } -#[cfg(not(no_relaxed_trait_bounds))] macro_rules! seq_impl { ( $(#[$attr:meta])* - $ty:ident + $ty:ident ) => { $(#[$attr])* impl Serialize for $ty @@ -207,45 +206,22 @@ macro_rules! seq_impl { } } -#[cfg(no_relaxed_trait_bounds)] -macro_rules! seq_impl { - ( - $(#[$attr:meta])* - $ty:ident - ) => { - $(#[$attr])* - impl Serialize for $ty - where - T: Serialize $(+ $tbound1 $(+ $tbound2)*)*, - $($typaram: $bound,)* - { - #[inline] - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.collect_seq(self) - } - } - } -} - seq_impl! { #[cfg(any(feature = "std", feature = "alloc"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] - BinaryHeap + BinaryHeap } seq_impl! { #[cfg(any(feature = "std", feature = "alloc"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] - BTreeSet + BTreeSet } seq_impl! { #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] - HashSet + HashSet } seq_impl! { @@ -445,7 +421,6 @@ tuple_impls! { //////////////////////////////////////////////////////////////////////////////// -#[cfg(not(no_relaxed_trait_bounds))] macro_rules! map_impl { ( $(#[$attr:meta])* @@ -468,30 +443,6 @@ macro_rules! map_impl { } } -#[cfg(no_relaxed_trait_bounds)] -macro_rules! map_impl { - ( - $(#[$attr:meta])* - $ty:ident - ) => { - $(#[$attr])* - impl Serialize for $ty - where - K: Serialize $(+ $kbound1 $(+ $kbound2)*)*, - V: Serialize, - $($typaram: $bound,)* - { - #[inline] - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.collect_map(self) - } - } - } -} - map_impl! { #[cfg(any(feature = "std", feature = "alloc"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] @@ -631,16 +582,6 @@ macro_rules! nonzero_integers { } } -nonzero_integers! { - NonZeroU8, - NonZeroU16, - NonZeroU32, - NonZeroU64, - NonZeroU128, - NonZeroUsize, -} - -#[cfg(not(no_num_nonzero_signed))] nonzero_integers! { NonZeroI8, NonZeroI16, @@ -648,6 +589,12 @@ nonzero_integers! { NonZeroI64, NonZeroI128, NonZeroIsize, + NonZeroU8, + NonZeroU16, + NonZeroU32, + NonZeroU64, + NonZeroU128, + NonZeroUsize, } impl Serialize for Cell @@ -713,6 +660,8 @@ where //////////////////////////////////////////////////////////////////////////////// +#[cfg(feature = "result")] +#[cfg_attr(docsrs, doc(cfg(feature = "result")))] impl Serialize for Result where T: Serialize, @@ -773,28 +722,17 @@ impl Serialize for SystemTime { /// statically known to never have more than a constant `MAX_LEN` bytes. /// /// Panics if the `Display` impl tries to write more than `MAX_LEN` bytes. -#[cfg(feature = "std")] +#[cfg(any(feature = "std", not(no_core_net)))] macro_rules! serialize_display_bounded_length { ($value:expr, $max:expr, $serializer:expr) => {{ let mut buffer = [0u8; $max]; - let remaining_len = { - let mut remaining = &mut buffer[..]; - write!(remaining, "{}", $value).unwrap(); - remaining.len() - }; - let written_len = buffer.len() - remaining_len; - let written = &buffer[..written_len]; - - // write! only provides fmt::Formatter to Display implementations, which - // has methods write_str and write_char but no method to write arbitrary - // bytes. Therefore `written` must be valid UTF-8. - let written_str = str::from_utf8(written).expect("must be valid UTF-8"); - $serializer.serialize_str(written_str) + let mut writer = crate::format::Buf::new(&mut buffer); + write!(&mut writer, "{}", $value).unwrap(); + $serializer.serialize_str(writer.as_str()) }}; } -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(any(feature = "std", not(no_core_net)))] impl Serialize for net::IpAddr { fn serialize(&self, serializer: S) -> Result where @@ -818,7 +756,7 @@ impl Serialize for net::IpAddr { } } -#[cfg(feature = "std")] +#[cfg(any(feature = "std", not(no_core_net)))] const DEC_DIGITS_LUT: &[u8] = b"\ 0001020304050607080910111213141516171819\ 2021222324252627282930313233343536373839\ @@ -826,7 +764,7 @@ const DEC_DIGITS_LUT: &[u8] = b"\ 6061626364656667686970717273747576777879\ 8081828384858687888990919293949596979899"; -#[cfg(feature = "std")] +#[cfg(any(feature = "std", not(no_core_net)))] #[inline] fn format_u8(mut n: u8, out: &mut [u8]) -> usize { if n >= 100 { @@ -847,7 +785,7 @@ fn format_u8(mut n: u8, out: &mut [u8]) -> usize { } } -#[cfg(feature = "std")] +#[cfg(any(feature = "std", not(no_core_net)))] #[test] fn test_format_u8() { let mut i = 0u8; @@ -864,8 +802,7 @@ fn test_format_u8() { } } -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(any(feature = "std", not(no_core_net)))] impl Serialize for net::Ipv4Addr { fn serialize(&self, serializer: S) -> Result where @@ -889,8 +826,7 @@ impl Serialize for net::Ipv4Addr { } } -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(any(feature = "std", not(no_core_net)))] impl Serialize for net::Ipv6Addr { fn serialize(&self, serializer: S) -> Result where @@ -906,8 +842,7 @@ impl Serialize for net::Ipv6Addr { } } -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(any(feature = "std", not(no_core_net)))] impl Serialize for net::SocketAddr { fn serialize(&self, serializer: S) -> Result where @@ -931,8 +866,7 @@ impl Serialize for net::SocketAddr { } } -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(any(feature = "std", not(no_core_net)))] impl Serialize for net::SocketAddrV4 { fn serialize(&self, serializer: S) -> Result where @@ -948,8 +882,7 @@ impl Serialize for net::SocketAddrV4 { } } -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(any(feature = "std", not(no_core_net)))] impl Serialize for net::SocketAddrV6 { fn serialize(&self, serializer: S) -> Result where diff --git a/pkg/installer/vendor/serde/src/ser/impossible.rs b/pkg/installer/vendor/serde/src/core/ser/impossible.rs similarity index 90% rename from pkg/installer/vendor/serde/src/ser/impossible.rs rename to pkg/installer/vendor/serde/src/core/ser/impossible.rs index 6432d5775af..fe69ae24e14 100644 --- a/pkg/installer/vendor/serde/src/ser/impossible.rs +++ b/pkg/installer/vendor/serde/src/core/ser/impossible.rs @@ -17,7 +17,7 @@ use crate::ser::{ /// /// ```edition2021 /// # use serde::ser::{Serializer, Impossible}; -/// # use serde::__private::doc::Error; +/// # use serde_core::__private::doc::Error; /// # /// # struct MySerializer; /// # @@ -41,7 +41,7 @@ use crate::ser::{ /// } /// /// /* other Serializer methods */ -/// # serde::__serialize_unimplemented! { +/// # serde_core::__serialize_unimplemented! { /// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none some /// # unit unit_struct unit_variant newtype_struct newtype_variant /// # tuple tuple_struct tuple_variant map struct struct_variant @@ -49,14 +49,14 @@ use crate::ser::{ /// } /// ``` /// -/// [`Serializer`]: trait.Serializer.html -/// [`SerializeSeq`]: trait.SerializeSeq.html -/// [`SerializeTuple`]: trait.SerializeTuple.html -/// [`SerializeTupleStruct`]: trait.SerializeTupleStruct.html -/// [`SerializeTupleVariant`]: trait.SerializeTupleVariant.html -/// [`SerializeMap`]: trait.SerializeMap.html -/// [`SerializeStruct`]: trait.SerializeStruct.html -/// [`SerializeStructVariant`]: trait.SerializeStructVariant.html +/// [`Serializer`]: crate::Serializer +/// [`SerializeSeq`]: crate::ser::SerializeSeq +/// [`SerializeTuple`]: crate::ser::SerializeTuple +/// [`SerializeTupleStruct`]: crate::ser::SerializeTupleStruct +/// [`SerializeTupleVariant`]: crate::ser::SerializeTupleVariant +/// [`SerializeMap`]: crate::ser::SerializeMap +/// [`SerializeStruct`]: crate::ser::SerializeStruct +/// [`SerializeStructVariant`]: crate::ser::SerializeStructVariant pub struct Impossible { void: Void, ok: PhantomData, diff --git a/pkg/installer/vendor/serde/src/ser/mod.rs b/pkg/installer/vendor/serde/src/core/ser/mod.rs similarity index 94% rename from pkg/installer/vendor/serde/src/ser/mod.rs rename to pkg/installer/vendor/serde/src/core/ser/mod.rs index 30a64809331..62e59d981d4 100644 --- a/pkg/installer/vendor/serde/src/ser/mod.rs +++ b/pkg/installer/vendor/serde/src/core/ser/mod.rs @@ -97,8 +97,8 @@ //! //! [Implementing `Serialize`]: https://serde.rs/impl-serialize.html //! [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html -//! [`Serialize`]: ../trait.Serialize.html -//! [`Serializer`]: ../trait.Serializer.html +//! [`Serialize`]: crate::Serialize +//! [`Serializer`]: crate::Serializer //! [`postcard`]: https://github.com/jamesmunns/postcard //! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map //! [`serde_derive`]: https://crates.io/crates/serde_derive @@ -115,10 +115,10 @@ mod impossible; pub use self::impossible::Impossible; -#[cfg(not(any(feature = "std", feature = "unstable")))] +#[cfg(all(not(feature = "std"), no_core_error))] #[doc(no_inline)] pub use crate::std_error::Error as StdError; -#[cfg(all(feature = "unstable", not(feature = "std")))] +#[cfg(not(any(feature = "std", no_core_error)))] #[doc(no_inline)] pub use core::error::Error as StdError; #[cfg(feature = "std")] @@ -139,6 +139,12 @@ macro_rules! declare_error_trait { /// type appropriate for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html + #[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::Error` is not satisfied", + ) + )] pub trait Error: Sized $(+ $($supertrait)::+)* { /// Used when a [`Serialize`] implementation encounters any error /// while serializing a type. @@ -173,8 +179,8 @@ macro_rules! declare_error_trait { /// } /// ``` /// - /// [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html - /// [`Serialize`]: ../trait.Serialize.html + /// [`Path`]: std::path::Path + /// [`Serialize`]: crate::Serialize fn custom(msg: T) -> Self where T: Display; @@ -218,6 +224,9 @@ declare_error_trait!(Error: Sized + Debug + Display); #[cfg_attr( not(no_diagnostic_namespace), diagnostic::on_unimplemented( + // Prevents `serde_core::ser::Serialize` appearing in the error message + // in projects with no direct dependency on serde_core. + message = "the trait bound `{Self}: serde::Serialize` is not satisfied", note = "for local types consider adding `#[derive(serde::Serialize)]` to your `{Self}` type", note = "for types from other crates check whether the crate offers a `serde` feature flag", ) @@ -337,6 +346,12 @@ pub trait Serialize { /// a basic JSON `Serializer`. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::Serializer` is not satisfied", + ) +)] pub trait Serializer: Sized { /// The output type produced by this `Serializer` during successful /// serialization. Most serializers that produce text or binary output @@ -345,7 +360,7 @@ pub trait Serializer: Sized { /// in-memory data structures may be simplified by using `Ok` to propagate /// the data structure around. /// - /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + /// [`io::Write`]: std::io::Write type Ok; /// The error type when some error occurs during serialization. @@ -398,7 +413,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for bool { /// fn serialize(&self, serializer: S) -> Result @@ -420,7 +435,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for i8 { /// fn serialize(&self, serializer: S) -> Result @@ -442,7 +457,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for i16 { /// fn serialize(&self, serializer: S) -> Result @@ -464,7 +479,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for i32 { /// fn serialize(&self, serializer: S) -> Result @@ -482,7 +497,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for i64 { /// fn serialize(&self, serializer: S) -> Result @@ -500,7 +515,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for i128 { /// fn serialize(&self, serializer: S) -> Result @@ -527,7 +542,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for u8 { /// fn serialize(&self, serializer: S) -> Result @@ -549,7 +564,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for u16 { /// fn serialize(&self, serializer: S) -> Result @@ -571,7 +586,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for u32 { /// fn serialize(&self, serializer: S) -> Result @@ -589,7 +604,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for u64 { /// fn serialize(&self, serializer: S) -> Result @@ -607,7 +622,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for u128 { /// fn serialize(&self, serializer: S) -> Result @@ -634,7 +649,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for f32 { /// fn serialize(&self, serializer: S) -> Result @@ -652,7 +667,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for f64 { /// fn serialize(&self, serializer: S) -> Result @@ -673,7 +688,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for char { /// fn serialize(&self, serializer: S) -> Result @@ -691,7 +706,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for str { /// fn serialize(&self, serializer: S) -> Result @@ -714,7 +729,7 @@ pub trait Serializer: Sized { /// /// ```edition2021 /// # use serde::ser::{Serializer, SerializeSeq}; - /// # use serde::__private::doc::Error; + /// # use serde_core::__private::doc::Error; /// # /// # struct MySerializer; /// # @@ -730,7 +745,7 @@ pub trait Serializer: Sized { /// seq.end() /// } /// # - /// # serde::__serialize_unimplemented! { + /// # serde_core::__serialize_unimplemented! { /// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some /// # unit unit_struct unit_variant newtype_struct newtype_variant /// # seq tuple tuple_struct tuple_variant map struct struct_variant @@ -769,7 +784,7 @@ pub trait Serializer: Sized { /// # fn main() {} /// ``` /// - /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None + /// [`None`]: core::option::Option::None fn serialize_none(self) -> Result; /// Serialize a [`Some(T)`] value. @@ -802,7 +817,7 @@ pub trait Serializer: Sized { /// # fn main() {} /// ``` /// - /// [`Some(T)`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some + /// [`Some(T)`]: core::option::Option::Some fn serialize_some(self, value: &T) -> Result where T: ?Sized + Serialize; @@ -812,7 +827,7 @@ pub trait Serializer: Sized { /// ```edition2021 /// # use serde::Serializer; /// # - /// # serde::__private_serialize!(); + /// # serde_core::__private_serialize!(); /// # /// impl Serialize for () { /// fn serialize(&self, serializer: S) -> Result @@ -1353,8 +1368,7 @@ pub trait Serializer: Sized { /// } /// ``` /// - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - /// [`serialize_str`]: #tymethod.serialize_str + /// [`serialize_str`]: Self::serialize_str #[cfg(any(feature = "std", feature = "alloc"))] fn collect_str(self, value: &T) -> Result where @@ -1495,6 +1509,12 @@ pub trait Serializer: Sized { /// implementation of `SerializeSeq` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeSeq` is not satisfied", + ) +)] pub trait SerializeSeq { /// Must match the `Ok` type of our `Serializer`. type Ok; @@ -1595,6 +1615,12 @@ pub trait SerializeSeq { /// implementation of `SerializeTuple` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeTuple` is not satisfied", + ) +)] pub trait SerializeTuple { /// Must match the `Ok` type of our `Serializer`. type Ok; @@ -1640,6 +1666,12 @@ pub trait SerializeTuple { /// implementation of `SerializeTupleStruct` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeTupleStruct` is not satisfied", + ) +)] pub trait SerializeTupleStruct { /// Must match the `Ok` type of our `Serializer`. type Ok; @@ -1698,6 +1730,12 @@ pub trait SerializeTupleStruct { /// implementation of `SerializeTupleVariant` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeTupleVariant` is not satisfied", + ) +)] pub trait SerializeTupleVariant { /// Must match the `Ok` type of our `Serializer`. type Ok; @@ -1764,6 +1802,12 @@ pub trait SerializeTupleVariant { /// implementation of `SerializeMap` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeMap` is not satisfied", + ) +)] pub trait SerializeMap { /// Must match the `Ok` type of our `Serializer`. type Ok; @@ -1805,9 +1849,9 @@ pub trait SerializeMap { /// care about performance or are not able to optimize `serialize_entry` any /// better than this. /// - /// [`Serialize`]: ../trait.Serialize.html - /// [`serialize_key`]: #tymethod.serialize_key - /// [`serialize_value`]: #tymethod.serialize_value + /// [`Serialize`]: crate::Serialize + /// [`serialize_key`]: Self::serialize_key + /// [`serialize_value`]: Self::serialize_value fn serialize_entry(&mut self, key: &K, value: &V) -> Result<(), Self::Error> where K: ?Sized + Serialize, @@ -1854,6 +1898,12 @@ pub trait SerializeMap { /// implementation of `SerializeStruct` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeStruct` is not satisfied", + ) +)] pub trait SerializeStruct { /// Must match the `Ok` type of our `Serializer`. type Ok; @@ -1918,6 +1968,12 @@ pub trait SerializeStruct { /// implementation of `SerializeStructVariant` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeStructVariant` is not satisfied", + ) +)] pub trait SerializeStructVariant { /// Must match the `Ok` type of our `Serializer`. type Ok; diff --git a/pkg/installer/vendor/serde/src/std_error.rs b/pkg/installer/vendor/serde/src/core/std_error.rs similarity index 95% rename from pkg/installer/vendor/serde/src/std_error.rs rename to pkg/installer/vendor/serde/src/core/std_error.rs index f15a4d74add..e026ace100f 100644 --- a/pkg/installer/vendor/serde/src/std_error.rs +++ b/pkg/installer/vendor/serde/src/core/std_error.rs @@ -42,7 +42,7 @@ use crate::lib::{Debug, Display}; /// ``` pub trait Error: Debug + Display { /// The underlying cause of this error, if any. - fn source(&self) -> Option<&(Error + 'static)> { + fn source(&self) -> Option<&(dyn Error + 'static)> { None } } diff --git a/pkg/installer/vendor/serde/src/integer128.rs b/pkg/installer/vendor/serde/src/integer128.rs index 2f94a644bee..c9ff9d64bd1 100644 --- a/pkg/installer/vendor/serde/src/integer128.rs +++ b/pkg/installer/vendor/serde/src/integer128.rs @@ -1,6 +1,11 @@ -// No longer used. Old versions of serde used this macro for supporting targets -// that did not yet have 128-bit integer support. #[macro_export] +#[deprecated = " +This macro has no effect on any version of Serde released in the past 2 years. +It was used long ago in crates that needed to support Rustc older than 1.26.0, +or Emscripten targets older than 1.40.0, which did not yet have 128-bit integer +support. These days Serde requires a Rust compiler newer than that so 128-bit +integers are always supported. +"] #[doc(hidden)] macro_rules! serde_if_integer128 { ($($tt:tt)*) => { diff --git a/pkg/installer/vendor/serde/src/lib.rs b/pkg/installer/vendor/serde/src/lib.rs index c65826d080e..ae495282bda 100644 --- a/pkg/installer/vendor/serde/src/lib.rs +++ b/pkg/installer/vendor/serde/src/lib.rs @@ -9,7 +9,7 @@ //! these two groups interact with each other, allowing any supported data //! structure to be serialized and deserialized using any supported data format. //! -//! See the Serde website for additional documentation and +//! See the Serde website for additional documentation and //! usage examples. //! //! ## Design @@ -95,7 +95,7 @@ //////////////////////////////////////////////////////////////////////////////// // Serde types in rustdoc of other crates get linked to here. -#![doc(html_root_url = "https://docs.rs/serde/1.0.207")] +#![doc(html_root_url = "https://docs.rs/serde/1.0.228")] // Support using Serde without the standard library! #![cfg_attr(not(feature = "std"), no_std)] // Show which crate feature enables conditionally compiled APIs in documentation. @@ -106,7 +106,12 @@ // // https://github.com/serde-rs/serde/issues/812 #![cfg_attr(feature = "unstable", feature(never_type))] -#![allow(unknown_lints, bare_trait_objects, deprecated)] +#![allow( + unknown_lints, + bare_trait_objects, + deprecated, + mismatched_lifetime_syntaxes +)] // Ignored clippy and clippy_pedantic lints #![allow( // clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704 @@ -144,6 +149,8 @@ clippy::too_many_lines, // preference clippy::doc_markdown, + clippy::elidable_lifetime_names, + clippy::needless_lifetimes, clippy::unseparated_literal_suffix, // false positive clippy::needless_doctest_main, @@ -161,166 +168,103 @@ #[cfg(feature = "alloc")] extern crate alloc; -/// A facade around all the types we need from the `std`, `core`, and `alloc` -/// crates. This avoids elaborate import wrangling having to happen in every -/// module. -mod lib { - mod core { - #[cfg(not(feature = "std"))] - pub use core::*; - #[cfg(feature = "std")] - pub use std::*; - } - - pub use self::core::{f32, f64}; - pub use self::core::{i16, i32, i64, i8, isize}; - pub use self::core::{iter, num, ptr, str}; - pub use self::core::{u16, u32, u64, u8, usize}; - - #[cfg(any(feature = "std", feature = "alloc"))] - pub use self::core::{cmp, mem, slice}; - - pub use self::core::cell::{Cell, RefCell}; - pub use self::core::clone; - pub use self::core::cmp::Reverse; - pub use self::core::convert; - pub use self::core::default; - pub use self::core::fmt::{self, Debug, Display, Write as FmtWrite}; - pub use self::core::marker::{self, PhantomData}; - pub use self::core::num::Wrapping; - pub use self::core::ops::{Bound, Range, RangeFrom, RangeInclusive, RangeTo}; - pub use self::core::option; - pub use self::core::result; - pub use self::core::time::Duration; - - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::borrow::{Cow, ToOwned}; - #[cfg(feature = "std")] - pub use std::borrow::{Cow, ToOwned}; - - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::string::{String, ToString}; - #[cfg(feature = "std")] - pub use std::string::{String, ToString}; - - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::vec::Vec; - #[cfg(feature = "std")] - pub use std::vec::Vec; - - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::boxed::Box; - #[cfg(feature = "std")] - pub use std::boxed::Box; - - #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] - pub use alloc::rc::{Rc, Weak as RcWeak}; - #[cfg(all(feature = "rc", feature = "std"))] - pub use std::rc::{Rc, Weak as RcWeak}; - - #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] - pub use alloc::sync::{Arc, Weak as ArcWeak}; - #[cfg(all(feature = "rc", feature = "std"))] - pub use std::sync::{Arc, Weak as ArcWeak}; - - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; - #[cfg(feature = "std")] - pub use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; - - #[cfg(all(not(no_core_cstr), not(feature = "std")))] - pub use self::core::ffi::CStr; - #[cfg(feature = "std")] - pub use std::ffi::CStr; +// Rustdoc has a lot of shortcomings related to cross-crate re-exports that make +// the rendered documentation of serde_core traits in serde more challenging to +// understand than the equivalent documentation of the same items in serde_core. +// https://github.com/rust-lang/rust/labels/A-cross-crate-reexports +// So, just for the purpose of docs.rs documentation, we inline the contents of +// serde_core into serde. This sidesteps all the cross-crate rustdoc bugs. +#[cfg(docsrs)] +#[macro_use] +#[path = "core/crate_root.rs"] +mod crate_root; - #[cfg(all(not(no_core_cstr), feature = "alloc", not(feature = "std")))] - pub use alloc::ffi::CString; - #[cfg(feature = "std")] - pub use std::ffi::CString; +#[cfg(docsrs)] +#[macro_use] +#[path = "core/macros.rs"] +mod macros; - #[cfg(feature = "std")] - pub use std::{error, net}; +#[cfg(not(docsrs))] +macro_rules! crate_root { + () => { + /// A facade around all the types we need from the `std`, `core`, and `alloc` + /// crates. This avoids elaborate import wrangling having to happen in every + /// module. + mod lib { + mod core { + #[cfg(not(feature = "std"))] + pub use core::*; + #[cfg(feature = "std")] + pub use std::*; + } + + pub use self::core::{f32, f64}; + pub use self::core::{ptr, str}; + + #[cfg(any(feature = "std", feature = "alloc"))] + pub use self::core::slice; + + pub use self::core::clone; + pub use self::core::convert; + pub use self::core::default; + pub use self::core::fmt::{self, Debug, Display, Write as FmtWrite}; + pub use self::core::marker::{self, PhantomData}; + pub use self::core::option; + pub use self::core::result; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::borrow::{Cow, ToOwned}; + #[cfg(feature = "std")] + pub use std::borrow::{Cow, ToOwned}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::string::{String, ToString}; + #[cfg(feature = "std")] + pub use std::string::{String, ToString}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::vec::Vec; + #[cfg(feature = "std")] + pub use std::vec::Vec; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::boxed::Box; + #[cfg(feature = "std")] + pub use std::boxed::Box; + } - #[cfg(feature = "std")] - pub use std::collections::{HashMap, HashSet}; - #[cfg(feature = "std")] - pub use std::ffi::{OsStr, OsString}; - #[cfg(feature = "std")] - pub use std::hash::{BuildHasher, Hash}; - #[cfg(feature = "std")] - pub use std::io::Write; - #[cfg(feature = "std")] - pub use std::path::{Path, PathBuf}; - #[cfg(feature = "std")] - pub use std::sync::{Mutex, RwLock}; - #[cfg(feature = "std")] - pub use std::time::{SystemTime, UNIX_EPOCH}; + // None of this crate's error handling needs the `From::from` error conversion + // performed implicitly by the `?` operator or the standard library's `try!` + // macro. This simplified macro gives a 5.5% improvement in compile time + // compared to standard `try!`, and 9% improvement compared to `?`. + #[cfg(not(no_serde_derive))] + macro_rules! tri { + ($expr:expr) => { + match $expr { + Ok(val) => val, + Err(err) => return Err(err), + } + }; + } - #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic)))] - pub use std::sync::atomic::{ - AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU8, - AtomicUsize, Ordering, - }; - #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic64)))] - pub use std::sync::atomic::{AtomicI64, AtomicU64}; + //////////////////////////////////////////////////////////////////////////////// - #[cfg(all(feature = "std", not(no_target_has_atomic)))] - pub use std::sync::atomic::Ordering; - #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "8"))] - pub use std::sync::atomic::{AtomicBool, AtomicI8, AtomicU8}; - #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "16"))] - pub use std::sync::atomic::{AtomicI16, AtomicU16}; - #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "32"))] - pub use std::sync::atomic::{AtomicI32, AtomicU32}; - #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "64"))] - pub use std::sync::atomic::{AtomicI64, AtomicU64}; - #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "ptr"))] - pub use std::sync::atomic::{AtomicIsize, AtomicUsize}; + pub use serde_core::{ + de, forward_to_deserialize_any, ser, Deserialize, Deserializer, Serialize, Serializer, + }; - #[cfg(not(no_core_num_saturating))] - pub use self::core::num::Saturating; -} + // Used by generated code and doc tests. Not public API. + #[doc(hidden)] + mod private; -// None of this crate's error handling needs the `From::from` error conversion -// performed implicitly by the `?` operator or the standard library's `try!` -// macro. This simplified macro gives a 5.5% improvement in compile time -// compared to standard `try!`, and 9% improvement compared to `?`. -macro_rules! tri { - ($expr:expr) => { - match $expr { - Ok(val) => val, - Err(err) => return Err(err), - } + include!(concat!(env!("OUT_DIR"), "/private.rs")); }; } -//////////////////////////////////////////////////////////////////////////////// - -#[macro_use] -mod macros; +crate_root!(); -#[macro_use] mod integer128; -pub mod de; -pub mod ser; - -#[doc(inline)] -pub use crate::de::{Deserialize, Deserializer}; -#[doc(inline)] -pub use crate::ser::{Serialize, Serializer}; - -// Used by generated code and doc tests. Not public API. -#[doc(hidden)] -#[path = "private/mod.rs"] -pub mod __private; - -#[path = "de/seed.rs"] -mod seed; - -#[cfg(not(any(feature = "std", feature = "unstable")))] -mod std_error; - // Re-export #[derive(Serialize, Deserialize)]. // // The reason re-exporting is not enabled by default is that disabling it would @@ -334,7 +278,8 @@ extern crate serde_derive; #[cfg_attr(docsrs, doc(cfg(feature = "derive")))] pub use serde_derive::{Deserialize, Serialize}; -#[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))] -mod actually_private { - pub struct T; +#[macro_export] +#[doc(hidden)] +macro_rules! __require_serde_not_serde_core { + () => {}; } diff --git a/pkg/installer/vendor/serde/src/private/de.rs b/pkg/installer/vendor/serde/src/private/de.rs index c402d2c66aa..6f657f50eb3 100644 --- a/pkg/installer/vendor/serde/src/private/de.rs +++ b/pkg/installer/vendor/serde/src/private/de.rs @@ -11,12 +11,13 @@ use crate::de::{MapAccess, Unexpected}; #[cfg(any(feature = "std", feature = "alloc"))] pub use self::content::{ - Content, ContentDeserializer, ContentRefDeserializer, EnumDeserializer, - InternallyTaggedUnitVisitor, TagContentOtherField, TagContentOtherFieldVisitor, - TagOrContentField, TagOrContentFieldVisitor, TaggedContentVisitor, UntaggedUnitVisitor, + content_as_str, Content, ContentDeserializer, ContentRefDeserializer, ContentVisitor, + EnumDeserializer, InternallyTaggedUnitVisitor, TagContentOtherField, + TagContentOtherFieldVisitor, TagOrContentField, TagOrContentFieldVisitor, TaggedContentVisitor, + UntaggedUnitVisitor, }; -pub use crate::seed::InPlaceSeed; +pub use crate::serde_core_private::InPlaceSeed; /// If the missing field is of type `Option` then treat is as `None`, /// otherwise it is an error. @@ -27,6 +28,7 @@ where { struct MissingFieldDeserializer(&'static str, PhantomData); + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, E> Deserializer<'de> for MissingFieldDeserializer where E: Error, @@ -47,7 +49,7 @@ where visitor.visit_none() } - forward_to_deserialize_any! { + serde_core::forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any @@ -66,6 +68,7 @@ where { struct CowStrVisitor; + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a> Visitor<'a> for CowStrVisitor { type Value = Cow<'a, str>; @@ -139,6 +142,7 @@ where { struct CowBytesVisitor; + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a> Visitor<'a> for CowBytesVisitor { type Value = Cow<'a, [u8]>; @@ -208,123 +212,104 @@ mod content { use crate::lib::*; - use crate::actually_private; - use crate::de::value::{MapDeserializer, SeqDeserializer}; use crate::de::{ - self, size_hint, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Expected, - IgnoredAny, MapAccess, SeqAccess, Unexpected, Visitor, + self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Expected, IgnoredAny, + MapAccess, SeqAccess, Unexpected, Visitor, }; - - /// Used from generated code to buffer the contents of the Deserializer when - /// deserializing untagged enums and internally tagged enums. - /// - /// Not public API. Use serde-value instead. - #[derive(Debug, Clone)] - pub enum Content<'de> { - Bool(bool), - - U8(u8), - U16(u16), - U32(u32), - U64(u64), - - I8(i8), - I16(i16), - I32(i32), - I64(i64), - - F32(f32), - F64(f64), - - Char(char), - String(String), - Str(&'de str), - ByteBuf(Vec), - Bytes(&'de [u8]), - - None, - Some(Box>), - - Unit, - Newtype(Box>), - Seq(Vec>), - Map(Vec<(Content<'de>, Content<'de>)>), + use crate::serde_core_private::size_hint; + pub use crate::serde_core_private::Content; + + pub fn content_as_str<'a, 'de>(content: &'a Content<'de>) -> Option<&'a str> { + match *content { + Content::Str(x) => Some(x), + Content::String(ref x) => Some(x), + Content::Bytes(x) => str::from_utf8(x).ok(), + Content::ByteBuf(ref x) => str::from_utf8(x).ok(), + _ => None, + } + } + + fn content_clone<'de>(content: &Content<'de>) -> Content<'de> { + match content { + Content::Bool(b) => Content::Bool(*b), + Content::U8(n) => Content::U8(*n), + Content::U16(n) => Content::U16(*n), + Content::U32(n) => Content::U32(*n), + Content::U64(n) => Content::U64(*n), + Content::I8(n) => Content::I8(*n), + Content::I16(n) => Content::I16(*n), + Content::I32(n) => Content::I32(*n), + Content::I64(n) => Content::I64(*n), + Content::F32(f) => Content::F32(*f), + Content::F64(f) => Content::F64(*f), + Content::Char(c) => Content::Char(*c), + Content::String(s) => Content::String(s.clone()), + Content::Str(s) => Content::Str(*s), + Content::ByteBuf(b) => Content::ByteBuf(b.clone()), + Content::Bytes(b) => Content::Bytes(b), + Content::None => Content::None, + Content::Some(content) => Content::Some(Box::new(content_clone(content))), + Content::Unit => Content::Unit, + Content::Newtype(content) => Content::Newtype(Box::new(content_clone(content))), + Content::Seq(seq) => Content::Seq(seq.iter().map(content_clone).collect()), + Content::Map(map) => Content::Map( + map.iter() + .map(|(k, v)| (content_clone(k), content_clone(v))) + .collect(), + ), + } + } + + #[cold] + fn content_unexpected<'a, 'de>(content: &'a Content<'de>) -> Unexpected<'a> { + match *content { + Content::Bool(b) => Unexpected::Bool(b), + Content::U8(n) => Unexpected::Unsigned(n as u64), + Content::U16(n) => Unexpected::Unsigned(n as u64), + Content::U32(n) => Unexpected::Unsigned(n as u64), + Content::U64(n) => Unexpected::Unsigned(n), + Content::I8(n) => Unexpected::Signed(n as i64), + Content::I16(n) => Unexpected::Signed(n as i64), + Content::I32(n) => Unexpected::Signed(n as i64), + Content::I64(n) => Unexpected::Signed(n), + Content::F32(f) => Unexpected::Float(f as f64), + Content::F64(f) => Unexpected::Float(f), + Content::Char(c) => Unexpected::Char(c), + Content::String(ref s) => Unexpected::Str(s), + Content::Str(s) => Unexpected::Str(s), + Content::ByteBuf(ref b) => Unexpected::Bytes(b), + Content::Bytes(b) => Unexpected::Bytes(b), + Content::None | Content::Some(_) => Unexpected::Option, + Content::Unit => Unexpected::Unit, + Content::Newtype(_) => Unexpected::NewtypeStruct, + Content::Seq(_) => Unexpected::Seq, + Content::Map(_) => Unexpected::Map, + } + } + + pub struct ContentVisitor<'de> { + value: PhantomData>, } - impl<'de> Content<'de> { - pub fn as_str(&self) -> Option<&str> { - match *self { - Content::Str(x) => Some(x), - Content::String(ref x) => Some(x), - Content::Bytes(x) => str::from_utf8(x).ok(), - Content::ByteBuf(ref x) => str::from_utf8(x).ok(), - _ => None, - } + impl<'de> ContentVisitor<'de> { + pub fn new() -> Self { + ContentVisitor { value: PhantomData } } + } - #[cold] - fn unexpected(&self) -> Unexpected { - match *self { - Content::Bool(b) => Unexpected::Bool(b), - Content::U8(n) => Unexpected::Unsigned(n as u64), - Content::U16(n) => Unexpected::Unsigned(n as u64), - Content::U32(n) => Unexpected::Unsigned(n as u64), - Content::U64(n) => Unexpected::Unsigned(n), - Content::I8(n) => Unexpected::Signed(n as i64), - Content::I16(n) => Unexpected::Signed(n as i64), - Content::I32(n) => Unexpected::Signed(n as i64), - Content::I64(n) => Unexpected::Signed(n), - Content::F32(f) => Unexpected::Float(f as f64), - Content::F64(f) => Unexpected::Float(f), - Content::Char(c) => Unexpected::Char(c), - Content::String(ref s) => Unexpected::Str(s), - Content::Str(s) => Unexpected::Str(s), - Content::ByteBuf(ref b) => Unexpected::Bytes(b), - Content::Bytes(b) => Unexpected::Bytes(b), - Content::None | Content::Some(_) => Unexpected::Option, - Content::Unit => Unexpected::Unit, - Content::Newtype(_) => Unexpected::NewtypeStruct, - Content::Seq(_) => Unexpected::Seq, - Content::Map(_) => Unexpected::Map, - } - } - } - - impl<'de> Deserialize<'de> for Content<'de> { - fn deserialize(deserializer: D) -> Result + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de> DeserializeSeed<'de> for ContentVisitor<'de> { + type Value = Content<'de>; + + fn deserialize(self, deserializer: D) -> Result where D: Deserializer<'de>, { - // Untagged and internally tagged enums are only supported in - // self-describing formats. - let visitor = ContentVisitor { value: PhantomData }; - deserializer.__deserialize_content(actually_private::T, visitor) - } - } - - impl<'de, E> de::IntoDeserializer<'de, E> for Content<'de> - where - E: de::Error, - { - type Deserializer = ContentDeserializer<'de, E>; - - fn into_deserializer(self) -> Self::Deserializer { - ContentDeserializer::new(self) - } - } - - /// Used to capture data in [`Content`] from other deserializers. - /// Cannot capture externally tagged enums, `i128` and `u128`. - struct ContentVisitor<'de> { - value: PhantomData>, - } - - impl<'de> ContentVisitor<'de> { - fn new() -> Self { - ContentVisitor { value: PhantomData } + deserializer.__deserialize_content_v1(self) } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de> Visitor<'de> for ContentVisitor<'de> { type Value = Content<'de>; @@ -476,14 +461,16 @@ mod content { where D: Deserializer<'de>, { - Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v))) + let v = tri!(ContentVisitor::new().deserialize(deserializer)); + Ok(Content::Some(Box::new(v))) } fn visit_newtype_struct(self, deserializer: D) -> Result where D: Deserializer<'de>, { - Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v))) + let v = tri!(ContentVisitor::new().deserialize(deserializer)); + Ok(Content::Newtype(Box::new(v))) } fn visit_seq(self, mut visitor: V) -> Result @@ -492,7 +479,7 @@ mod content { { let mut vec = Vec::::with_capacity(size_hint::cautious::(visitor.size_hint())); - while let Some(e) = tri!(visitor.next_element()) { + while let Some(e) = tri!(visitor.next_element_seed(ContentVisitor::new())) { vec.push(e); } Ok(Content::Seq(vec)) @@ -506,7 +493,9 @@ mod content { Vec::<(Content, Content)>::with_capacity( size_hint::cautious::<(Content, Content)>(visitor.size_hint()), ); - while let Some(kv) = tri!(visitor.next_entry()) { + while let Some(kv) = + tri!(visitor.next_entry_seed(ContentVisitor::new(), ContentVisitor::new())) + { vec.push(kv); } Ok(Content::Map(vec)) @@ -546,6 +535,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de> DeserializeSeed<'de> for TagOrContentVisitor<'de> { type Value = TagOrContent<'de>; @@ -559,6 +549,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de> Visitor<'de> for TagOrContentVisitor<'de> { type Value = TagOrContent<'de>; @@ -840,6 +831,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, T> Visitor<'de> for TaggedContentVisitor where T: Deserialize<'de>, @@ -861,7 +853,7 @@ mod content { } }; let rest = de::value::SeqAccessDeserializer::new(seq); - Ok((tag, tri!(Content::deserialize(rest)))) + Ok((tag, tri!(ContentVisitor::new().deserialize(rest)))) } fn visit_map(self, mut map: M) -> Result @@ -882,7 +874,7 @@ mod content { tag = Some(tri!(map.next_value())); } TagOrContent::Content(k) => { - let v = tri!(map.next_value()); + let v = tri!(map.next_value_seed(ContentVisitor::new())); vec.push((k, v)); } } @@ -904,10 +896,13 @@ mod content { /// Not public API. pub struct TagOrContentFieldVisitor { + /// Name of the tag field of the adjacently tagged enum pub tag: &'static str, + /// Name of the content field of the adjacently tagged enum pub content: &'static str, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor { type Value = TagOrContentField; @@ -919,6 +914,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de> Visitor<'de> for TagOrContentFieldVisitor { type Value = TagOrContentField; @@ -979,10 +975,13 @@ mod content { /// Not public API. pub struct TagContentOtherFieldVisitor { + /// Name of the tag field of the adjacently tagged enum pub tag: &'static str, + /// Name of the content field of the adjacently tagged enum pub content: &'static str, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de> DeserializeSeed<'de> for TagContentOtherFieldVisitor { type Value = TagContentOtherField; @@ -994,6 +993,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de> Visitor<'de> for TagContentOtherFieldVisitor { type Value = TagContentOtherField; @@ -1048,8 +1048,8 @@ mod content { E: de::Error, { #[cold] - fn invalid_type(self, exp: &Expected) -> E { - de::Error::invalid_type(self.content.unexpected(), exp) + fn invalid_type(self, exp: &dyn Expected) -> E { + de::Error::invalid_type(content_unexpected(&self.content), exp) } fn deserialize_integer(self, visitor: V) -> Result @@ -1094,8 +1094,7 @@ mod content { V: Visitor<'de>, E: de::Error, { - let seq = content.into_iter().map(ContentDeserializer::new); - let mut seq_visitor = SeqDeserializer::new(seq); + let mut seq_visitor = SeqDeserializer::new(content); let value = tri!(visitor.visit_seq(&mut seq_visitor)); tri!(seq_visitor.end()); Ok(value) @@ -1109,10 +1108,7 @@ mod content { V: Visitor<'de>, E: de::Error, { - let map = content - .into_iter() - .map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v))); - let mut map_visitor = MapDeserializer::new(map); + let mut map_visitor = MapDeserializer::new(content); let value = tri!(visitor.visit_map(&mut map_visitor)); tri!(map_visitor.end()); Ok(value) @@ -1120,6 +1116,7 @@ mod content { /// Used when deserializing an internally tagged enum because the content /// will be used exactly once. + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, E> Deserializer<'de> for ContentDeserializer<'de, E> where E: de::Error, @@ -1453,7 +1450,7 @@ mod content { s @ Content::String(_) | s @ Content::Str(_) => (s, None), other => { return Err(de::Error::invalid_type( - other.unexpected(), + content_unexpected(&other), &"string or map", )); } @@ -1485,11 +1482,7 @@ mod content { visitor.visit_unit() } - fn __deserialize_content( - self, - _: actually_private::T, - visitor: V, - ) -> Result, Self::Error> + fn __deserialize_content_v1(self, visitor: V) -> Result where V: Visitor<'de, Value = Content<'de>>, { @@ -1508,6 +1501,369 @@ mod content { } } + struct SeqDeserializer<'de, E> { + iter: > as IntoIterator>::IntoIter, + count: usize, + marker: PhantomData, + } + + impl<'de, E> SeqDeserializer<'de, E> { + fn new(content: Vec>) -> Self { + SeqDeserializer { + iter: content.into_iter(), + count: 0, + marker: PhantomData, + } + } + } + + impl<'de, E> SeqDeserializer<'de, E> + where + E: de::Error, + { + fn end(self) -> Result<(), E> { + let remaining = self.iter.count(); + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInSeq(self.count), + )) + } + } + } + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de, E> Deserializer<'de> for SeqDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn deserialize_any(mut self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let v = tri!(visitor.visit_seq(&mut self)); + tri!(self.end()); + Ok(v) + } + + serde_core::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } + } + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de, E> SeqAccess<'de> for SeqDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn next_element_seed(&mut self, seed: V) -> Result, Self::Error> + where + V: DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => { + self.count += 1; + seed.deserialize(ContentDeserializer::new(value)).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } + } + + struct ExpectedInSeq(usize); + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl Expected for ExpectedInSeq { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + formatter.write_str("1 element in sequence") + } else { + write!(formatter, "{} elements in sequence", self.0) + } + } + } + + struct MapDeserializer<'de, E> { + iter: , Content<'de>)> as IntoIterator>::IntoIter, + value: Option>, + count: usize, + error: PhantomData, + } + + impl<'de, E> MapDeserializer<'de, E> { + fn new(content: Vec<(Content<'de>, Content<'de>)>) -> Self { + MapDeserializer { + iter: content.into_iter(), + value: None, + count: 0, + error: PhantomData, + } + } + } + + impl<'de, E> MapDeserializer<'de, E> + where + E: de::Error, + { + fn end(self) -> Result<(), E> { + let remaining = self.iter.count(); + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInMap(self.count), + )) + } + } + } + + impl<'de, E> MapDeserializer<'de, E> { + fn next_pair(&mut self) -> Option<(Content<'de>, Content<'de>)> { + match self.iter.next() { + Some((k, v)) => { + self.count += 1; + Some((k, v)) + } + None => None, + } + } + } + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de, E> Deserializer<'de> for MapDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn deserialize_any(mut self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let value = tri!(visitor.visit_map(&mut self)); + tri!(self.end()); + Ok(value) + } + + fn deserialize_seq(mut self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let value = tri!(visitor.visit_seq(&mut self)); + tri!(self.end()); + Ok(value) + } + + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + let _ = len; + self.deserialize_seq(visitor) + } + + serde_core::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct tuple_struct map + struct enum identifier ignored_any + } + } + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de, E> MapAccess<'de> for MapDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn next_key_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(ContentDeserializer::new(key)).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed(&mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + let value = self.value.take(); + // Panic because this indicates a bug in the program rather than an + // expected failure. + let value = value.expect("MapAccess::next_value called before next_key"); + seed.deserialize(ContentDeserializer::new(value)) + } + + fn next_entry_seed( + &mut self, + kseed: TK, + vseed: TV, + ) -> Result, Self::Error> + where + TK: DeserializeSeed<'de>, + TV: DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + let key = tri!(kseed.deserialize(ContentDeserializer::new(key))); + let value = tri!(vseed.deserialize(ContentDeserializer::new(value))); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } + } + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de, E> SeqAccess<'de> for MapDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((k, v)) => { + let de = PairDeserializer(k, v, PhantomData); + seed.deserialize(de).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } + } + + struct PairDeserializer<'de, E>(Content<'de>, Content<'de>, PhantomData); + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de, E> Deserializer<'de> for PairDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + serde_core::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct tuple_struct map + struct enum identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData); + let pair = tri!(visitor.visit_seq(&mut pair_visitor)); + if pair_visitor.1.is_none() { + Ok(pair) + } else { + let remaining = pair_visitor.size_hint().unwrap(); + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining))) + } + } + + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + if len == 2 { + self.deserialize_seq(visitor) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(len))) + } + } + } + + struct PairVisitor<'de, E>(Option>, Option>, PhantomData); + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de, E> SeqAccess<'de> for PairVisitor<'de, E> + where + E: de::Error, + { + type Error = E; + + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>, + { + if let Some(k) = self.0.take() { + seed.deserialize(ContentDeserializer::new(k)).map(Some) + } else if let Some(v) = self.1.take() { + seed.deserialize(ContentDeserializer::new(v)).map(Some) + } else { + Ok(None) + } + } + + fn size_hint(&self) -> Option { + if self.0.is_some() { + Some(2) + } else if self.1.is_some() { + Some(1) + } else { + Some(0) + } + } + } + + struct ExpectedInMap(usize); + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl Expected for ExpectedInMap { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + formatter.write_str("1 element in map") + } else { + write!(formatter, "{} elements in map", self.0) + } + } + } + pub struct EnumDeserializer<'de, E> where E: de::Error, @@ -1530,6 +1886,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E> where E: de::Error, @@ -1558,6 +1915,7 @@ mod content { err: PhantomData, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E> where E: de::Error, @@ -1590,10 +1948,10 @@ mod content { { match self.value { Some(Content::Seq(v)) => { - de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor) + de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor) } Some(other) => Err(de::Error::invalid_type( - other.unexpected(), + content_unexpected(&other), &"tuple variant", )), None => Err(de::Error::invalid_type( @@ -1613,13 +1971,13 @@ mod content { { match self.value { Some(Content::Map(v)) => { - de::Deserializer::deserialize_any(MapDeserializer::new(v.into_iter()), visitor) + de::Deserializer::deserialize_any(MapDeserializer::new(v), visitor) } Some(Content::Seq(v)) => { - de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor) + de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor) } Some(other) => Err(de::Error::invalid_type( - other.unexpected(), + content_unexpected(&other), &"struct variant", )), None => Err(de::Error::invalid_type( @@ -1641,8 +1999,8 @@ mod content { E: de::Error, { #[cold] - fn invalid_type(self, exp: &Expected) -> E { - de::Error::invalid_type(self.content.unexpected(), exp) + fn invalid_type(self, exp: &dyn Expected) -> E { + de::Error::invalid_type(content_unexpected(self.content), exp) } fn deserialize_integer(self, visitor: V) -> Result @@ -1690,8 +2048,7 @@ mod content { V: Visitor<'de>, E: de::Error, { - let seq = content.iter().map(ContentRefDeserializer::new); - let mut seq_visitor = SeqDeserializer::new(seq); + let mut seq_visitor = SeqRefDeserializer::new(content); let value = tri!(visitor.visit_seq(&mut seq_visitor)); tri!(seq_visitor.end()); Ok(value) @@ -1705,13 +2062,7 @@ mod content { V: Visitor<'de>, E: de::Error, { - let map = content.iter().map(|(k, v)| { - ( - ContentRefDeserializer::new(k), - ContentRefDeserializer::new(v), - ) - }); - let mut map_visitor = MapDeserializer::new(map); + let mut map_visitor = MapRefDeserializer::new(content); let value = tri!(visitor.visit_map(&mut map_visitor)); tri!(map_visitor.end()); Ok(value) @@ -1719,6 +2070,7 @@ mod content { /// Used when deserializing an untagged enum because the content may need /// to be used more than once. + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, 'de, E> where E: de::Error, @@ -1894,10 +2246,19 @@ mod content { where V: Visitor<'de>, { + // Covered by tests/test_enum_untagged.rs + // with_optional_field::* match *self.content { Content::None => visitor.visit_none(), Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), Content::Unit => visitor.visit_unit(), + // This case is to support data formats which do not encode an + // indication whether a value is optional. An example of such a + // format is JSON, and a counterexample is RON. When requesting + // `deserialize_any` in JSON, the data format never performs + // `Visitor::visit_some` but we still must be able to + // deserialize the resulting Content into data structures with + // optional fields. _ => visitor.visit_some(self), } } @@ -1927,10 +2288,21 @@ mod content { where V: Visitor<'de>, { + // Covered by tests/test_enum_untagged.rs + // newtype_struct match *self.content { Content::Newtype(ref v) => { visitor.visit_newtype_struct(ContentRefDeserializer::new(v)) } + // This case is to support data formats that encode newtype + // structs and their underlying data the same, with no + // indication whether a newtype wrapper was present. For example + // JSON does this, while RON does not. In RON a newtype's name + // is included in the serialized representation and it knows to + // call `Visitor::visit_newtype_struct` from `deserialize_any`. + // JSON's `deserialize_any` never calls `visit_newtype_struct` + // but in this code we still must be able to deserialize the + // resulting Content into newtypes. _ => visitor.visit_newtype_struct(self), } } @@ -2023,7 +2395,7 @@ mod content { ref s @ Content::String(_) | ref s @ Content::Str(_) => (s, None), ref other => { return Err(de::Error::invalid_type( - other.unexpected(), + content_unexpected(other), &"string or map", )); } @@ -2058,16 +2430,12 @@ mod content { visitor.visit_unit() } - fn __deserialize_content( - self, - _: actually_private::T, - visitor: V, - ) -> Result, Self::Error> + fn __deserialize_content_v1(self, visitor: V) -> Result where V: Visitor<'de, Value = Content<'de>>, { let _ = visitor; - Ok(self.content.clone()) + Ok(content_clone(self.content)) } } @@ -2081,176 +2449,329 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, 'de: 'a, E> Copy for ContentRefDeserializer<'a, 'de, E> {} + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, 'de: 'a, E> Clone for ContentRefDeserializer<'a, 'de, E> { fn clone(&self) -> Self { *self } } - struct EnumRefDeserializer<'a, 'de: 'a, E> - where - E: de::Error, - { - variant: &'a Content<'de>, - value: Option<&'a Content<'de>>, - err: PhantomData, + struct SeqRefDeserializer<'a, 'de, E> { + iter: <&'a [Content<'de>] as IntoIterator>::IntoIter, + count: usize, + marker: PhantomData, } - impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E> + impl<'a, 'de, E> SeqRefDeserializer<'a, 'de, E> { + fn new(content: &'a [Content<'de>]) -> Self { + SeqRefDeserializer { + iter: content.iter(), + count: 0, + marker: PhantomData, + } + } + } + + impl<'a, 'de, E> SeqRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + fn end(self) -> Result<(), E> { + let remaining = self.iter.count(); + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInSeq(self.count), + )) + } + } + } + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'a, 'de, E> Deserializer<'de> for SeqRefDeserializer<'a, 'de, E> where E: de::Error, { type Error = E; - type Variant = VariantRefDeserializer<'a, 'de, Self::Error>; - fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + fn deserialize_any(mut self, visitor: V) -> Result where - V: de::DeserializeSeed<'de>, + V: Visitor<'de>, { - let visitor = VariantRefDeserializer { - value: self.value, - err: PhantomData, - }; - seed.deserialize(ContentRefDeserializer::new(self.variant)) - .map(|v| (v, visitor)) + let v = tri!(visitor.visit_seq(&mut self)); + tri!(self.end()); + Ok(v) + } + + serde_core::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any } } - struct VariantRefDeserializer<'a, 'de: 'a, E> + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'a, 'de, E> SeqAccess<'de> for SeqRefDeserializer<'a, 'de, E> where E: de::Error, { + type Error = E; + + fn next_element_seed(&mut self, seed: V) -> Result, Self::Error> + where + V: DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => { + self.count += 1; + seed.deserialize(ContentRefDeserializer::new(value)) + .map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } + } + + struct MapRefDeserializer<'a, 'de, E> { + iter: <&'a [(Content<'de>, Content<'de>)] as IntoIterator>::IntoIter, value: Option<&'a Content<'de>>, - err: PhantomData, + count: usize, + error: PhantomData, } - impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E> + impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E> { + fn new(content: &'a [(Content<'de>, Content<'de>)]) -> Self { + MapRefDeserializer { + iter: content.iter(), + value: None, + count: 0, + error: PhantomData, + } + } + } + + impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E> where E: de::Error, { - type Error = E; + fn end(self) -> Result<(), E> { + let remaining = self.iter.count(); + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInMap(self.count), + )) + } + } + } - fn unit_variant(self) -> Result<(), E> { - match self.value { - Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)), - None => Ok(()), + impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E> { + fn next_pair(&mut self) -> Option<(&'a Content<'de>, &'a Content<'de>)> { + match self.iter.next() { + Some((k, v)) => { + self.count += 1; + Some((k, v)) + } + None => None, } } + } - fn newtype_variant_seed(self, seed: T) -> Result + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'a, 'de, E> Deserializer<'de> for MapRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + + fn deserialize_any(mut self, visitor: V) -> Result where - T: de::DeserializeSeed<'de>, + V: Visitor<'de>, { - match self.value { - Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), - None => Err(de::Error::invalid_type( - de::Unexpected::UnitVariant, - &"newtype variant", - )), - } + let value = tri!(visitor.visit_map(&mut self)); + tri!(self.end()); + Ok(value) } - fn tuple_variant(self, _len: usize, visitor: V) -> Result + fn deserialize_seq(mut self, visitor: V) -> Result where - V: de::Visitor<'de>, + V: Visitor<'de>, { - match self.value { - Some(Content::Seq(v)) => { - de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type( - other.unexpected(), - &"tuple variant", - )), - None => Err(de::Error::invalid_type( - de::Unexpected::UnitVariant, - &"tuple variant", - )), - } + let value = tri!(visitor.visit_seq(&mut self)); + tri!(self.end()); + Ok(value) } - fn struct_variant( - self, - _fields: &'static [&'static str], - visitor: V, - ) -> Result + fn deserialize_tuple(self, len: usize, visitor: V) -> Result where - V: de::Visitor<'de>, + V: Visitor<'de>, { - match self.value { - Some(Content::Map(v)) => { - de::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor) - } - Some(Content::Seq(v)) => { - de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type( - other.unexpected(), - &"struct variant", - )), - None => Err(de::Error::invalid_type( - de::Unexpected::UnitVariant, - &"struct variant", - )), - } + let _ = len; + self.deserialize_seq(visitor) + } + + serde_core::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct tuple_struct map + struct enum identifier ignored_any } } - struct SeqRefDeserializer<'a, 'de: 'a, E> + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'a, 'de, E> MapAccess<'de> for MapRefDeserializer<'a, 'de, E> where E: de::Error, { - iter: <&'a [Content<'de>] as IntoIterator>::IntoIter, - err: PhantomData, + type Error = E; + + fn next_key_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(ContentRefDeserializer::new(key)).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed(&mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + let value = self.value.take(); + // Panic because this indicates a bug in the program rather than an + // expected failure. + let value = value.expect("MapAccess::next_value called before next_key"); + seed.deserialize(ContentRefDeserializer::new(value)) + } + + fn next_entry_seed( + &mut self, + kseed: TK, + vseed: TV, + ) -> Result, Self::Error> + where + TK: DeserializeSeed<'de>, + TV: DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + let key = tri!(kseed.deserialize(ContentRefDeserializer::new(key))); + let value = tri!(vseed.deserialize(ContentRefDeserializer::new(value))); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } } - impl<'a, 'de, E> SeqRefDeserializer<'a, 'de, E> + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'a, 'de, E> SeqAccess<'de> for MapRefDeserializer<'a, 'de, E> where E: de::Error, { - fn new(slice: &'a [Content<'de>]) -> Self { - SeqRefDeserializer { - iter: slice.iter(), - err: PhantomData, + type Error = E; + + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((k, v)) => { + let de = PairRefDeserializer(k, v, PhantomData); + seed.deserialize(de).map(Some) + } + None => Ok(None), } } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } } - impl<'de, 'a, E> de::Deserializer<'de> for SeqRefDeserializer<'a, 'de, E> + struct PairRefDeserializer<'a, 'de, E>(&'a Content<'de>, &'a Content<'de>, PhantomData); + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'a, 'de, E> Deserializer<'de> for PairRefDeserializer<'a, 'de, E> where E: de::Error, { type Error = E; - #[inline] - fn deserialize_any(mut self, visitor: V) -> Result + serde_core::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct tuple_struct map + struct enum identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result where - V: de::Visitor<'de>, + V: Visitor<'de>, { - let len = self.iter.len(); - if len == 0 { - visitor.visit_unit() + self.deserialize_seq(visitor) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let mut pair_visitor = PairRefVisitor(Some(self.0), Some(self.1), PhantomData); + let pair = tri!(visitor.visit_seq(&mut pair_visitor)); + if pair_visitor.1.is_none() { + Ok(pair) } else { - let ret = tri!(visitor.visit_seq(&mut self)); - let remaining = self.iter.len(); - if remaining == 0 { - Ok(ret) - } else { - Err(de::Error::invalid_length(len, &"fewer elements in array")) - } + let remaining = pair_visitor.size_hint().unwrap(); + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining))) } } - forward_to_deserialize_any! { - bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string - bytes byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + if len == 2 { + self.deserialize_seq(visitor) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(len))) + } } } - impl<'de, 'a, E> de::SeqAccess<'de> for SeqRefDeserializer<'a, 'de, E> + struct PairRefVisitor<'a, 'de, E>( + Option<&'a Content<'de>>, + Option<&'a Content<'de>>, + PhantomData, + ); + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'a, 'de, E> SeqAccess<'de> for PairRefVisitor<'a, 'de, E> where E: de::Error, { @@ -2258,98 +2779,154 @@ mod content { fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> where - T: de::DeserializeSeed<'de>, + T: DeserializeSeed<'de>, { - match self.iter.next() { - Some(value) => seed - .deserialize(ContentRefDeserializer::new(value)) - .map(Some), - None => Ok(None), + if let Some(k) = self.0.take() { + seed.deserialize(ContentRefDeserializer::new(k)).map(Some) + } else if let Some(v) = self.1.take() { + seed.deserialize(ContentRefDeserializer::new(v)).map(Some) + } else { + Ok(None) } } fn size_hint(&self) -> Option { - size_hint::from_bounds(&self.iter) + if self.0.is_some() { + Some(2) + } else if self.1.is_some() { + Some(1) + } else { + Some(0) + } } } - struct MapRefDeserializer<'a, 'de: 'a, E> + struct EnumRefDeserializer<'a, 'de: 'a, E> where E: de::Error, { - iter: <&'a [(Content<'de>, Content<'de>)] as IntoIterator>::IntoIter, + variant: &'a Content<'de>, value: Option<&'a Content<'de>>, err: PhantomData, } - impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E> + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E> where E: de::Error, { - fn new(map: &'a [(Content<'de>, Content<'de>)]) -> Self { - MapRefDeserializer { - iter: map.iter(), - value: None, + type Error = E; + type Variant = VariantRefDeserializer<'a, 'de, Self::Error>; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where + V: de::DeserializeSeed<'de>, + { + let visitor = VariantRefDeserializer { + value: self.value, err: PhantomData, - } + }; + seed.deserialize(ContentRefDeserializer::new(self.variant)) + .map(|v| (v, visitor)) } } - impl<'de, 'a, E> de::MapAccess<'de> for MapRefDeserializer<'a, 'de, E> + struct VariantRefDeserializer<'a, 'de: 'a, E> + where + E: de::Error, + { + value: Option<&'a Content<'de>>, + err: PhantomData, + } + + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] + impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E> where E: de::Error, { type Error = E; - fn next_key_seed(&mut self, seed: T) -> Result, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - match self.iter.next() { - Some((key, value)) => { - self.value = Some(value); - seed.deserialize(ContentRefDeserializer::new(key)).map(Some) - } - None => Ok(None), + fn unit_variant(self) -> Result<(), E> { + match self.value { + Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)), + // Covered by tests/test_annotations.rs + // test_partially_untagged_adjacently_tagged_enum + // Covered by tests/test_enum_untagged.rs + // newtype_enum::unit + None => Ok(()), } } - fn next_value_seed(&mut self, seed: T) -> Result + fn newtype_variant_seed(self, seed: T) -> Result where T: de::DeserializeSeed<'de>, { - match self.value.take() { + match self.value { + // Covered by tests/test_annotations.rs + // test_partially_untagged_enum_desugared + // test_partially_untagged_enum_generic + // Covered by tests/test_enum_untagged.rs + // newtype_enum::newtype Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), - None => Err(de::Error::custom("value is missing")), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"newtype variant", + )), } } - fn size_hint(&self) -> Option { - size_hint::from_bounds(&self.iter) - } - } - - impl<'de, 'a, E> de::Deserializer<'de> for MapRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - type Error = E; - - #[inline] - fn deserialize_any(self, visitor: V) -> Result + fn tuple_variant(self, _len: usize, visitor: V) -> Result where V: de::Visitor<'de>, { - visitor.visit_map(self) + match self.value { + // Covered by tests/test_annotations.rs + // test_partially_untagged_enum + // test_partially_untagged_enum_desugared + // Covered by tests/test_enum_untagged.rs + // newtype_enum::tuple0 + // newtype_enum::tuple2 + Some(Content::Seq(v)) => visit_content_seq_ref(v, visitor), + Some(other) => Err(de::Error::invalid_type( + content_unexpected(other), + &"tuple variant", + )), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"tuple variant", + )), + } } - forward_to_deserialize_any! { - bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string - bytes byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any + fn struct_variant( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + match self.value { + // Covered by tests/test_enum_untagged.rs + // newtype_enum::struct_from_map + Some(Content::Map(v)) => visit_content_map_ref(v, visitor), + // Covered by tests/test_enum_untagged.rs + // newtype_enum::struct_from_seq + // newtype_enum::empty_struct_from_seq + Some(Content::Seq(v)) => visit_content_seq_ref(v, visitor), + Some(other) => Err(de::Error::invalid_type( + content_unexpected(other), + &"struct variant", + )), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"struct variant", + )), + } } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E> where E: de::Error, @@ -2361,6 +2938,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, 'de, E> where E: de::Error, @@ -2390,6 +2968,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> { type Value = (); @@ -2435,6 +3014,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> { type Value = (); @@ -2482,6 +3062,7 @@ pub trait IdentifierDeserializer<'de, E: Error> { pub struct Borrowed<'de, T: 'de + ?Sized>(pub &'de T); +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, E> IdentifierDeserializer<'de, E> for u64 where E: Error, @@ -2498,6 +3079,7 @@ pub struct StrDeserializer<'a, E> { marker: PhantomData, } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E> where E: Error, @@ -2511,7 +3093,7 @@ where visitor.visit_str(self.value) } - forward_to_deserialize_any! { + serde_core::forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any @@ -2523,6 +3105,7 @@ pub struct BorrowedStrDeserializer<'de, E> { marker: PhantomData, } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, E> Deserializer<'de> for BorrowedStrDeserializer<'de, E> where E: Error, @@ -2536,13 +3119,14 @@ where visitor.visit_borrowed_str(self.value) } - forward_to_deserialize_any! { + serde_core::forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any } } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, E> IdentifierDeserializer<'a, E> for &'a str where E: Error, @@ -2557,6 +3141,7 @@ where } } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, E> IdentifierDeserializer<'de, E> for Borrowed<'de, str> where E: Error, @@ -2571,6 +3156,7 @@ where } } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, E> IdentifierDeserializer<'a, E> for &'a [u8] where E: Error, @@ -2582,6 +3168,7 @@ where } } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, E> IdentifierDeserializer<'de, E> for Borrowed<'de, [u8]> where E: Error, @@ -2624,6 +3211,7 @@ macro_rules! forward_to_deserialize_other { } #[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, 'de, E> Deserializer<'de> for FlatMapDeserializer<'a, 'de, E> where E: Error, @@ -2710,6 +3298,17 @@ where visitor.visit_unit() } + fn deserialize_unit_struct( + self, + _name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } + fn deserialize_ignored_any(self, visitor: V) -> Result where V: Visitor<'de>, @@ -2734,7 +3333,6 @@ where deserialize_string() deserialize_bytes() deserialize_byte_buf() - deserialize_unit_struct(&'static str) deserialize_seq() deserialize_tuple(usize) deserialize_tuple_struct(&'static str, usize) @@ -2750,6 +3348,7 @@ struct FlatMapAccess<'a, 'de: 'a, E> { } #[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, 'de, E> MapAccess<'de> for FlatMapAccess<'a, 'de, E> where E: Error, @@ -2794,6 +3393,7 @@ struct FlatStructAccess<'a, 'de: 'a, E> { } #[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, 'de, E> MapAccess<'de> for FlatStructAccess<'a, 'de, E> where E: Error, @@ -2836,7 +3436,7 @@ fn flat_map_take_entry<'de>( // and if the field is one recognized by the current data structure. let is_recognized = match entry { None => false, - Some((k, _v)) => k.as_str().map_or(false, |name| recognized.contains(&name)), + Some((k, _v)) => content_as_str(k).map_or(false, |name| recognized.contains(&name)), }; if is_recognized { @@ -2857,6 +3457,7 @@ pub struct AdjacentlyTaggedEnumVariantVisitor { fields_enum: PhantomData, } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, F> Visitor<'de> for AdjacentlyTaggedEnumVariantVisitor where F: Deserialize<'de>, @@ -2877,6 +3478,7 @@ where } } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'de, F> DeserializeSeed<'de> for AdjacentlyTaggedEnumVariantSeed where F: Deserialize<'de>, diff --git a/pkg/installer/vendor/serde/src/private/mod.rs b/pkg/installer/vendor/serde/src/private/mod.rs index 177f8501b58..20bfa4eb886 100644 --- a/pkg/installer/vendor/serde/src/private/mod.rs +++ b/pkg/installer/vendor/serde/src/private/mod.rs @@ -3,11 +3,8 @@ pub mod de; #[cfg(not(no_serde_derive))] pub mod ser; -// FIXME: #[cfg(doctest)] once https://github.com/rust-lang/rust/issues/67295 is fixed. -pub mod doc; - pub use crate::lib::clone::Clone; -pub use crate::lib::convert::{From, Into}; +pub use crate::lib::convert::{From, Into, TryFrom}; pub use crate::lib::default::Default; pub use crate::lib::fmt::{self, Formatter}; pub use crate::lib::marker::PhantomData; @@ -15,34 +12,7 @@ pub use crate::lib::option::Option::{self, None, Some}; pub use crate::lib::ptr; pub use crate::lib::result::Result::{self, Err, Ok}; -pub use self::string::from_utf8_lossy; +pub use crate::serde_core_private::string::from_utf8_lossy; #[cfg(any(feature = "alloc", feature = "std"))] pub use crate::lib::{ToString, Vec}; - -#[cfg(not(no_core_try_from))] -pub use crate::lib::convert::TryFrom; - -mod string { - use crate::lib::*; - - #[cfg(any(feature = "std", feature = "alloc"))] - pub fn from_utf8_lossy(bytes: &[u8]) -> Cow { - String::from_utf8_lossy(bytes) - } - - // The generated code calls this like: - // - // let value = &_serde::__private::from_utf8_lossy(bytes); - // Err(_serde::de::Error::unknown_variant(value, VARIANTS)) - // - // so it is okay for the return type to be different from the std case as long - // as the above works. - #[cfg(not(any(feature = "std", feature = "alloc")))] - pub fn from_utf8_lossy(bytes: &[u8]) -> &str { - // Three unicode replacement characters if it fails. They look like a - // white-on-black question mark. The user will recognize it as invalid - // UTF-8. - str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}") - } -} diff --git a/pkg/installer/vendor/serde/src/private/ser.rs b/pkg/installer/vendor/serde/src/private/ser.rs index 9570629e9a0..411e2b41ee8 100644 --- a/pkg/installer/vendor/serde/src/private/ser.rs +++ b/pkg/installer/vendor/serde/src/private/ser.rs @@ -51,14 +51,14 @@ enum Unsupported { String, ByteArray, Optional, - #[cfg(any(feature = "std", feature = "alloc"))] - UnitStruct, Sequence, Tuple, TupleStruct, + #[cfg(not(any(feature = "std", feature = "alloc")))] Enum, } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl Display for Unsupported { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -69,11 +69,10 @@ impl Display for Unsupported { Unsupported::String => formatter.write_str("a string"), Unsupported::ByteArray => formatter.write_str("a byte array"), Unsupported::Optional => formatter.write_str("an optional"), - #[cfg(any(feature = "std", feature = "alloc"))] - Unsupported::UnitStruct => formatter.write_str("unit struct"), Unsupported::Sequence => formatter.write_str("a sequence"), Unsupported::Tuple => formatter.write_str("a tuple"), Unsupported::TupleStruct => formatter.write_str("a tuple struct"), + #[cfg(not(any(feature = "std", feature = "alloc")))] Unsupported::Enum => formatter.write_str("an enum"), } } @@ -91,6 +90,7 @@ where } } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl Serializer for TaggedSerializer where S: Serializer, @@ -357,6 +357,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue where M: ser::SerializeMap, @@ -397,6 +398,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::SerializeStructVariant for SerializeStructVariantAsMapValue where M: ser::SerializeMap, @@ -464,6 +466,7 @@ mod content { ), } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl Serialize for Content { fn serialize(&self, serializer: S) -> Result where @@ -556,6 +559,7 @@ mod content { } } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl Serializer for ContentSerializer where E: ser::Error, @@ -767,6 +771,7 @@ mod content { error: PhantomData, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::SerializeSeq for SerializeSeq where E: ser::Error, @@ -793,6 +798,7 @@ mod content { error: PhantomData, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::SerializeTuple for SerializeTuple where E: ser::Error, @@ -820,6 +826,7 @@ mod content { error: PhantomData, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::SerializeTupleStruct for SerializeTupleStruct where E: ser::Error, @@ -849,6 +856,7 @@ mod content { error: PhantomData, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::SerializeTupleVariant for SerializeTupleVariant where E: ser::Error, @@ -881,6 +889,7 @@ mod content { error: PhantomData, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::SerializeMap for SerializeMap where E: ser::Error, @@ -932,6 +941,7 @@ mod content { error: PhantomData, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::SerializeStruct for SerializeStruct where E: ser::Error, @@ -961,6 +971,7 @@ mod content { error: PhantomData, } + #[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl ser::SerializeStructVariant for SerializeStructVariant where E: ser::Error, @@ -1005,6 +1016,7 @@ where } #[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, M> Serializer for FlatMapSerializer<'a, M> where M: SerializeMap + 'a, @@ -1092,16 +1104,16 @@ where } fn serialize_unit_struct(self, _: &'static str) -> Result { - Err(Self::bad_type(Unsupported::UnitStruct)) + Ok(()) } fn serialize_unit_variant( self, _: &'static str, _: u32, - _: &'static str, + variant: &'static str, ) -> Result { - Err(Self::bad_type(Unsupported::Enum)) + self.0.serialize_entry(variant, &()) } fn serialize_newtype_struct( @@ -1186,6 +1198,7 @@ where pub struct FlatMapSerializeMap<'a, M: 'a>(&'a mut M); #[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, M> ser::SerializeMap for FlatMapSerializeMap<'a, M> where M: SerializeMap + 'a, @@ -1224,6 +1237,7 @@ where pub struct FlatMapSerializeStruct<'a, M: 'a>(&'a mut M); #[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, M> ser::SerializeStruct for FlatMapSerializeStruct<'a, M> where M: SerializeMap + 'a, @@ -1265,6 +1279,7 @@ where } #[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, M> ser::SerializeTupleVariant for FlatMapSerializeTupleVariantAsMapValue<'a, M> where M: SerializeMap + 'a, @@ -1311,6 +1326,7 @@ where } #[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl<'a, M> ser::SerializeStructVariant for FlatMapSerializeStructVariantAsMapValue<'a, M> where M: SerializeMap + 'a, @@ -1341,6 +1357,7 @@ pub struct AdjacentlyTaggedEnumVariant { pub variant_name: &'static str, } +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl Serialize for AdjacentlyTaggedEnumVariant { fn serialize(&self, serializer: S) -> Result where @@ -1354,6 +1371,7 @@ impl Serialize for AdjacentlyTaggedEnumVariant { // that is not recognized. pub struct CannotSerializeVariant(pub T); +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] impl Display for CannotSerializeVariant where T: Debug, diff --git a/pkg/installer/vendor/serde_core/.cargo-checksum.json b/pkg/installer/vendor/serde_core/.cargo-checksum.json new file mode 100644 index 00000000000..38e7802250f --- /dev/null +++ b/pkg/installer/vendor/serde_core/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{".cargo_vcs_info.json":"e01db62f4f66f74eadd338e6870263e4d3b19cc597ccf84e14da1963b9bc3a88","Cargo.lock":"41b57ccedaca4ff518654e9c0c8dea66d672dd2509db99a521d081e96f861938","Cargo.toml":"b1c07acb994f88418a0bbb0d393f76c4ca4276d9f4497ca734eb182286169ea8","Cargo.toml.orig":"0c7419cdb49704f6e3fb750f19d9b4b555e82507370b5dd8553ab35647b5c9c5","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"d9ca174c5818d7885265f0242d3193dd2963c2ee1da84aed8b938ec6a6990e58","build.rs":"a5fdacb9913eeede5fc08f39acbd31b2508483fdc20c79d6bc274d74407a1816","src/crate_root.rs":"157ca402e23c32f11a4f1797c81afb5e9f08df96768012cf3e3199153aafb2dd","src/de/ignored_any.rs":"6480f2b2a83dc4764d01b2eec7309729eef2492eede2e5ee98d23a60b05198eb","src/de/impls.rs":"9fb7a0322af51971fe1fa8f5b56c7ca3716622a6e9127b86bddfc0742c11383c","src/de/mod.rs":"5ec8602d593915e0cf480b0ce67b02f6ab066dac34725237d2c7b4a6ef12a845","src/de/value.rs":"fb6fef6d23d95d516c6e1d6b5cefd8b98ba3881214a82a8a7e0a8ffbb0a12083","src/format.rs":"c85071b016df643b161859682d21ce34fa0ebf2a3bdbeeea69859da48f5d934f","src/lib.rs":"5789fbaa20497111e3efa2af8a3c1d18bb41c0c0480b542d26a2573e8ff5cf5c","src/macros.rs":"a61c9d19b210697304328e6bb9380a1de713e21042256df90a2b4553f178b0be","src/private/content.rs":"5fdfb2bb95ecc80375507acb813a4c640496385e56fc99ab448f6b19e01fcc01","src/private/doc.rs":"abe656c015267555ca26ebbcf2f4dcc52c719a0b9ade3a5ed4635b2784699b8c","src/private/mod.rs":"3bb3427ec80077b9df1853aa17681de796de0179d74871a96b88b72469de6cfc","src/private/seed.rs":"3f6e098c5bd314788370dcaf3ab0152fcd7feb6bcf36a9c51808938cd58071eb","src/private/size_hint.rs":"350694a2abaad94ca5d33958710a5bb8973a2ea1a3dcc50a41405c943761b81f","src/private/string.rs":"c1500fd4b64c24a5e45fa5f48c85c802816d6954a2999a72fc5a8861687212d4","src/ser/fmt.rs":"bd129d9f085933b76dafef6eb43ffac893c1f6484a3064dcd82faeeebc3b203c","src/ser/impls.rs":"5ee7efc439345e8665da0bd79bc06c02a0506e5fd0f3a4cf11af0c7197eaa643","src/ser/impossible.rs":"283f628d5107aa030d2e96eeb1dee187f0ac18c24d517edeb51738ab15dfb871","src/ser/mod.rs":"ec097d92c8545356961e977a4c9650361cadd1d3a243d805ae7b0e0e589ae803","src/std_error.rs":"b36fd6a2b6898770b9f1c51517eb362af115767d0f7cb4a713e1b949530ffa8a"},"package":"41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"} \ No newline at end of file diff --git a/pkg/installer/vendor/serde_core/.cargo_vcs_info.json b/pkg/installer/vendor/serde_core/.cargo_vcs_info.json new file mode 100644 index 00000000000..a0d68a61144 --- /dev/null +++ b/pkg/installer/vendor/serde_core/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "a866b336f14aa57a07f0d0be9f8762746e64ecb4" + }, + "path_in_vcs": "serde_core" +} \ No newline at end of file diff --git a/pkg/installer/vendor/serde_core/Cargo.lock b/pkg/installer/vendor/serde_core/Cargo.lock new file mode 100644 index 00000000000..798a9c0c337 --- /dev/null +++ b/pkg/installer/vendor/serde_core/Cargo.lock @@ -0,0 +1,63 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.185" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be9b6f69f1dfd54c3b568ffa45c310d6973a5e5148fd40cf515acaf38cf5bc31" + +[[package]] +name = "serde_core" +version = "1.0.228" +dependencies = [ + "serde", + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" diff --git a/pkg/installer/vendor/serde_core/Cargo.toml b/pkg/installer/vendor/serde_core/Cargo.toml new file mode 100644 index 00000000000..4a7417fea49 --- /dev/null +++ b/pkg/installer/vendor/serde_core/Cargo.toml @@ -0,0 +1,87 @@ +# 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" +rust-version = "1.56" +name = "serde_core" +version = "1.0.228" +authors = [ + "Erick Tryzelaar ", + "David Tolnay ", +] +build = "build.rs" +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Serde traits only, with no support for derive -- use the `serde` crate instead" +homepage = "https://serde.rs" +documentation = "https://docs.rs/serde_core" +readme = "README.md" +keywords = [ + "serde", + "serialization", + "no_std", +] +categories = [ + "encoding", + "no-std", + "no-std::no-alloc", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/serde-rs/serde" + +[package.metadata.playground] +features = [ + "rc", + "result", +] + +[package.metadata.docs.rs] +features = [ + "rc", + "result", + "unstable", +] +targets = ["x86_64-unknown-linux-gnu"] +rustdoc-args = [ + "--generate-link-to-definition", + "--generate-macro-expansion", + "--extern-html-root-url=core=https://doc.rust-lang.org", + "--extern-html-root-url=alloc=https://doc.rust-lang.org", + "--extern-html-root-url=std=https://doc.rust-lang.org", +] + +[features] +alloc = [] +default = [ + "std", + "result", +] +rc = [] +result = [] +std = [] +unstable = [] + +[lib] +name = "serde_core" +path = "src/lib.rs" + +[dev-dependencies.serde] +version = "1" + +[dev-dependencies.serde_derive] +version = "1" + +[target."cfg(any())".dependencies.serde_derive] +version = "=1.0.228" diff --git a/pkg/installer/vendor/serde_core/Cargo.toml.orig b/pkg/installer/vendor/serde_core/Cargo.toml.orig new file mode 100644 index 00000000000..6705c998ab6 --- /dev/null +++ b/pkg/installer/vendor/serde_core/Cargo.toml.orig @@ -0,0 +1,70 @@ +[package] +name = "serde_core" +version = "1.0.228" +authors = ["Erick Tryzelaar ", "David Tolnay "] +build = "build.rs" +categories = ["encoding", "no-std", "no-std::no-alloc"] +description = "Serde traits only, with no support for derive -- use the `serde` crate instead" +documentation = "https://docs.rs/serde_core" +edition = "2021" +homepage = "https://serde.rs" +keywords = ["serde", "serialization", "no_std"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/serde-rs/serde" +rust-version = "1.56" + +[dev-dependencies] +serde = { version = "1", path = "../serde" } +serde_derive = { version = "1", path = "../serde_derive" } + +[package.metadata.playground] +features = ["rc", "result"] + +[package.metadata.docs.rs] +features = ["rc", "result", "unstable"] +targets = ["x86_64-unknown-linux-gnu"] +rustdoc-args = [ + "--generate-link-to-definition", + "--generate-macro-expansion", + "--extern-html-root-url=core=https://doc.rust-lang.org", + "--extern-html-root-url=alloc=https://doc.rust-lang.org", + "--extern-html-root-url=std=https://doc.rust-lang.org", +] + +# This cfg cannot be enabled, but it still forces Cargo to keep serde_derive's +# version in lockstep with serde's, even if someone depends on the two crates +# separately with serde's "derive" feature disabled. Every serde_derive release +# is compatible with exactly one serde release because the generated code +# involves nonpublic APIs which are not bound by semver. +[target.'cfg(any())'.dependencies] +serde_derive = { version = "=1.0.228", path = "../serde_derive" } + + +### FEATURES ################################################################# + +[features] +default = ["std", "result"] + +# Provide impls for common standard library types like Vec and HashMap. +# Requires a dependency on the Rust standard library. +std = [] + +# Provide impls for types that require unstable functionality. For tracking and +# discussion of unstable functionality please refer to this issue: +# +# https://github.com/serde-rs/serde/issues/812 +unstable = [] + +# Provide impls for types in the Rust core allocation and collections library +# including String, Box, Vec, and Cow. This is a subset of std but may +# be enabled without depending on all of std. +alloc = [] + +# Opt into impls for Rc and Arc. Serializing and deserializing these types +# does not preserve identity and may result in multiple copies of the same data. +# Be sure that this is what you want before enabling this feature. +rc = [] + +# Provide impls for Result. Convenient in some contexts but can lead to +# confusion if ? or unwrap are used incautiously. +result = [] diff --git a/pkg/installer/vendor/serde_core/LICENSE-APACHE b/pkg/installer/vendor/serde_core/LICENSE-APACHE new file mode 100644 index 00000000000..1b5ec8b78e2 --- /dev/null +++ b/pkg/installer/vendor/serde_core/LICENSE-APACHE @@ -0,0 +1,176 @@ + 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 diff --git a/pkg/installer/vendor/serde_core/LICENSE-MIT b/pkg/installer/vendor/serde_core/LICENSE-MIT new file mode 100644 index 00000000000..31aa79387f2 --- /dev/null +++ b/pkg/installer/vendor/serde_core/LICENSE-MIT @@ -0,0 +1,23 @@ +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. diff --git a/pkg/installer/vendor/serde_core/README.md b/pkg/installer/vendor/serde_core/README.md new file mode 100644 index 00000000000..94a765e2818 --- /dev/null +++ b/pkg/installer/vendor/serde_core/README.md @@ -0,0 +1,28 @@ +The `serde_core` crate contains Serde's trait definitions with **no support for +#\[derive()\]**. + +In crates that derive an implementation of `Serialize` or `Deserialize`, you +must depend on the [`serde`] crate, not `serde_core`. + +[`serde`]: https://crates.io/crates/serde + +In crates that handwrite implementations of Serde traits, or only use them as +trait bounds, depending on `serde_core` is permitted. But `serde` re-exports all +of these traits and can be used for this use case too. If in doubt, disregard +`serde_core` and always use `serde`. + +Crates that depend on `serde_core` instead of `serde` are able to compile in +parallel with `serde_derive` even when `serde`'s "derive" feature is turned on, +as shown in the following build timings. + +
+ +| When `serde_json` depends on `serde` | +|---| +| | + +
+ +| When `serde_json` depends on `serde_core` | +|---| +| | diff --git a/pkg/installer/vendor/serde_core/build.rs b/pkg/installer/vendor/serde_core/build.rs new file mode 100644 index 00000000000..9a33ab30775 --- /dev/null +++ b/pkg/installer/vendor/serde_core/build.rs @@ -0,0 +1,113 @@ +use std::env; +use std::fs; +use std::path::PathBuf; +use std::process::Command; +use std::str; + +const PRIVATE: &str = "\ +#[doc(hidden)] +pub mod __private$$ { + #[doc(hidden)] + pub use crate::private::*; +} +"; + +// The rustc-cfg strings below are *not* public API. Please let us know by +// opening a GitHub issue if your build environment requires some way to enable +// these cfgs other than by executing our build script. +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + + let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); + let patch_version = env::var("CARGO_PKG_VERSION_PATCH").unwrap(); + let module = PRIVATE.replace("$$", &patch_version); + fs::write(out_dir.join("private.rs"), module).unwrap(); + + let minor = match rustc_minor_version() { + Some(minor) => minor, + None => return, + }; + + if minor >= 77 { + println!("cargo:rustc-check-cfg=cfg(if_docsrs_then_no_serde_core)"); + println!("cargo:rustc-check-cfg=cfg(no_core_cstr)"); + println!("cargo:rustc-check-cfg=cfg(no_core_error)"); + println!("cargo:rustc-check-cfg=cfg(no_core_net)"); + println!("cargo:rustc-check-cfg=cfg(no_core_num_saturating)"); + println!("cargo:rustc-check-cfg=cfg(no_diagnostic_namespace)"); + println!("cargo:rustc-check-cfg=cfg(no_serde_derive)"); + println!("cargo:rustc-check-cfg=cfg(no_std_atomic)"); + println!("cargo:rustc-check-cfg=cfg(no_std_atomic64)"); + println!("cargo:rustc-check-cfg=cfg(no_target_has_atomic)"); + } + + let target = env::var("TARGET").unwrap(); + let emscripten = target == "asmjs-unknown-emscripten" || target == "wasm32-unknown-emscripten"; + + // Support for #[cfg(target_has_atomic = "...")] stabilized in Rust 1.60. + if minor < 60 { + println!("cargo:rustc-cfg=no_target_has_atomic"); + // Allowlist of archs that support std::sync::atomic module. This is + // based on rustc's compiler/rustc_target/src/spec/*.rs. + let has_atomic64 = target.starts_with("x86_64") + || target.starts_with("i686") + || target.starts_with("aarch64") + || target.starts_with("powerpc64") + || target.starts_with("sparc64") + || target.starts_with("mips64el") + || target.starts_with("riscv64"); + let has_atomic32 = has_atomic64 || emscripten; + if minor < 34 || !has_atomic64 { + println!("cargo:rustc-cfg=no_std_atomic64"); + } + if minor < 34 || !has_atomic32 { + println!("cargo:rustc-cfg=no_std_atomic"); + } + } + + // Current minimum supported version of serde_derive crate is Rust 1.61. + if minor < 61 { + println!("cargo:rustc-cfg=no_serde_derive"); + } + + // Support for core::ffi::CStr and alloc::ffi::CString stabilized in Rust 1.64. + // https://blog.rust-lang.org/2022/09/22/Rust-1.64.0.html#c-compatible-ffi-types-in-core-and-alloc + if minor < 64 { + println!("cargo:rustc-cfg=no_core_cstr"); + } + + // Support for core::num::Saturating and std::num::Saturating stabilized in Rust 1.74 + // https://blog.rust-lang.org/2023/11/16/Rust-1.74.0.html#stabilized-apis + if minor < 74 { + println!("cargo:rustc-cfg=no_core_num_saturating"); + } + + // Support for core::net stabilized in Rust 1.77. + // https://blog.rust-lang.org/2024/03/21/Rust-1.77.0.html + if minor < 77 { + println!("cargo:rustc-cfg=no_core_net"); + } + + // Support for the `#[diagnostic]` tool attribute namespace + // https://blog.rust-lang.org/2024/05/02/Rust-1.78.0.html#diagnostic-attributes + if minor < 78 { + println!("cargo:rustc-cfg=no_diagnostic_namespace"); + } + + // The Error trait became available in core in 1.81. + // https://blog.rust-lang.org/2024/09/05/Rust-1.81.0.html#coreerrorerror + if minor < 81 { + println!("cargo:rustc-cfg=no_core_error"); + } +} + +fn rustc_minor_version() -> Option { + let rustc = env::var_os("RUSTC")?; + let output = Command::new(rustc).arg("--version").output().ok()?; + let version = str::from_utf8(&output.stdout).ok()?; + let mut pieces = version.split('.'); + if pieces.next() != Some("rustc 1") { + return None; + } + pieces.next()?.parse().ok() +} diff --git a/pkg/installer/vendor/serde_core/src/crate_root.rs b/pkg/installer/vendor/serde_core/src/crate_root.rs new file mode 100644 index 00000000000..2cf75a40196 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/crate_root.rs @@ -0,0 +1,171 @@ +macro_rules! crate_root { + () => { + /// A facade around all the types we need from the `std`, `core`, and `alloc` + /// crates. This avoids elaborate import wrangling having to happen in every + /// module. + mod lib { + mod core { + #[cfg(not(feature = "std"))] + pub use core::*; + #[cfg(feature = "std")] + pub use std::*; + } + + pub use self::core::{f32, f64}; + pub use self::core::{iter, num, str}; + + #[cfg(any(feature = "std", feature = "alloc"))] + pub use self::core::{cmp, mem}; + + pub use self::core::cell::{Cell, RefCell}; + pub use self::core::cmp::Reverse; + pub use self::core::fmt::{self, Debug, Display, Write as FmtWrite}; + pub use self::core::marker::PhantomData; + pub use self::core::num::Wrapping; + pub use self::core::ops::{Bound, Range, RangeFrom, RangeInclusive, RangeTo}; + pub use self::core::result; + pub use self::core::time::Duration; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::borrow::{Cow, ToOwned}; + #[cfg(feature = "std")] + pub use std::borrow::{Cow, ToOwned}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::string::{String, ToString}; + #[cfg(feature = "std")] + pub use std::string::{String, ToString}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::vec::Vec; + #[cfg(feature = "std")] + pub use std::vec::Vec; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::boxed::Box; + #[cfg(feature = "std")] + pub use std::boxed::Box; + + #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] + pub use alloc::rc::{Rc, Weak as RcWeak}; + #[cfg(all(feature = "rc", feature = "std"))] + pub use std::rc::{Rc, Weak as RcWeak}; + + #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] + pub use alloc::sync::{Arc, Weak as ArcWeak}; + #[cfg(all(feature = "rc", feature = "std"))] + pub use std::sync::{Arc, Weak as ArcWeak}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; + #[cfg(feature = "std")] + pub use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; + + #[cfg(all(not(no_core_cstr), not(feature = "std")))] + pub use self::core::ffi::CStr; + #[cfg(feature = "std")] + pub use std::ffi::CStr; + + #[cfg(all(not(no_core_cstr), feature = "alloc", not(feature = "std")))] + pub use alloc::ffi::CString; + #[cfg(feature = "std")] + pub use std::ffi::CString; + + #[cfg(all(not(no_core_net), not(feature = "std")))] + pub use self::core::net; + #[cfg(feature = "std")] + pub use std::net; + + #[cfg(feature = "std")] + pub use std::error; + + #[cfg(feature = "std")] + pub use std::collections::{HashMap, HashSet}; + #[cfg(feature = "std")] + pub use std::ffi::{OsStr, OsString}; + #[cfg(feature = "std")] + pub use std::hash::{BuildHasher, Hash}; + #[cfg(feature = "std")] + pub use std::io::Write; + #[cfg(feature = "std")] + pub use std::path::{Path, PathBuf}; + #[cfg(feature = "std")] + pub use std::sync::{Mutex, RwLock}; + #[cfg(feature = "std")] + pub use std::time::{SystemTime, UNIX_EPOCH}; + + #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic)))] + pub use std::sync::atomic::{ + AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, + AtomicU8, AtomicUsize, Ordering, + }; + #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic64)))] + pub use std::sync::atomic::{AtomicI64, AtomicU64}; + + #[cfg(all(feature = "std", not(no_target_has_atomic)))] + pub use std::sync::atomic::Ordering; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "8"))] + pub use std::sync::atomic::{AtomicBool, AtomicI8, AtomicU8}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "16"))] + pub use std::sync::atomic::{AtomicI16, AtomicU16}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "32"))] + pub use std::sync::atomic::{AtomicI32, AtomicU32}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "64"))] + pub use std::sync::atomic::{AtomicI64, AtomicU64}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "ptr"))] + pub use std::sync::atomic::{AtomicIsize, AtomicUsize}; + + #[cfg(not(no_core_num_saturating))] + pub use self::core::num::Saturating; + } + + // None of this crate's error handling needs the `From::from` error conversion + // performed implicitly by the `?` operator or the standard library's `try!` + // macro. This simplified macro gives a 5.5% improvement in compile time + // compared to standard `try!`, and 9% improvement compared to `?`. + macro_rules! tri { + ($expr:expr) => { + match $expr { + Ok(val) => val, + Err(err) => return Err(err), + } + }; + } + + #[cfg_attr(all(docsrs, if_docsrs_then_no_serde_core), path = "core/de/mod.rs")] + pub mod de; + #[cfg_attr(all(docsrs, if_docsrs_then_no_serde_core), path = "core/ser/mod.rs")] + pub mod ser; + + #[cfg_attr(all(docsrs, if_docsrs_then_no_serde_core), path = "core/format.rs")] + mod format; + + #[doc(inline)] + pub use crate::de::{Deserialize, Deserializer}; + #[doc(inline)] + pub use crate::ser::{Serialize, Serializer}; + + // Used by generated code. Not public API. + #[doc(hidden)] + #[cfg_attr( + all(docsrs, if_docsrs_then_no_serde_core), + path = "core/private/mod.rs" + )] + mod private; + + // Used by declarative macro generated code. Not public API. + #[doc(hidden)] + pub mod __private { + #[doc(hidden)] + pub use crate::private::doc; + #[doc(hidden)] + pub use core::result::Result; + } + + include!(concat!(env!("OUT_DIR"), "/private.rs")); + + #[cfg(all(not(feature = "std"), no_core_error))] + #[cfg_attr(all(docsrs, if_docsrs_then_no_serde_core), path = "core/std_error.rs")] + mod std_error; + }; +} diff --git a/pkg/installer/vendor/serde_core/src/de/ignored_any.rs b/pkg/installer/vendor/serde_core/src/de/ignored_any.rs new file mode 100644 index 00000000000..2360a174236 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/de/ignored_any.rs @@ -0,0 +1,238 @@ +use crate::lib::*; + +use crate::de::{ + Deserialize, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor, +}; + +/// An efficient way of discarding data from a deserializer. +/// +/// Think of this like `serde_json::Value` in that it can be deserialized from +/// any type, except that it does not store any information about the data that +/// gets deserialized. +/// +/// ```edition2021 +/// use serde::de::{ +/// self, Deserialize, DeserializeSeed, Deserializer, IgnoredAny, SeqAccess, Visitor, +/// }; +/// use std::fmt; +/// use std::marker::PhantomData; +/// +/// /// A seed that can be used to deserialize only the `n`th element of a sequence +/// /// while efficiently discarding elements of any type before or after index `n`. +/// /// +/// /// For example to deserialize only the element at index 3: +/// /// +/// /// ``` +/// /// NthElement::new(3).deserialize(deserializer) +/// /// ``` +/// pub struct NthElement { +/// n: usize, +/// marker: PhantomData, +/// } +/// +/// impl NthElement { +/// pub fn new(n: usize) -> Self { +/// NthElement { +/// n: n, +/// marker: PhantomData, +/// } +/// } +/// } +/// +/// impl<'de, T> Visitor<'de> for NthElement +/// where +/// T: Deserialize<'de>, +/// { +/// type Value = T; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!( +/// formatter, +/// "a sequence in which we care about element {}", +/// self.n +/// ) +/// } +/// +/// fn visit_seq
(self, mut seq: A) -> Result +/// where +/// A: SeqAccess<'de>, +/// { +/// // Skip over the first `n` elements. +/// for i in 0..self.n { +/// // It is an error if the sequence ends before we get to element `n`. +/// if seq.next_element::()?.is_none() { +/// return Err(de::Error::invalid_length(i, &self)); +/// } +/// } +/// +/// // Deserialize the one we care about. +/// let nth = match seq.next_element()? { +/// Some(nth) => nth, +/// None => { +/// return Err(de::Error::invalid_length(self.n, &self)); +/// } +/// }; +/// +/// // Skip over any remaining elements in the sequence after `n`. +/// while let Some(IgnoredAny) = seq.next_element()? { +/// // ignore +/// } +/// +/// Ok(nth) +/// } +/// } +/// +/// impl<'de, T> DeserializeSeed<'de> for NthElement +/// where +/// T: Deserialize<'de>, +/// { +/// type Value = T; +/// +/// fn deserialize(self, deserializer: D) -> Result +/// where +/// D: Deserializer<'de>, +/// { +/// deserializer.deserialize_seq(self) +/// } +/// } +/// +/// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error> +/// # where +/// # D: Deserializer<'de>, +/// # { +/// // Deserialize only the sequence element at index 3 from this deserializer. +/// // The element at index 3 is required to be a string. Elements before and +/// // after index 3 are allowed to be of any type. +/// let s: String = NthElement::new(3).deserialize(deserializer)?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Copy, Clone, Debug, Default, PartialEq)] +pub struct IgnoredAny; + +impl<'de> Visitor<'de> for IgnoredAny { + type Value = IgnoredAny; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("anything at all") + } + + #[inline] + fn visit_bool(self, x: bool) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_i64(self, x: i64) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_i128(self, x: i128) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_u64(self, x: u64) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_u128(self, x: u128) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_f64(self, x: f64) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_str(self, s: &str) -> Result + where + E: Error, + { + let _ = s; + Ok(IgnoredAny) + } + + #[inline] + fn visit_none(self) -> Result { + Ok(IgnoredAny) + } + + #[inline] + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + IgnoredAny::deserialize(deserializer) + } + + #[inline] + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + IgnoredAny::deserialize(deserializer) + } + + #[inline] + fn visit_unit(self) -> Result { + Ok(IgnoredAny) + } + + #[inline] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + while let Some(IgnoredAny) = tri!(seq.next_element()) { + // Gobble + } + Ok(IgnoredAny) + } + + #[inline] + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + while let Some((IgnoredAny, IgnoredAny)) = tri!(map.next_entry()) { + // Gobble + } + Ok(IgnoredAny) + } + + #[inline] + fn visit_bytes(self, bytes: &[u8]) -> Result + where + E: Error, + { + let _ = bytes; + Ok(IgnoredAny) + } + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + tri!(data.variant::()).1.newtype_variant() + } +} + +impl<'de> Deserialize<'de> for IgnoredAny { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_ignored_any(IgnoredAny) + } +} diff --git a/pkg/installer/vendor/serde_core/src/de/impls.rs b/pkg/installer/vendor/serde_core/src/de/impls.rs new file mode 100644 index 00000000000..ab1a893cc4d --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/de/impls.rs @@ -0,0 +1,3173 @@ +use crate::lib::*; + +use crate::de::{ + Deserialize, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, Unexpected, VariantAccess, + Visitor, +}; +use crate::private::{self, InPlaceSeed}; + +#[cfg(any(feature = "std", feature = "alloc"))] +use crate::private::size_hint; + +//////////////////////////////////////////////////////////////////////////////// + +struct UnitVisitor; + +impl<'de> Visitor<'de> for UnitVisitor { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("unit") + } + + fn visit_unit(self) -> Result + where + E: Error, + { + Ok(()) + } +} + +impl<'de> Deserialize<'de> for () { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_unit(UnitVisitor) + } +} + +#[cfg(feature = "unstable")] +#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] +impl<'de> Deserialize<'de> for ! { + fn deserialize(_deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Err(Error::custom("cannot deserialize `!`")) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct BoolVisitor; + +impl<'de> Visitor<'de> for BoolVisitor { + type Value = bool; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a boolean") + } + + fn visit_bool(self, v: bool) -> Result + where + E: Error, + { + Ok(v) + } +} + +impl<'de> Deserialize<'de> for bool { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_bool(BoolVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! impl_deserialize_num { + ($primitive:ident, $nonzero:ident, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => { + impl_deserialize_num!($primitive, $deserialize $($method!($($val : $visit)*);)*); + + impl<'de> Deserialize<'de> for num::$nonzero { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct NonZeroVisitor; + + impl<'de> Visitor<'de> for NonZeroVisitor { + type Value = num::$nonzero; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a nonzero ", stringify!($primitive))) + } + + $($($method!(nonzero $primitive $val : $visit);)*)* + } + + deserializer.$deserialize(NonZeroVisitor) + } + } + + #[cfg(not(no_core_num_saturating))] + impl<'de> Deserialize<'de> for Saturating<$primitive> { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct SaturatingVisitor; + + impl<'de> Visitor<'de> for SaturatingVisitor { + type Value = Saturating<$primitive>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("integer with support for saturating semantics") + } + + $($($method!(saturating $primitive $val : $visit);)*)* + } + + deserializer.$deserialize(SaturatingVisitor) + } + } + }; + + ($primitive:ident, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => { + impl<'de> Deserialize<'de> for $primitive { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct PrimitiveVisitor; + + impl<'de> Visitor<'de> for PrimitiveVisitor { + type Value = $primitive; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(stringify!($primitive)) + } + + $($($method!($val : $visit);)*)* + } + + deserializer.$deserialize(PrimitiveVisitor) + } + } + }; +} + +macro_rules! num_self { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Ok(v) + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if let Some(nonzero) = Self::Value::new(v) { + Ok(nonzero) + } else { + Err(Error::invalid_value(Unexpected::Unsigned(0), &self)) + } + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Ok(Saturating(v)) + } + }; +} + +macro_rules! num_as_self { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Ok(v as Self::Value) + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if let Some(nonzero) = Self::Value::new(v as $primitive) { + Ok(nonzero) + } else { + Err(Error::invalid_value(Unexpected::Unsigned(0), &self)) + } + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Ok(Saturating(v as $primitive)) + } + }; +} + +macro_rules! num_as_copysign_self { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + #[cfg(not(feature = "std"))] + { + Ok(v as Self::Value) + } + + #[cfg(feature = "std")] + { + // Preserve sign of NaN. The `as` produces a nondeterministic sign. + let sign = if v.is_sign_positive() { 1.0 } else { -1.0 }; + Ok((v as Self::Value).copysign(sign)) + } + } + }; +} + +macro_rules! int_to_int { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Self::Value::try_from(v as i64) + .map_err(|_| Error::invalid_value(Unexpected::Signed(v as i64), &self)) + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if let Ok(v) = $primitive::try_from(v as i64) { + if let Some(nonzero) = Self::Value::new(v) { + return Ok(nonzero); + } + } + Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if (v as i64) < $primitive::MIN as i64 { + Ok(Saturating($primitive::MIN)) + } else if ($primitive::MAX as i64) < v as i64 { + Ok(Saturating($primitive::MAX)) + } else { + Ok(Saturating(v as $primitive)) + } + } + }; +} + +macro_rules! int_to_uint { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if 0 <= v { + #[allow(irrefutable_let_patterns)] + if let Ok(v) = Self::Value::try_from(v as u64) { + return Ok(v as Self::Value); + } + } + Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if 0 < v { + #[allow(irrefutable_let_patterns)] + if let Ok(v) = $primitive::try_from(v as u64) { + if let Some(nonzero) = Self::Value::new(v) { + return Ok(nonzero); + } + } + } + Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if v < 0 { + Ok(Saturating(0)) + } else if ($primitive::MAX as u64) < v as u64 { + Ok(Saturating($primitive::MAX)) + } else { + Ok(Saturating(v as $primitive)) + } + } + }; +} + +macro_rules! uint_to_self { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Self::Value::try_from(v as u64) + .map_err(|_| Error::invalid_value(Unexpected::Unsigned(v as u64), &self)) + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if let Ok(v) = $primitive::try_from(v as u64) { + if let Some(nonzero) = Self::Value::new(v) { + return Ok(nonzero); + } + } + Err(Error::invalid_value(Unexpected::Unsigned(v as u64), &self)) + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if let Ok(v) = $primitive::try_from(v as u64) { + Ok(Saturating(v as $primitive)) + } else { + Ok(Saturating($primitive::MAX)) + } + } + }; +} + +impl_deserialize_num! { + i8, NonZeroI8, deserialize_i8 + num_self!(i8:visit_i8); + int_to_int!(i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + i16, NonZeroI16, deserialize_i16 + num_self!(i16:visit_i16); + num_as_self!(i8:visit_i8); + int_to_int!(i32:visit_i32 i64:visit_i64); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + i32, NonZeroI32, deserialize_i32 + num_self!(i32:visit_i32); + num_as_self!(i8:visit_i8 i16:visit_i16); + int_to_int!(i64:visit_i64); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + i64, NonZeroI64, deserialize_i64 + num_self!(i64:visit_i64); + num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + isize, NonZeroIsize, deserialize_i64 + num_as_self!(i8:visit_i8 i16:visit_i16); + int_to_int!(i32:visit_i32 i64:visit_i64); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + u8, NonZeroU8, deserialize_u8 + num_self!(u8:visit_u8); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + u16, NonZeroU16, deserialize_u16 + num_self!(u16:visit_u16); + num_as_self!(u8:visit_u8); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + u32, NonZeroU32, deserialize_u32 + num_self!(u32:visit_u32); + num_as_self!(u8:visit_u8 u16:visit_u16); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u64:visit_u64); +} + +impl_deserialize_num! { + u64, NonZeroU64, deserialize_u64 + num_self!(u64:visit_u64); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); +} + +impl_deserialize_num! { + usize, NonZeroUsize, deserialize_u64 + num_as_self!(u8:visit_u8 u16:visit_u16); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + f32, deserialize_f32 + num_self!(f32:visit_f32); + num_as_copysign_self!(f64:visit_f64); + num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + f64, deserialize_f64 + num_self!(f64:visit_f64); + num_as_copysign_self!(f32:visit_f32); + num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +macro_rules! num_128 { + ($ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if v as i128 >= Self::Value::MIN as i128 && v as u128 <= Self::Value::MAX as u128 { + Ok(v as Self::Value) + } else { + Err(Error::invalid_value( + Unexpected::Other(stringify!($ty)), + &self, + )) + } + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if v as i128 >= $primitive::MIN as i128 && v as u128 <= $primitive::MAX as u128 { + if let Some(nonzero) = Self::Value::new(v as $primitive) { + Ok(nonzero) + } else { + Err(Error::invalid_value(Unexpected::Unsigned(0), &self)) + } + } else { + Err(Error::invalid_value( + Unexpected::Other(stringify!($ty)), + &self, + )) + } + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if (v as i128) < $primitive::MIN as i128 { + Ok(Saturating($primitive::MIN)) + } else if ($primitive::MAX as u128) < v as u128 { + Ok(Saturating($primitive::MAX)) + } else { + Ok(Saturating(v as $primitive)) + } + } + }; +} + +impl_deserialize_num! { + i128, NonZeroI128, deserialize_i128 + num_self!(i128:visit_i128); + num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); + num_128!(u128:visit_u128); +} + +impl_deserialize_num! { + u128, NonZeroU128, deserialize_u128 + num_self!(u128:visit_u128); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + num_128!(i128:visit_i128); +} + +//////////////////////////////////////////////////////////////////////////////// + +struct CharVisitor; + +impl<'de> Visitor<'de> for CharVisitor { + type Value = char; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a character") + } + + #[inline] + fn visit_char(self, v: char) -> Result + where + E: Error, + { + Ok(v) + } + + #[inline] + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + let mut iter = v.chars(); + match (iter.next(), iter.next()) { + (Some(c), None) => Ok(c), + _ => Err(Error::invalid_value(Unexpected::Str(v), &self)), + } + } +} + +impl<'de> Deserialize<'de> for char { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_char(CharVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +struct StringVisitor; +#[cfg(any(feature = "std", feature = "alloc"))] +struct StringInPlaceVisitor<'a>(&'a mut String); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de> Visitor<'de> for StringVisitor { + type Value = String; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + Ok(v.to_owned()) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + Ok(v) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => Ok(s.to_owned()), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + match String::from_utf8(v) { + Ok(s) => Ok(s), + Err(e) => Err(Error::invalid_value( + Unexpected::Bytes(&e.into_bytes()), + &self, + )), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de> Visitor<'de> for StringInPlaceVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + self.0.clear(); + self.0.push_str(v); + Ok(()) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + *self.0 = v; + Ok(()) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => { + self.0.clear(); + self.0.push_str(s); + Ok(()) + } + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + match String::from_utf8(v) { + Ok(s) => { + *self.0 = s; + Ok(()) + } + Err(e) => Err(Error::invalid_value( + Unexpected::Bytes(&e.into_bytes()), + &self, + )), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de> Deserialize<'de> for String { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(StringVisitor) + } + + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(StringInPlaceVisitor(place)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct StrVisitor; + +impl<'a> Visitor<'a> for StrVisitor { + type Value = &'a str; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a borrowed string") + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where + E: Error, + { + Ok(v) // so easy + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where + E: Error, + { + str::from_utf8(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) + } +} + +impl<'de: 'a, 'a> Deserialize<'de> for &'a str { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(StrVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct BytesVisitor; + +impl<'a> Visitor<'a> for BytesVisitor { + type Value = &'a [u8]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a borrowed byte array") + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where + E: Error, + { + Ok(v) + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where + E: Error, + { + Ok(v.as_bytes()) + } +} + +impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_bytes(BytesVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] +struct CStringVisitor; + +#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] +impl<'de> Visitor<'de> for CStringVisitor { + type Value = CString; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("byte array") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let capacity = size_hint::cautious::(seq.size_hint()); + let mut values = Vec::::with_capacity(capacity); + + while let Some(value) = tri!(seq.next_element()) { + values.push(value); + } + + CString::new(values).map_err(Error::custom) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } +} + +#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de> Deserialize<'de> for CString { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_byte_buf(CStringVisitor) + } +} + +macro_rules! forwarded_impl { + ( + $(#[$attr:meta])* + ($($id:ident),*), $ty:ty, $func:expr + ) => { + $(#[$attr])* + impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map($func) + } + } + } +} + +forwarded_impl! { + #[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + (), Box, CString::into_boxed_c_str +} + +forwarded_impl! { + (T), Reverse, Reverse +} + +//////////////////////////////////////////////////////////////////////////////// + +struct OptionVisitor { + marker: PhantomData, +} + +impl<'de, T> Visitor<'de> for OptionVisitor +where + T: Deserialize<'de>, +{ + type Value = Option; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("option") + } + + #[inline] + fn visit_unit(self) -> Result + where + E: Error, + { + Ok(None) + } + + #[inline] + fn visit_none(self) -> Result + where + E: Error, + { + Ok(None) + } + + #[inline] + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::deserialize(deserializer).map(Some) + } + + fn __private_visit_untagged_option(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Ok(T::deserialize(deserializer).ok()) + } +} + +impl<'de, T> Deserialize<'de> for Option +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_option(OptionVisitor { + marker: PhantomData, + }) + } + + // The Some variant's repr is opaque, so we can't play cute tricks with its + // tag to have deserialize_in_place build the content in place unconditionally. + // + // FIXME: investigate whether branching on the old value being Some to + // deserialize_in_place the value is profitable (probably data-dependent?) +} + +//////////////////////////////////////////////////////////////////////////////// + +struct PhantomDataVisitor { + marker: PhantomData, +} + +impl<'de, T> Visitor<'de> for PhantomDataVisitor +where + T: ?Sized, +{ + type Value = PhantomData; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("unit") + } + + #[inline] + fn visit_unit(self) -> Result + where + E: Error, + { + Ok(PhantomData) + } +} + +impl<'de, T> Deserialize<'de> for PhantomData +where + T: ?Sized, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let visitor = PhantomDataVisitor { + marker: PhantomData, + }; + deserializer.deserialize_unit_struct("PhantomData", visitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! seq_impl { + ( + $(#[$attr:meta])* + $ty:ident , + $access:ident, + $clear:expr, + $with_capacity:expr, + $reserve:expr, + $insert:expr + ) => { + $(#[$attr])* + impl<'de, T $(, $typaram)*> Deserialize<'de> for $ty + where + T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound1 $(+ $bound2)*,)* + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct SeqVisitor { + marker: PhantomData<$ty>, + } + + impl<'de, T $(, $typaram)*> Visitor<'de> for SeqVisitor + where + T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound1 $(+ $bound2)*,)* + { + type Value = $ty; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + #[inline] + fn visit_seq(self, mut $access: A) -> Result + where + A: SeqAccess<'de>, + { + let mut values = $with_capacity; + + while let Some(value) = tri!($access.next_element()) { + $insert(&mut values, value); + } + + Ok(values) + } + } + + let visitor = SeqVisitor { marker: PhantomData }; + deserializer.deserialize_seq(visitor) + } + + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + struct SeqInPlaceVisitor<'a, T: 'a $(, $typaram: 'a)*>(&'a mut $ty); + + impl<'a, 'de, T $(, $typaram)*> Visitor<'de> for SeqInPlaceVisitor<'a, T $(, $typaram)*> + where + T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound1 $(+ $bound2)*,)* + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + #[inline] + fn visit_seq(mut self, mut $access: A) -> Result + where + A: SeqAccess<'de>, + { + $clear(&mut self.0); + $reserve(&mut self.0, size_hint::cautious::($access.size_hint())); + + // FIXME: try to overwrite old values here? (Vec, VecDeque, LinkedList) + while let Some(value) = tri!($access.next_element()) { + $insert(&mut self.0, value); + } + + Ok(()) + } + } + + deserializer.deserialize_seq(SeqInPlaceVisitor(place)) + } + } + } +} + +// Dummy impl of reserve +#[cfg(any(feature = "std", feature = "alloc"))] +fn nop_reserve(_seq: T, _n: usize) {} + +seq_impl!( + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BinaryHeap, + seq, + BinaryHeap::clear, + BinaryHeap::with_capacity(size_hint::cautious::(seq.size_hint())), + BinaryHeap::reserve, + BinaryHeap::push +); + +seq_impl!( + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BTreeSet, + seq, + BTreeSet::clear, + BTreeSet::new(), + nop_reserve, + BTreeSet::insert +); + +seq_impl!( + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + LinkedList, + seq, + LinkedList::clear, + LinkedList::new(), + nop_reserve, + LinkedList::push_back +); + +seq_impl!( + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + HashSet, + seq, + HashSet::clear, + HashSet::with_capacity_and_hasher(size_hint::cautious::(seq.size_hint()), S::default()), + HashSet::reserve, + HashSet::insert +); + +seq_impl!( + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + VecDeque, + seq, + VecDeque::clear, + VecDeque::with_capacity(size_hint::cautious::(seq.size_hint())), + VecDeque::reserve, + VecDeque::push_back +); + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, T> Deserialize<'de> for Vec +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct VecVisitor { + marker: PhantomData, + } + + impl<'de, T> Visitor<'de> for VecVisitor + where + T: Deserialize<'de>, + { + type Value = Vec; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let capacity = size_hint::cautious::(seq.size_hint()); + let mut values = Vec::::with_capacity(capacity); + + while let Some(value) = tri!(seq.next_element()) { + values.push(value); + } + + Ok(values) + } + } + + let visitor = VecVisitor { + marker: PhantomData, + }; + deserializer.deserialize_seq(visitor) + } + + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + struct VecInPlaceVisitor<'a, T: 'a>(&'a mut Vec); + + impl<'a, 'de, T> Visitor<'de> for VecInPlaceVisitor<'a, T> + where + T: Deserialize<'de>, + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let hint = size_hint::cautious::(seq.size_hint()); + if let Some(additional) = hint.checked_sub(self.0.len()) { + self.0.reserve(additional); + } + + for i in 0..self.0.len() { + let next = { + let next_place = InPlaceSeed(&mut self.0[i]); + tri!(seq.next_element_seed(next_place)) + }; + if next.is_none() { + self.0.truncate(i); + return Ok(()); + } + } + + while let Some(value) = tri!(seq.next_element()) { + self.0.push(value); + } + + Ok(()) + } + } + + deserializer.deserialize_seq(VecInPlaceVisitor(place)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct ArrayVisitor { + marker: PhantomData, +} +struct ArrayInPlaceVisitor<'a, A: 'a>(&'a mut A); + +impl ArrayVisitor { + fn new() -> Self { + ArrayVisitor { + marker: PhantomData, + } + } +} + +impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> { + type Value = [T; 0]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("an empty array") + } + + #[inline] + fn visit_seq(self, _: A) -> Result + where + A: SeqAccess<'de>, + { + Ok([]) + } +} + +// Does not require T: Deserialize<'de>. +impl<'de, T> Deserialize<'de> for [T; 0] { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple(0, ArrayVisitor::<[T; 0]>::new()) + } +} + +macro_rules! array_impls { + ($($len:expr => ($($n:tt)+))+) => { + $( + impl<'de, T> Visitor<'de> for ArrayVisitor<[T; $len]> + where + T: Deserialize<'de>, + { + type Value = [T; $len]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("an array of length ", $len)) + } + + #[inline] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + Ok([$( + match tri!(seq.next_element()) { + Some(val) => val, + None => return Err(Error::invalid_length($n, &self)), + } + ),+]) + } + } + + impl<'a, 'de, T> Visitor<'de> for ArrayInPlaceVisitor<'a, [T; $len]> + where + T: Deserialize<'de>, + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("an array of length ", $len)) + } + + #[inline] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let mut fail_idx = None; + for (idx, dest) in self.0[..].iter_mut().enumerate() { + if tri!(seq.next_element_seed(InPlaceSeed(dest))).is_none() { + fail_idx = Some(idx); + break; + } + } + if let Some(idx) = fail_idx { + return Err(Error::invalid_length(idx, &self)); + } + Ok(()) + } + } + + impl<'de, T> Deserialize<'de> for [T; $len] + where + T: Deserialize<'de>, + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple($len, ArrayVisitor::<[T; $len]>::new()) + } + + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple($len, ArrayInPlaceVisitor(place)) + } + } + )+ + } +} + +array_impls! { + 1 => (0) + 2 => (0 1) + 3 => (0 1 2) + 4 => (0 1 2 3) + 5 => (0 1 2 3 4) + 6 => (0 1 2 3 4 5) + 7 => (0 1 2 3 4 5 6) + 8 => (0 1 2 3 4 5 6 7) + 9 => (0 1 2 3 4 5 6 7 8) + 10 => (0 1 2 3 4 5 6 7 8 9) + 11 => (0 1 2 3 4 5 6 7 8 9 10) + 12 => (0 1 2 3 4 5 6 7 8 9 10 11) + 13 => (0 1 2 3 4 5 6 7 8 9 10 11 12) + 14 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13) + 15 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14) + 16 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) + 17 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16) + 18 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17) + 19 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18) + 20 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19) + 21 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20) + 22 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21) + 23 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22) + 24 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23) + 25 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24) + 26 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25) + 27 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26) + 28 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27) + 29 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28) + 30 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29) + 31 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30) + 32 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31) +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! tuple_impls { + ($($len:tt => ($($n:tt $name:ident)+))+) => { + $( + #[cfg_attr(docsrs, doc(hidden))] + impl<'de, $($name),+> Deserialize<'de> for ($($name,)+) + where + $($name: Deserialize<'de>,)+ + { + tuple_impl_body!($len => ($($n $name)+)); + } + )+ + }; +} + +macro_rules! tuple_impl_body { + ($len:tt => ($($n:tt $name:ident)+)) => { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct TupleVisitor<$($name,)+> { + marker: PhantomData<($($name,)+)>, + } + + impl<'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleVisitor<$($name,)+> { + type Value = ($($name,)+); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a tuple of size ", $len)) + } + + #[inline] + #[allow(non_snake_case)] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + $( + let $name = match tri!(seq.next_element()) { + Some(value) => value, + None => return Err(Error::invalid_length($n, &self)), + }; + )+ + + Ok(($($name,)+)) + } + } + + deserializer.deserialize_tuple($len, TupleVisitor { marker: PhantomData }) + } + + #[inline] + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + struct TupleInPlaceVisitor<'a, $($name: 'a,)+>(&'a mut ($($name,)+)); + + impl<'a, 'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleInPlaceVisitor<'a, $($name,)+> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a tuple of size ", $len)) + } + + #[inline] + #[allow(non_snake_case)] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + $( + if tri!(seq.next_element_seed(InPlaceSeed(&mut (self.0).$n))).is_none() { + return Err(Error::invalid_length($n, &self)); + } + )+ + + Ok(()) + } + } + + deserializer.deserialize_tuple($len, TupleInPlaceVisitor(place)) + } + }; +} + +#[cfg_attr(docsrs, doc(fake_variadic))] +#[cfg_attr( + docsrs, + doc = "This trait is implemented for tuples up to 16 items long." +)] +impl<'de, T> Deserialize<'de> for (T,) +where + T: Deserialize<'de>, +{ + tuple_impl_body!(1 => (0 T)); +} + +tuple_impls! { + 2 => (0 T0 1 T1) + 3 => (0 T0 1 T1 2 T2) + 4 => (0 T0 1 T1 2 T2 3 T3) + 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) + 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) + 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) + 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) + 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) + 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) + 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) + 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) + 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) + 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) + 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) + 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! map_impl { + ( + $(#[$attr:meta])* + $ty:ident , + $access:ident, + $with_capacity:expr, + ) => { + $(#[$attr])* + impl<'de, K, V $(, $typaram)*> Deserialize<'de> for $ty + where + K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*, + V: Deserialize<'de>, + $($typaram: $bound1 $(+ $bound2)*),* + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct MapVisitor { + marker: PhantomData<$ty>, + } + + impl<'de, K, V $(, $typaram)*> Visitor<'de> for MapVisitor + where + K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*, + V: Deserialize<'de>, + $($typaram: $bound1 $(+ $bound2)*),* + { + type Value = $ty; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a map") + } + + #[inline] + fn visit_map(self, mut $access: A) -> Result + where + A: MapAccess<'de>, + { + let mut values = $with_capacity; + + while let Some((key, value)) = tri!($access.next_entry()) { + values.insert(key, value); + } + + Ok(values) + } + } + + let visitor = MapVisitor { marker: PhantomData }; + deserializer.deserialize_map(visitor) + } + } + } +} + +map_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BTreeMap, + map, + BTreeMap::new(), +} + +map_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + HashMap, + map, + HashMap::with_capacity_and_hasher(size_hint::cautious::<(K, V)>(map.size_hint()), S::default()), +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! parse_ip_impl { + ($ty:ty, $expecting:expr, $size:tt) => { + impl<'de> Deserialize<'de> for $ty { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + deserializer.deserialize_str(FromStrVisitor::new($expecting)) + } else { + <[u8; $size]>::deserialize(deserializer).map(<$ty>::from) + } + } + } + }; +} + +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! variant_identifier { + ( + $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*) + $expecting_message:expr, + $variants_name:ident + ) => { + enum $name_kind { + $($variant),* + } + + static $variants_name: &[&str] = &[$(stringify!($variant)),*]; + + impl<'de> Deserialize<'de> for $name_kind { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct KindVisitor; + + impl<'de> Visitor<'de> for KindVisitor { + type Value = $name_kind; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str($expecting_message) + } + + fn visit_u64(self, value: u64) -> Result + where + E: Error, + { + match value { + $( + $index => Ok($name_kind :: $variant), + )* + _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self),), + } + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + $( + stringify!($variant) => Ok($name_kind :: $variant), + )* + _ => Err(Error::unknown_variant(value, $variants_name)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + $( + $bytes => Ok($name_kind :: $variant), + )* + _ => { + match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, $variants_name)), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)), + } + } + } + } + } + + deserializer.deserialize_identifier(KindVisitor) + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! deserialize_enum { + ( + $name:ident $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*) + $expecting_message:expr, + $deserializer:expr + ) => { + variant_identifier! { + $name_kind ($($variant; $bytes; $index),*) + $expecting_message, + VARIANTS + } + + struct EnumVisitor; + impl<'de> Visitor<'de> for EnumVisitor { + type Value = $name; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a ", stringify!($name))) + } + + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + match tri!(data.variant()) { + $( + ($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant), + )* + } + } + } + $deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor) + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl<'de> Deserialize<'de> for net::IpAddr { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + deserializer.deserialize_str(FromStrVisitor::new("IP address")) + } else { + use crate::lib::net::IpAddr; + deserialize_enum! { + IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1) + "`V4` or `V6`", + deserializer + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +parse_ip_impl!(net::Ipv4Addr, "IPv4 address", 4); + +#[cfg(any(feature = "std", not(no_core_net)))] +parse_ip_impl!(net::Ipv6Addr, "IPv6 address", 16); + +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! parse_socket_impl { + ( + $ty:ty, $expecting:tt, + $new:expr, + ) => { + impl<'de> Deserialize<'de> for $ty { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + deserializer.deserialize_str(FromStrVisitor::new($expecting)) + } else { + <(_, u16)>::deserialize(deserializer).map($new) + } + } + } + }; +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl<'de> Deserialize<'de> for net::SocketAddr { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + deserializer.deserialize_str(FromStrVisitor::new("socket address")) + } else { + use crate::lib::net::SocketAddr; + deserialize_enum! { + SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1) + "`V4` or `V6`", + deserializer + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +parse_socket_impl! { + net::SocketAddrV4, "IPv4 socket address", + |(ip, port)| net::SocketAddrV4::new(ip, port), +} + +#[cfg(any(feature = "std", not(no_core_net)))] +parse_socket_impl! { + net::SocketAddrV6, "IPv6 socket address", + |(ip, port)| net::SocketAddrV6::new(ip, port, 0, 0), +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +struct PathVisitor; + +#[cfg(feature = "std")] +impl<'a> Visitor<'a> for PathVisitor { + type Value = &'a Path; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a borrowed path") + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where + E: Error, + { + Ok(v.as_ref()) + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where + E: Error, + { + str::from_utf8(v) + .map(AsRef::as_ref) + .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de: 'a, 'a> Deserialize<'de> for &'a Path { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(PathVisitor) + } +} + +#[cfg(feature = "std")] +struct PathBufVisitor; + +#[cfg(feature = "std")] +impl<'de> Visitor<'de> for PathBufVisitor { + type Value = PathBuf; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("path string") + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + Ok(From::from(v)) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + Ok(From::from(v)) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + str::from_utf8(v) + .map(From::from) + .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + String::from_utf8(v) + .map(From::from) + .map_err(|e| Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self)) + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de> Deserialize<'de> for PathBuf { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(PathBufVisitor) + } +} + +forwarded_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + (), Box, PathBuf::into_boxed_path +} + +//////////////////////////////////////////////////////////////////////////////// + +// If this were outside of the serde crate, it would just use: +// +// #[derive(Deserialize)] +// #[serde(variant_identifier)] +#[cfg(all(feature = "std", any(unix, windows)))] +variant_identifier! { + OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1) + "`Unix` or `Windows`", + OSSTR_VARIANTS +} + +#[cfg(all(feature = "std", any(unix, windows)))] +struct OsStringVisitor; + +#[cfg(all(feature = "std", any(unix, windows)))] +impl<'de> Visitor<'de> for OsStringVisitor { + type Value = OsString; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("os string") + } + + #[cfg(unix)] + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + use std::os::unix::ffi::OsStringExt; + + match tri!(data.variant()) { + (OsStringKind::Unix, v) => v.newtype_variant().map(OsString::from_vec), + (OsStringKind::Windows, _) => Err(Error::custom( + "cannot deserialize Windows OS string on Unix", + )), + } + } + + #[cfg(windows)] + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + use std::os::windows::ffi::OsStringExt; + + match tri!(data.variant()) { + (OsStringKind::Windows, v) => v + .newtype_variant::>() + .map(|vec| OsString::from_wide(&vec)), + (OsStringKind::Unix, _) => Err(Error::custom( + "cannot deserialize Unix OS string on Windows", + )), + } + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))] +impl<'de> Deserialize<'de> for OsString { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +forwarded_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + (T), Box, Box::new +} + +forwarded_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + (T), Box<[T]>, Vec::into_boxed_slice +} + +forwarded_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + (), Box, String::into_boxed_str +} + +forwarded_impl! { + #[cfg(all(feature = "std", any(unix, windows)))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))] + (), Box, OsString::into_boxed_os_str +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, 'a, T> Deserialize<'de> for Cow<'a, T> +where + T: ?Sized + ToOwned, + T::Owned: Deserialize<'de>, +{ + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::Owned::deserialize(deserializer).map(Cow::Owned) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting +/// `Weak` has a reference count of 0 and cannot be upgraded. +/// +/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +#[cfg_attr( + docsrs, + doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))) +)] +impl<'de, T> Deserialize<'de> for RcWeak +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + tri!(Option::::deserialize(deserializer)); + Ok(RcWeak::new()) + } +} + +/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting +/// `Weak` has a reference count of 0 and cannot be upgraded. +/// +/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +#[cfg_attr( + docsrs, + doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))) +)] +impl<'de, T> Deserialize<'de> for ArcWeak +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + tri!(Option::::deserialize(deserializer)); + Ok(ArcWeak::new()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! box_forwarded_impl { + ( + $(#[$attr:meta])* + $t:ident + ) => { + $(#[$attr])* + impl<'de, T> Deserialize<'de> for $t + where + T: ?Sized, + Box: Deserialize<'de>, + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Box::deserialize(deserializer).map(Into::into) + } + } + }; +} + +box_forwarded_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Deserializing a data structure containing `Rc` will not attempt to + /// deduplicate `Rc` references to the same data. Every deserialized `Rc` + /// will end up with a strong count of 1. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))] + Rc +} + +box_forwarded_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Deserializing a data structure containing `Arc` will not attempt to + /// deduplicate `Arc` references to the same data. Every deserialized `Arc` + /// will end up with a strong count of 1. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))] + Arc +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, T> Deserialize<'de> for Cell +where + T: Deserialize<'de> + Copy, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::deserialize(deserializer).map(Cell::new) + } +} + +forwarded_impl! { + (T), RefCell, RefCell::new +} + +forwarded_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + (T), Mutex, Mutex::new +} + +forwarded_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + (T), RwLock, RwLock::new +} + +//////////////////////////////////////////////////////////////////////////////// + +// This is a cleaned-up version of the impl generated by: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct Duration { +// secs: u64, +// nanos: u32, +// } +impl<'de> Deserialize<'de> for Duration { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + Secs, + Nanos, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`secs` or `nanos`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "secs" => Ok(Field::Secs), + "nanos" => Ok(Field::Nanos), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"secs" => Ok(Field::Secs), + b"nanos" => Ok(Field::Nanos), + _ => { + let value = private::string::from_utf8_lossy(value); + Err(Error::unknown_field(&*value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + fn check_overflow(secs: u64, nanos: u32) -> Result<(), E> + where + E: Error, + { + static NANOS_PER_SEC: u32 = 1_000_000_000; + match secs.checked_add((nanos / NANOS_PER_SEC) as u64) { + Some(_) => Ok(()), + None => Err(E::custom("overflow deserializing Duration")), + } + } + + struct DurationVisitor; + + impl<'de> Visitor<'de> for DurationVisitor { + type Value = Duration; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct Duration") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let secs: u64 = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let nanos: u32 = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + tri!(check_overflow(secs, nanos)); + Ok(Duration::new(secs, nanos)) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut secs: Option = None; + let mut nanos: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::Secs => { + if secs.is_some() { + return Err(::duplicate_field("secs")); + } + secs = Some(tri!(map.next_value())); + } + Field::Nanos => { + if nanos.is_some() { + return Err(::duplicate_field("nanos")); + } + nanos = Some(tri!(map.next_value())); + } + } + } + let secs = match secs { + Some(secs) => secs, + None => return Err(::missing_field("secs")), + }; + let nanos = match nanos { + Some(nanos) => nanos, + None => return Err(::missing_field("nanos")), + }; + tri!(check_overflow(secs, nanos)); + Ok(Duration::new(secs, nanos)) + } + } + + const FIELDS: &[&str] = &["secs", "nanos"]; + deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de> Deserialize<'de> for SystemTime { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // Reuse duration + enum Field { + Secs, + Nanos, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "secs_since_epoch" => Ok(Field::Secs), + "nanos_since_epoch" => Ok(Field::Nanos), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"secs_since_epoch" => Ok(Field::Secs), + b"nanos_since_epoch" => Ok(Field::Nanos), + _ => { + let value = String::from_utf8_lossy(value); + Err(Error::unknown_field(&value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + fn check_overflow(secs: u64, nanos: u32) -> Result<(), E> + where + E: Error, + { + static NANOS_PER_SEC: u32 = 1_000_000_000; + match secs.checked_add((nanos / NANOS_PER_SEC) as u64) { + Some(_) => Ok(()), + None => Err(E::custom("overflow deserializing SystemTime epoch offset")), + } + } + + struct DurationVisitor; + + impl<'de> Visitor<'de> for DurationVisitor { + type Value = Duration; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct SystemTime") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let secs: u64 = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let nanos: u32 = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + tri!(check_overflow(secs, nanos)); + Ok(Duration::new(secs, nanos)) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut secs: Option = None; + let mut nanos: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::Secs => { + if secs.is_some() { + return Err(::duplicate_field( + "secs_since_epoch", + )); + } + secs = Some(tri!(map.next_value())); + } + Field::Nanos => { + if nanos.is_some() { + return Err(::duplicate_field( + "nanos_since_epoch", + )); + } + nanos = Some(tri!(map.next_value())); + } + } + } + let secs = match secs { + Some(secs) => secs, + None => return Err(::missing_field("secs_since_epoch")), + }; + let nanos = match nanos { + Some(nanos) => nanos, + None => return Err(::missing_field("nanos_since_epoch")), + }; + tri!(check_overflow(secs, nanos)); + Ok(Duration::new(secs, nanos)) + } + } + + const FIELDS: &[&str] = &["secs_since_epoch", "nanos_since_epoch"]; + let duration = tri!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor)); + UNIX_EPOCH + .checked_add(duration) + .ok_or_else(|| D::Error::custom("overflow deserializing SystemTime")) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Similar to: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct Range { +// start: Idx, +// end: Idx, +// } +impl<'de, Idx> Deserialize<'de> for Range +where + Idx: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let (start, end) = tri!(deserializer.deserialize_struct( + "Range", + range::FIELDS, + range::RangeVisitor { + expecting: "struct Range", + phantom: PhantomData, + }, + )); + Ok(start..end) + } +} + +impl<'de, Idx> Deserialize<'de> for RangeInclusive +where + Idx: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let (start, end) = tri!(deserializer.deserialize_struct( + "RangeInclusive", + range::FIELDS, + range::RangeVisitor { + expecting: "struct RangeInclusive", + phantom: PhantomData, + }, + )); + Ok(RangeInclusive::new(start, end)) + } +} + +mod range { + use crate::lib::*; + + use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + use crate::private; + + pub const FIELDS: &[&str] = &["start", "end"]; + + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + Start, + End, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`start` or `end`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "start" => Ok(Field::Start), + "end" => Ok(Field::End), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"start" => Ok(Field::Start), + b"end" => Ok(Field::End), + _ => { + let value = private::string::from_utf8_lossy(value); + Err(Error::unknown_field(&*value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + pub struct RangeVisitor { + pub expecting: &'static str, + pub phantom: PhantomData, + } + + impl<'de, Idx> Visitor<'de> for RangeVisitor + where + Idx: Deserialize<'de>, + { + type Value = (Idx, Idx); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.expecting) + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let start: Idx = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let end: Idx = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + Ok((start, end)) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut start: Option = None; + let mut end: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::Start => { + if start.is_some() { + return Err(::duplicate_field("start")); + } + start = Some(tri!(map.next_value())); + } + Field::End => { + if end.is_some() { + return Err(::duplicate_field("end")); + } + end = Some(tri!(map.next_value())); + } + } + } + let start = match start { + Some(start) => start, + None => return Err(::missing_field("start")), + }; + let end = match end { + Some(end) => end, + None => return Err(::missing_field("end")), + }; + Ok((start, end)) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Similar to: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct RangeFrom { +// start: Idx, +// } +impl<'de, Idx> Deserialize<'de> for RangeFrom +where + Idx: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let start = tri!(deserializer.deserialize_struct( + "RangeFrom", + range_from::FIELDS, + range_from::RangeFromVisitor { + expecting: "struct RangeFrom", + phantom: PhantomData, + }, + )); + Ok(start..) + } +} + +mod range_from { + use crate::lib::*; + + use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + use crate::private; + + pub const FIELDS: &[&str] = &["start"]; + + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + Start, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`start`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "start" => Ok(Field::Start), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"start" => Ok(Field::Start), + _ => { + let value = private::string::from_utf8_lossy(value); + Err(Error::unknown_field(&*value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + pub struct RangeFromVisitor { + pub expecting: &'static str, + pub phantom: PhantomData, + } + + impl<'de, Idx> Visitor<'de> for RangeFromVisitor + where + Idx: Deserialize<'de>, + { + type Value = Idx; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.expecting) + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let start: Idx = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + Ok(start) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut start: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::Start => { + if start.is_some() { + return Err(::duplicate_field("start")); + } + start = Some(tri!(map.next_value())); + } + } + } + let start = match start { + Some(start) => start, + None => return Err(::missing_field("start")), + }; + Ok(start) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Similar to: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct RangeTo { +// end: Idx, +// } +impl<'de, Idx> Deserialize<'de> for RangeTo +where + Idx: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let end = tri!(deserializer.deserialize_struct( + "RangeTo", + range_to::FIELDS, + range_to::RangeToVisitor { + expecting: "struct RangeTo", + phantom: PhantomData, + }, + )); + Ok(..end) + } +} + +mod range_to { + use crate::lib::*; + + use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + use crate::private; + + pub const FIELDS: &[&str] = &["end"]; + + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + End, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`end`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "end" => Ok(Field::End), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"end" => Ok(Field::End), + _ => { + let value = private::string::from_utf8_lossy(value); + Err(Error::unknown_field(&*value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + pub struct RangeToVisitor { + pub expecting: &'static str, + pub phantom: PhantomData, + } + + impl<'de, Idx> Visitor<'de> for RangeToVisitor + where + Idx: Deserialize<'de>, + { + type Value = Idx; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.expecting) + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let end: Idx = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + Ok(end) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut end: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::End => { + if end.is_some() { + return Err(::duplicate_field("end")); + } + end = Some(tri!(map.next_value())); + } + } + } + let end = match end { + Some(end) => end, + None => return Err(::missing_field("end")), + }; + Ok(end) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, T> Deserialize<'de> for Bound +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + enum Field { + Unbounded, + Included, + Excluded, + } + + impl<'de> Deserialize<'de> for Field { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`Unbounded`, `Included` or `Excluded`") + } + + fn visit_u64(self, value: u64) -> Result + where + E: Error, + { + match value { + 0 => Ok(Field::Unbounded), + 1 => Ok(Field::Included), + 2 => Ok(Field::Excluded), + _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)), + } + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "Unbounded" => Ok(Field::Unbounded), + "Included" => Ok(Field::Included), + "Excluded" => Ok(Field::Excluded), + _ => Err(Error::unknown_variant(value, VARIANTS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"Unbounded" => Ok(Field::Unbounded), + b"Included" => Ok(Field::Included), + b"Excluded" => Ok(Field::Excluded), + _ => match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, VARIANTS)), + Err(_) => { + Err(Error::invalid_value(Unexpected::Bytes(value), &self)) + } + }, + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + struct BoundVisitor(PhantomData>); + + impl<'de, T> Visitor<'de> for BoundVisitor + where + T: Deserialize<'de>, + { + type Value = Bound; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("enum Bound") + } + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + match tri!(data.variant()) { + (Field::Unbounded, v) => v.unit_variant().map(|()| Bound::Unbounded), + (Field::Included, v) => v.newtype_variant().map(Bound::Included), + (Field::Excluded, v) => v.newtype_variant().map(Bound::Excluded), + } + } + } + + const VARIANTS: &[&str] = &["Unbounded", "Included", "Excluded"]; + + deserializer.deserialize_enum("Bound", VARIANTS, BoundVisitor(PhantomData)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "result")] +#[cfg_attr(docsrs, doc(cfg(feature = "result")))] +impl<'de, T, E> Deserialize<'de> for Result +where + T: Deserialize<'de>, + E: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(variant_identifier)] + enum Field { + Ok, + Err, + } + + impl<'de> Deserialize<'de> for Field { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`Ok` or `Err`") + } + + fn visit_u64(self, value: u64) -> Result + where + E: Error, + { + match value { + 0 => Ok(Field::Ok), + 1 => Ok(Field::Err), + _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)), + } + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "Ok" => Ok(Field::Ok), + "Err" => Ok(Field::Err), + _ => Err(Error::unknown_variant(value, VARIANTS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"Ok" => Ok(Field::Ok), + b"Err" => Ok(Field::Err), + _ => match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, VARIANTS)), + Err(_) => { + Err(Error::invalid_value(Unexpected::Bytes(value), &self)) + } + }, + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + struct ResultVisitor(PhantomData>); + + impl<'de, T, E> Visitor<'de> for ResultVisitor + where + T: Deserialize<'de>, + E: Deserialize<'de>, + { + type Value = Result; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("enum Result") + } + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + match tri!(data.variant()) { + (Field::Ok, v) => v.newtype_variant().map(Ok), + (Field::Err, v) => v.newtype_variant().map(Err), + } + } + } + + const VARIANTS: &[&str] = &["Ok", "Err"]; + + deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, T> Deserialize<'de> for Wrapping +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(Wrapping) + } +} + +#[cfg(all(feature = "std", not(no_std_atomic)))] +macro_rules! atomic_impl { + ($($ty:ident $size:expr)*) => { + $( + #[cfg(any(no_target_has_atomic, target_has_atomic = $size))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "std", target_has_atomic = $size))))] + impl<'de> Deserialize<'de> for $ty { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(Self::new) + } + } + )* + }; +} + +#[cfg(all(feature = "std", not(no_std_atomic)))] +atomic_impl! { + AtomicBool "8" + AtomicI8 "8" + AtomicI16 "16" + AtomicI32 "32" + AtomicIsize "ptr" + AtomicU8 "8" + AtomicU16 "16" + AtomicU32 "32" + AtomicUsize "ptr" +} + +#[cfg(all(feature = "std", not(no_std_atomic64)))] +atomic_impl! { + AtomicI64 "64" + AtomicU64 "64" +} + +#[cfg(any(feature = "std", not(no_core_net)))] +struct FromStrVisitor { + expecting: &'static str, + ty: PhantomData, +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl FromStrVisitor { + fn new(expecting: &'static str) -> Self { + FromStrVisitor { + expecting, + ty: PhantomData, + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl<'de, T> Visitor<'de> for FromStrVisitor +where + T: str::FromStr, + T::Err: fmt::Display, +{ + type Value = T; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.expecting) + } + + fn visit_str(self, s: &str) -> Result + where + E: Error, + { + s.parse().map_err(Error::custom) + } +} diff --git a/pkg/installer/vendor/serde_core/src/de/mod.rs b/pkg/installer/vendor/serde_core/src/de/mod.rs new file mode 100644 index 00000000000..2518ae68274 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/de/mod.rs @@ -0,0 +1,2392 @@ +//! Generic data structure deserialization framework. +//! +//! The two most important traits in this module are [`Deserialize`] and +//! [`Deserializer`]. +//! +//! - **A type that implements `Deserialize` is a data structure** that can be +//! deserialized from any data format supported by Serde, and conversely +//! - **A type that implements `Deserializer` is a data format** that can +//! deserialize any data structure supported by Serde. +//! +//! # The Deserialize trait +//! +//! Serde provides [`Deserialize`] implementations for many Rust primitive and +//! standard library types. The complete list is below. All of these can be +//! deserialized using Serde out of the box. +//! +//! Additionally, Serde provides a procedural macro called [`serde_derive`] to +//! automatically generate [`Deserialize`] implementations for structs and enums +//! in your program. See the [derive section of the manual] for how to use this. +//! +//! In rare cases it may be necessary to implement [`Deserialize`] manually for +//! some type in your program. See the [Implementing `Deserialize`] section of +//! the manual for more about this. +//! +//! Third-party crates may provide [`Deserialize`] implementations for types +//! that they expose. For example the [`linked-hash-map`] crate provides a +//! [`LinkedHashMap`] type that is deserializable by Serde because the +//! crate provides an implementation of [`Deserialize`] for it. +//! +//! # The Deserializer trait +//! +//! [`Deserializer`] implementations are provided by third-party crates, for +//! example [`serde_json`], [`serde_yaml`] and [`postcard`]. +//! +//! A partial list of well-maintained formats is given on the [Serde +//! website][data formats]. +//! +//! # Implementations of Deserialize provided by Serde +//! +//! This is a slightly different set of types than what is supported for +//! serialization. Some types can be serialized by Serde but not deserialized. +//! One example is `OsStr`. +//! +//! - **Primitive types**: +//! - bool +//! - i8, i16, i32, i64, i128, isize +//! - u8, u16, u32, u64, u128, usize +//! - f32, f64 +//! - char +//! - **Compound types**: +//! - \[T; 0\] through \[T; 32\] +//! - tuples up to size 16 +//! - **Common standard library types**: +//! - String +//! - Option\ +//! - Result\ +//! - PhantomData\ +//! - **Wrapper types**: +//! - Box\ +//! - Box\<\[T\]\> +//! - Box\ +//! - Cow\<'a, T\> +//! - Cell\ +//! - RefCell\ +//! - Mutex\ +//! - RwLock\ +//! - Rc\ *(if* features = \["rc"\] *is enabled)* +//! - Arc\ *(if* features = \["rc"\] *is enabled)* +//! - **Collection types**: +//! - BTreeMap\ +//! - BTreeSet\ +//! - BinaryHeap\ +//! - HashMap\ +//! - HashSet\ +//! - LinkedList\ +//! - VecDeque\ +//! - Vec\ +//! - **Zero-copy types**: +//! - &str +//! - &\[u8\] +//! - **FFI types**: +//! - CString +//! - Box\ +//! - OsString +//! - **Miscellaneous standard library types**: +//! - Duration +//! - SystemTime +//! - Path +//! - PathBuf +//! - Range\ +//! - RangeInclusive\ +//! - Bound\ +//! - num::NonZero* +//! - `!` *(unstable)* +//! - **Net types**: +//! - IpAddr +//! - Ipv4Addr +//! - Ipv6Addr +//! - SocketAddr +//! - SocketAddrV4 +//! - SocketAddrV6 +//! +//! [Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html +//! [`Deserialize`]: crate::Deserialize +//! [`Deserializer`]: crate::Deserializer +//! [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +//! [`postcard`]: https://github.com/jamesmunns/postcard +//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map +//! [`serde_derive`]: https://crates.io/crates/serde_derive +//! [`serde_json`]: https://github.com/serde-rs/json +//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml +//! [derive section of the manual]: https://serde.rs/derive.html +//! [data formats]: https://serde.rs/#data-formats + +use crate::lib::*; + +//////////////////////////////////////////////////////////////////////////////// + +pub mod value; + +mod ignored_any; +mod impls; + +pub use self::ignored_any::IgnoredAny; +#[cfg(all(not(feature = "std"), no_core_error))] +#[doc(no_inline)] +pub use crate::std_error::Error as StdError; +#[cfg(not(any(feature = "std", no_core_error)))] +#[doc(no_inline)] +pub use core::error::Error as StdError; +#[cfg(feature = "std")] +#[doc(no_inline)] +pub use std::error::Error as StdError; + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! declare_error_trait { + (Error: Sized $(+ $($supertrait:ident)::+)*) => { + /// The `Error` trait allows `Deserialize` implementations to create descriptive + /// error messages belonging to the `Deserializer` against which they are + /// currently running. + /// + /// Every `Deserializer` declares an `Error` type that encompasses both + /// general-purpose deserialization errors as well as errors specific to the + /// particular deserialization format. For example the `Error` type of + /// `serde_json` can represent errors like an invalid JSON escape sequence or an + /// unterminated string literal, in addition to the error cases that are part of + /// this trait. + /// + /// Most deserializers should only need to provide the `Error::custom` method + /// and inherit the default behavior for the other methods. + /// + /// # Example implementation + /// + /// The [example data format] presented on the website shows an error + /// type appropriate for a basic JSON data format. + /// + /// [example data format]: https://serde.rs/data-format.html + #[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::Error` is not satisfied", + ) + )] + pub trait Error: Sized $(+ $($supertrait)::+)* { + /// Raised when there is general error when deserializing a type. + /// + /// The message should not be capitalized and should not end with a period. + /// + /// ```edition2021 + /// # use std::str::FromStr; + /// # + /// # struct IpAddr; + /// # + /// # impl FromStr for IpAddr { + /// # type Err = String; + /// # + /// # fn from_str(_: &str) -> Result { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::de::{self, Deserialize, Deserializer}; + /// + /// impl<'de> Deserialize<'de> for IpAddr { + /// fn deserialize(deserializer: D) -> Result + /// where + /// D: Deserializer<'de>, + /// { + /// let s = String::deserialize(deserializer)?; + /// s.parse().map_err(de::Error::custom) + /// } + /// } + /// ``` + fn custom(msg: T) -> Self + where + T: Display; + + /// Raised when a `Deserialize` receives a type different from what it was + /// expecting. + /// + /// The `unexp` argument provides information about what type was received. + /// This is the type that was present in the input file or other source data + /// of the Deserializer. + /// + /// The `exp` argument provides information about what type was being + /// expected. This is the type that is written in the program. + /// + /// For example if we try to deserialize a String out of a JSON file + /// containing an integer, the unexpected type is the integer and the + /// expected type is the string. + #[cold] + fn invalid_type(unexp: Unexpected, exp: &dyn Expected) -> Self { + Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp)) + } + + /// Raised when a `Deserialize` receives a value of the right type but that + /// is wrong for some other reason. + /// + /// The `unexp` argument provides information about what value was received. + /// This is the value that was present in the input file or other source + /// data of the Deserializer. + /// + /// The `exp` argument provides information about what value was being + /// expected. This is the type that is written in the program. + /// + /// For example if we try to deserialize a String out of some binary data + /// that is not valid UTF-8, the unexpected value is the bytes and the + /// expected value is a string. + #[cold] + fn invalid_value(unexp: Unexpected, exp: &dyn Expected) -> Self { + Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp)) + } + + /// Raised when deserializing a sequence or map and the input data contains + /// too many or too few elements. + /// + /// The `len` argument is the number of elements encountered. The sequence + /// or map may have expected more arguments or fewer arguments. + /// + /// The `exp` argument provides information about what data was being + /// expected. For example `exp` might say that a tuple of size 6 was + /// expected. + #[cold] + fn invalid_length(len: usize, exp: &dyn Expected) -> Self { + Error::custom(format_args!("invalid length {}, expected {}", len, exp)) + } + + /// Raised when a `Deserialize` enum type received a variant with an + /// unrecognized name. + #[cold] + fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self { + if expected.is_empty() { + Error::custom(format_args!( + "unknown variant `{}`, there are no variants", + variant + )) + } else { + Error::custom(format_args!( + "unknown variant `{}`, expected {}", + variant, + OneOf { names: expected } + )) + } + } + + /// Raised when a `Deserialize` struct type received a field with an + /// unrecognized name. + #[cold] + fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self { + if expected.is_empty() { + Error::custom(format_args!( + "unknown field `{}`, there are no fields", + field + )) + } else { + Error::custom(format_args!( + "unknown field `{}`, expected {}", + field, + OneOf { names: expected } + )) + } + } + + /// Raised when a `Deserialize` struct type expected to receive a required + /// field with a particular name but that field was not present in the + /// input. + #[cold] + fn missing_field(field: &'static str) -> Self { + Error::custom(format_args!("missing field `{}`", field)) + } + + /// Raised when a `Deserialize` struct type received more than one of the + /// same field. + #[cold] + fn duplicate_field(field: &'static str) -> Self { + Error::custom(format_args!("duplicate field `{}`", field)) + } + } + } +} + +#[cfg(feature = "std")] +declare_error_trait!(Error: Sized + StdError); + +#[cfg(not(feature = "std"))] +declare_error_trait!(Error: Sized + Debug + Display); + +/// `Unexpected` represents an unexpected invocation of any one of the `Visitor` +/// trait methods. +/// +/// This is used as an argument to the `invalid_type`, `invalid_value`, and +/// `invalid_length` methods of the `Error` trait to build error messages. +/// +/// ```edition2021 +/// # use std::fmt; +/// # +/// # use serde::de::{self, Unexpected, Visitor}; +/// # +/// # struct Example; +/// # +/// # impl<'de> Visitor<'de> for Example { +/// # type Value = (); +/// # +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "definitely not a boolean") +/// # } +/// # +/// fn visit_bool(self, v: bool) -> Result +/// where +/// E: de::Error, +/// { +/// Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) +/// } +/// # } +/// ``` +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum Unexpected<'a> { + /// The input contained a boolean value that was not expected. + Bool(bool), + + /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that + /// was not expected. + Unsigned(u64), + + /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that + /// was not expected. + Signed(i64), + + /// The input contained a floating point `f32` or `f64` that was not + /// expected. + Float(f64), + + /// The input contained a `char` that was not expected. + Char(char), + + /// The input contained a `&str` or `String` that was not expected. + Str(&'a str), + + /// The input contained a `&[u8]` or `Vec` that was not expected. + Bytes(&'a [u8]), + + /// The input contained a unit `()` that was not expected. + Unit, + + /// The input contained an `Option` that was not expected. + Option, + + /// The input contained a newtype struct that was not expected. + NewtypeStruct, + + /// The input contained a sequence that was not expected. + Seq, + + /// The input contained a map that was not expected. + Map, + + /// The input contained an enum that was not expected. + Enum, + + /// The input contained a unit variant that was not expected. + UnitVariant, + + /// The input contained a newtype variant that was not expected. + NewtypeVariant, + + /// The input contained a tuple variant that was not expected. + TupleVariant, + + /// The input contained a struct variant that was not expected. + StructVariant, + + /// A message stating what uncategorized thing the input contained that was + /// not expected. + /// + /// The message should be a noun or noun phrase, not capitalized and without + /// a period. An example message is "unoriginal superhero". + Other(&'a str), +} + +impl<'a> fmt::Display for Unexpected<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + use self::Unexpected::*; + match *self { + Bool(b) => write!(formatter, "boolean `{}`", b), + Unsigned(i) => write!(formatter, "integer `{}`", i), + Signed(i) => write!(formatter, "integer `{}`", i), + Float(f) => write!(formatter, "floating point `{}`", WithDecimalPoint(f)), + Char(c) => write!(formatter, "character `{}`", c), + Str(s) => write!(formatter, "string {:?}", s), + Bytes(_) => formatter.write_str("byte array"), + Unit => formatter.write_str("unit value"), + Option => formatter.write_str("Option value"), + NewtypeStruct => formatter.write_str("newtype struct"), + Seq => formatter.write_str("sequence"), + Map => formatter.write_str("map"), + Enum => formatter.write_str("enum"), + UnitVariant => formatter.write_str("unit variant"), + NewtypeVariant => formatter.write_str("newtype variant"), + TupleVariant => formatter.write_str("tuple variant"), + StructVariant => formatter.write_str("struct variant"), + Other(other) => formatter.write_str(other), + } + } +} + +/// `Expected` represents an explanation of what data a `Visitor` was expecting +/// to receive. +/// +/// This is used as an argument to the `invalid_type`, `invalid_value`, and +/// `invalid_length` methods of the `Error` trait to build error messages. The +/// message should be a noun or noun phrase that completes the sentence "This +/// Visitor expects to receive ...", for example the message could be "an +/// integer between 0 and 64". The message should not be capitalized and should +/// not end with a period. +/// +/// Within the context of a `Visitor` implementation, the `Visitor` itself +/// (`&self`) is an implementation of this trait. +/// +/// ```edition2021 +/// # use serde::de::{self, Unexpected, Visitor}; +/// # use std::fmt; +/// # +/// # struct Example; +/// # +/// # impl<'de> Visitor<'de> for Example { +/// # type Value = (); +/// # +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "definitely not a boolean") +/// # } +/// # +/// fn visit_bool(self, v: bool) -> Result +/// where +/// E: de::Error, +/// { +/// Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) +/// } +/// # } +/// ``` +/// +/// Outside of a `Visitor`, `&"..."` can be used. +/// +/// ```edition2021 +/// # use serde::de::{self, Unexpected}; +/// # +/// # fn example() -> Result<(), E> +/// # where +/// # E: de::Error, +/// # { +/// # let v = true; +/// return Err(de::Error::invalid_type( +/// Unexpected::Bool(v), +/// &"a negative integer", +/// )); +/// # } +/// ``` +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::Expected` is not satisfied", + ) +)] +pub trait Expected { + /// Format an explanation of what data was being expected. Same signature as + /// the `Display` and `Debug` traits. + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result; +} + +impl<'de, T> Expected for T +where + T: Visitor<'de>, +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.expecting(formatter) + } +} + +impl Expected for &str { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self) + } +} + +impl Display for dyn Expected + '_ { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Expected::fmt(self, formatter) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data structure** that can be deserialized from any data format supported +/// by Serde. +/// +/// Serde provides `Deserialize` implementations for many Rust primitive and +/// standard library types. The complete list is [here][crate::de]. All of these +/// can be deserialized using Serde out of the box. +/// +/// Additionally, Serde provides a procedural macro called `serde_derive` to +/// automatically generate `Deserialize` implementations for structs and enums +/// in your program. See the [derive section of the manual][derive] for how to +/// use this. +/// +/// In rare cases it may be necessary to implement `Deserialize` manually for +/// some type in your program. See the [Implementing +/// `Deserialize`][impl-deserialize] section of the manual for more about this. +/// +/// Third-party crates may provide `Deserialize` implementations for types that +/// they expose. For example the `linked-hash-map` crate provides a +/// `LinkedHashMap` type that is deserializable by Serde because the crate +/// provides an implementation of `Deserialize` for it. +/// +/// [derive]: https://serde.rs/derive.html +/// [impl-deserialize]: https://serde.rs/impl-deserialize.html +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by `Self` when deserialized. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + // Prevents `serde_core::de::Deserialize` appearing in the error message + // in projects with no direct dependency on serde_core. + message = "the trait bound `{Self}: serde::Deserialize<'de>` is not satisfied", + note = "for local types consider adding `#[derive(serde::Deserialize)]` to your `{Self}` type", + note = "for types from other crates check whether the crate offers a `serde` feature flag", + ) +)] +pub trait Deserialize<'de>: Sized { + /// Deserialize this value from the given Serde deserializer. + /// + /// See the [Implementing `Deserialize`][impl-deserialize] section of the + /// manual for more information about how to implement this method. + /// + /// [impl-deserialize]: https://serde.rs/impl-deserialize.html + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>; + + /// Deserializes a value into `self` from the given Deserializer. + /// + /// The purpose of this method is to allow the deserializer to reuse + /// resources and avoid copies. As such, if this method returns an error, + /// `self` will be in an indeterminate state where some parts of the struct + /// have been overwritten. Although whatever state that is will be + /// memory-safe. + /// + /// This is generally useful when repeatedly deserializing values that + /// are processed one at a time, where the value of `self` doesn't matter + /// when the next deserialization occurs. + /// + /// If you manually implement this, your recursive deserializations should + /// use `deserialize_in_place`. + /// + /// This method is stable and an official public API, but hidden from the + /// documentation because it is almost never what newbies are looking for. + /// Showing it in rustdoc would cause it to be featured more prominently + /// than it deserves. + #[doc(hidden)] + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + // Default implementation just delegates to `deserialize` impl. + *place = tri!(Deserialize::deserialize(deserializer)); + Ok(()) + } +} + +/// A data structure that can be deserialized without borrowing any data from +/// the deserializer. +/// +/// This is primarily useful for trait bounds on functions. For example a +/// `from_str` function may be able to deserialize a data structure that borrows +/// from the input string, but a `from_reader` function may only deserialize +/// owned data. +/// +/// ```edition2021 +/// # use serde::de::{Deserialize, DeserializeOwned}; +/// # use std::io::{Read, Result}; +/// # +/// # trait Ignore { +/// fn from_str<'a, T>(s: &'a str) -> Result +/// where +/// T: Deserialize<'a>; +/// +/// fn from_reader(rdr: R) -> Result +/// where +/// R: Read, +/// T: DeserializeOwned; +/// # } +/// ``` +/// +/// # Lifetime +/// +/// The relationship between `Deserialize` and `DeserializeOwned` in trait +/// bounds is explained in more detail on the page [Understanding deserializer +/// lifetimes]. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::DeserializeOwned` is not satisfied", + ) +)] +pub trait DeserializeOwned: for<'de> Deserialize<'de> {} +impl DeserializeOwned for T where T: for<'de> Deserialize<'de> {} + +/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you +/// ever find yourself looking for a way to pass data into a `Deserialize` impl, +/// this trait is the way to do it. +/// +/// As one example of stateful deserialization consider deserializing a JSON +/// array into an existing buffer. Using the `Deserialize` trait we could +/// deserialize a JSON array into a `Vec` but it would be a freshly allocated +/// `Vec`; there is no way for `Deserialize` to reuse a previously allocated +/// buffer. Using `DeserializeSeed` instead makes this possible as in the +/// example code below. +/// +/// The canonical API for stateless deserialization looks like this: +/// +/// ```edition2021 +/// # use serde::Deserialize; +/// # +/// # enum Error {} +/// # +/// fn func<'de, T: Deserialize<'de>>() -> Result +/// # { +/// # unimplemented!() +/// # } +/// ``` +/// +/// Adjusting an API like this to support stateful deserialization is a matter +/// of accepting a seed as input: +/// +/// ```edition2021 +/// # use serde::de::DeserializeSeed; +/// # +/// # enum Error {} +/// # +/// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result +/// # { +/// # let _ = seed; +/// # unimplemented!() +/// # } +/// ``` +/// +/// In practice the majority of deserialization is stateless. An API expecting a +/// seed can be appeased by passing `std::marker::PhantomData` as a seed in the +/// case of stateless deserialization. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by `Self::Value` when deserialized. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example +/// +/// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need +/// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`. +/// Allocating a brand new `Vec` for each subarray would be slow. Instead we +/// would like to allocate a single `Vec` and then deserialize each subarray +/// into it. This requires stateful deserialization using the `DeserializeSeed` +/// trait. +/// +/// ```edition2021 +/// use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor}; +/// use std::fmt; +/// use std::marker::PhantomData; +/// +/// // A DeserializeSeed implementation that uses stateful deserialization to +/// // append array elements onto the end of an existing vector. The preexisting +/// // state ("seed") in this case is the Vec. The `deserialize` method of +/// // `ExtendVec` will be traversing the inner arrays of the JSON input and +/// // appending each integer into the existing Vec. +/// struct ExtendVec<'a, T: 'a>(&'a mut Vec); +/// +/// impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T> +/// where +/// T: Deserialize<'de>, +/// { +/// // The return type of the `deserialize` method. This implementation +/// // appends onto an existing vector but does not create any new data +/// // structure, so the return type is (). +/// type Value = (); +/// +/// fn deserialize(self, deserializer: D) -> Result +/// where +/// D: Deserializer<'de>, +/// { +/// // Visitor implementation that will walk an inner array of the JSON +/// // input. +/// struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec); +/// +/// impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T> +/// where +/// T: Deserialize<'de>, +/// { +/// type Value = (); +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "an array of integers") +/// } +/// +/// fn visit_seq(self, mut seq: A) -> Result<(), A::Error> +/// where +/// A: SeqAccess<'de>, +/// { +/// // Decrease the number of reallocations if there are many elements +/// if let Some(size_hint) = seq.size_hint() { +/// self.0.reserve(size_hint); +/// } +/// +/// // Visit each element in the inner array and push it onto +/// // the existing vector. +/// while let Some(elem) = seq.next_element()? { +/// self.0.push(elem); +/// } +/// Ok(()) +/// } +/// } +/// +/// deserializer.deserialize_seq(ExtendVecVisitor(self.0)) +/// } +/// } +/// +/// // Visitor implementation that will walk the outer array of the JSON input. +/// struct FlattenedVecVisitor(PhantomData); +/// +/// impl<'de, T> Visitor<'de> for FlattenedVecVisitor +/// where +/// T: Deserialize<'de>, +/// { +/// // This Visitor constructs a single Vec to hold the flattened +/// // contents of the inner arrays. +/// type Value = Vec; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "an array of arrays") +/// } +/// +/// fn visit_seq(self, mut seq: A) -> Result, A::Error> +/// where +/// A: SeqAccess<'de>, +/// { +/// // Create a single Vec to hold the flattened contents. +/// let mut vec = Vec::new(); +/// +/// // Each iteration through this loop is one inner array. +/// while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? { +/// // Nothing to do; inner array has been appended into `vec`. +/// } +/// +/// // Return the finished vec. +/// Ok(vec) +/// } +/// } +/// +/// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error> +/// # where +/// # D: Deserializer<'de>, +/// # { +/// let visitor = FlattenedVecVisitor(PhantomData); +/// let flattened: Vec = deserializer.deserialize_seq(visitor)?; +/// # Ok(()) +/// # } +/// ``` +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::DeserializeSeed<'de>` is not satisfied", + ) +)] +pub trait DeserializeSeed<'de>: Sized { + /// The type produced by using this seed. + type Value; + + /// Equivalent to the more common `Deserialize::deserialize` method, except + /// with some initial piece of data (the seed) passed in. + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>; +} + +impl<'de, T> DeserializeSeed<'de> for PhantomData +where + T: Deserialize<'de>, +{ + type Value = T; + + #[inline] + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::deserialize(deserializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data format** that can deserialize any data structure supported by +/// Serde. +/// +/// The role of this trait is to define the deserialization half of the [Serde +/// data model], which is a way to categorize every Rust data type into one of +/// 29 possible types. Each method of the `Deserializer` trait corresponds to one +/// of the types of the data model. +/// +/// Implementations of `Deserialize` map themselves into this data model by +/// passing to the `Deserializer` a `Visitor` implementation that can receive +/// these various types. +/// +/// The types that make up the Serde data model are: +/// +/// - **14 primitive types** +/// - bool +/// - i8, i16, i32, i64, i128 +/// - u8, u16, u32, u64, u128 +/// - f32, f64 +/// - char +/// - **string** +/// - UTF-8 bytes with a length and no null terminator. +/// - When serializing, all strings are handled equally. When deserializing, +/// there are three flavors of strings: transient, owned, and borrowed. +/// - **byte array** - \[u8\] +/// - Similar to strings, during deserialization byte arrays can be +/// transient, owned, or borrowed. +/// - **option** +/// - Either none or some value. +/// - **unit** +/// - The type of `()` in Rust. It represents an anonymous value containing +/// no data. +/// - **unit_struct** +/// - For example `struct Unit` or `PhantomData`. It represents a named +/// value containing no data. +/// - **unit_variant** +/// - For example the `E::A` and `E::B` in `enum E { A, B }`. +/// - **newtype_struct** +/// - For example `struct Millimeters(u8)`. +/// - **newtype_variant** +/// - For example the `E::N` in `enum E { N(u8) }`. +/// - **seq** +/// - A variably sized heterogeneous sequence of values, for example `Vec` +/// or `HashSet`. When serializing, the length may or may not be known +/// before iterating through all the data. When deserializing, the length +/// is determined by looking at the serialized data. +/// - **tuple** +/// - A statically sized heterogeneous sequence of values for which the +/// length will be known at deserialization time without looking at the +/// serialized data, for example `(u8,)` or `(String, u64, Vec)` or +/// `[u64; 10]`. +/// - **tuple_struct** +/// - A named tuple, for example `struct Rgb(u8, u8, u8)`. +/// - **tuple_variant** +/// - For example the `E::T` in `enum E { T(u8, u8) }`. +/// - **map** +/// - A heterogeneous key-value pairing, for example `BTreeMap`. +/// - **struct** +/// - A heterogeneous key-value pairing in which the keys are strings and +/// will be known at deserialization time without looking at the serialized +/// data, for example `struct S { r: u8, g: u8, b: u8 }`. +/// - **struct_variant** +/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. +/// +/// The `Deserializer` trait supports two entry point styles which enables +/// different kinds of deserialization. +/// +/// 1. The `deserialize_any` method. Self-describing data formats like JSON are +/// able to look at the serialized data and tell what it represents. For +/// example the JSON deserializer may see an opening curly brace (`{`) and +/// know that it is seeing a map. If the data format supports +/// `Deserializer::deserialize_any`, it will drive the Visitor using whatever +/// type it sees in the input. JSON uses this approach when deserializing +/// `serde_json::Value` which is an enum that can represent any JSON +/// document. Without knowing what is in a JSON document, we can deserialize +/// it to `serde_json::Value` by going through +/// `Deserializer::deserialize_any`. +/// +/// 2. The various `deserialize_*` methods. Non-self-describing formats like +/// Postcard need to be told what is in the input in order to deserialize it. +/// The `deserialize_*` methods are hints to the deserializer for how to +/// interpret the next piece of input. Non-self-describing formats are not +/// able to deserialize something like `serde_json::Value` which relies on +/// `Deserializer::deserialize_any`. +/// +/// When implementing `Deserialize`, you should avoid relying on +/// `Deserializer::deserialize_any` unless you need to be told by the +/// Deserializer what type is in the input. Know that relying on +/// `Deserializer::deserialize_any` means your data type will be able to +/// deserialize from self-describing formats only, ruling out Postcard and many +/// others. +/// +/// [Serde data model]: https://serde.rs/data-model.html +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed from the input when deserializing. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website contains example code for +/// a basic JSON `Deserializer`. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::Deserializer<'de>` is not satisfied", + ) +)] +pub trait Deserializer<'de>: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// Require the `Deserializer` to figure out how to drive the visitor based + /// on what data type is in the input. + /// + /// When implementing `Deserialize`, you should avoid relying on + /// `Deserializer::deserialize_any` unless you need to be told by the + /// Deserializer what type is in the input. Know that relying on + /// `Deserializer::deserialize_any` means your data type will be able to + /// deserialize from self-describing formats only, ruling out Postcard and + /// many others. + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `bool` value. + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i8` value. + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i16` value. + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i32` value. + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i64` value. + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i128` value. + /// + /// The default behavior unconditionally returns an error. + fn deserialize_i128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let _ = visitor; + Err(Error::custom("i128 is not supported")) + } + + /// Hint that the `Deserialize` type is expecting a `u8` value. + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u16` value. + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u32` value. + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u64` value. + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `u128` value. + /// + /// The default behavior unconditionally returns an error. + fn deserialize_u128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let _ = visitor; + Err(Error::custom("u128 is not supported")) + } + + /// Hint that the `Deserialize` type is expecting a `f32` value. + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `f64` value. + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `char` value. + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a string value and does + /// not benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would benefit from taking ownership of `String` data, + /// indicate this to the `Deserializer` by using `deserialize_string` + /// instead. + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a string value and would + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would not benefit from taking ownership of `String` + /// data, indicate that to the `Deserializer` by using `deserialize_str` + /// instead. + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a byte array and does not + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would benefit from taking ownership of `Vec` data, + /// indicate this to the `Deserializer` by using `deserialize_byte_buf` + /// instead. + fn deserialize_bytes(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a byte array and would + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would not benefit from taking ownership of `Vec` + /// data, indicate that to the `Deserializer` by using `deserialize_bytes` + /// instead. + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an optional value. + /// + /// This allows deserializers that encode an optional value as a nullable + /// value to convert the null value into `None` and a regular value into + /// `Some(value)`. + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a unit value. + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a unit struct with a + /// particular name. + fn deserialize_unit_struct( + self, + name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a newtype struct with a + /// particular name. + fn deserialize_newtype_struct( + self, + name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a sequence of values. + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a sequence of values and + /// knows how many values there are without looking at the serialized data. + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a tuple struct with a + /// particular name and number of fields. + fn deserialize_tuple_struct( + self, + name: &'static str, + len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a map of key-value pairs. + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a struct with a particular + /// name and fields. + fn deserialize_struct( + self, + name: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an enum value with a + /// particular name and possible variants. + fn deserialize_enum( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting the name of a struct + /// field or the discriminant of an enum variant. + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type needs to deserialize a value whose type + /// doesn't matter because it is ignored. + /// + /// Deserializers for non-self-describing formats may not support this mode. + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Determine whether `Deserialize` implementations should expect to + /// deserialize their human-readable form. + /// + /// Some types have a human-readable form that may be somewhat expensive to + /// construct, as well as a binary form that is compact and efficient. + /// Generally text-based formats like JSON and YAML will prefer to use the + /// human-readable one and binary formats like Postcard will prefer the + /// compact one. + /// + /// ```edition2021 + /// # use std::ops::Add; + /// # use std::str::FromStr; + /// # + /// # struct Timestamp; + /// # + /// # impl Timestamp { + /// # const EPOCH: Timestamp = Timestamp; + /// # } + /// # + /// # impl FromStr for Timestamp { + /// # type Err = String; + /// # fn from_str(_: &str) -> Result { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # struct Duration; + /// # + /// # impl Duration { + /// # fn seconds(_: u64) -> Self { unimplemented!() } + /// # } + /// # + /// # impl Add for Timestamp { + /// # type Output = Timestamp; + /// # fn add(self, _: Duration) -> Self::Output { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::de::{self, Deserialize, Deserializer}; + /// + /// impl<'de> Deserialize<'de> for Timestamp { + /// fn deserialize(deserializer: D) -> Result + /// where + /// D: Deserializer<'de>, + /// { + /// if deserializer.is_human_readable() { + /// // Deserialize from a human-readable string like "2015-05-15T17:01:00Z". + /// let s = String::deserialize(deserializer)?; + /// Timestamp::from_str(&s).map_err(de::Error::custom) + /// } else { + /// // Deserialize from a compact binary representation, seconds since + /// // the Unix epoch. + /// let n = u64::deserialize(deserializer)?; + /// Ok(Timestamp::EPOCH + Duration::seconds(n)) + /// } + /// } + /// } + /// ``` + /// + /// The default implementation of this method returns `true`. Data formats + /// may override this to `false` to request a compact form for types that + /// support one. Note that modifying this method to change a format from + /// human-readable to compact or vice versa should be regarded as a breaking + /// change, as a value serialized in human-readable mode is not required to + /// deserialize from the same data in compact mode. + #[inline] + fn is_human_readable(&self) -> bool { + true + } + + // Not public API. + #[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))] + #[doc(hidden)] + fn __deserialize_content_v1(self, visitor: V) -> Result + where + V: Visitor<'de, Value = crate::private::Content<'de>>, + { + self.deserialize_any(visitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// This trait represents a visitor that walks through a deserializer. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the requirement for lifetime of data +/// that may be borrowed by `Self::Value`. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example +/// +/// ```edition2021 +/// # use serde::de::{self, Unexpected, Visitor}; +/// # use std::fmt; +/// # +/// /// A visitor that deserializes a long string - a string containing at least +/// /// some minimum number of bytes. +/// struct LongString { +/// min: usize, +/// } +/// +/// impl<'de> Visitor<'de> for LongString { +/// type Value = String; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "a string containing at least {} bytes", self.min) +/// } +/// +/// fn visit_str(self, s: &str) -> Result +/// where +/// E: de::Error, +/// { +/// if s.len() >= self.min { +/// Ok(s.to_owned()) +/// } else { +/// Err(de::Error::invalid_value(Unexpected::Str(s), &self)) +/// } +/// } +/// } +/// ``` +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::Visitor<'de>` is not satisfied", + ) +)] +pub trait Visitor<'de>: Sized { + /// The value produced by this visitor. + type Value; + + /// Format a message stating what data this Visitor expects to receive. + /// + /// This is used in error messages. The message should complete the sentence + /// "This Visitor expects to receive ...", for example the message could be + /// "an integer between 0 and 64". The message should not be capitalized and + /// should not end with a period. + /// + /// ```edition2021 + /// # use std::fmt; + /// # + /// # struct S { + /// # max: usize, + /// # } + /// # + /// # impl<'de> serde::de::Visitor<'de> for S { + /// # type Value = (); + /// # + /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + /// write!(formatter, "an integer between 0 and {}", self.max) + /// } + /// # } + /// ``` + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result; + + /// The input contains a boolean. + /// + /// The default implementation fails with a type error. + fn visit_bool(self, v: bool) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Bool(v), &self)) + } + + /// The input contains an `i8`. + /// + /// The default implementation forwards to [`visit_i64`]. + /// + /// [`visit_i64`]: #method.visit_i64 + fn visit_i8(self, v: i8) -> Result + where + E: Error, + { + self.visit_i64(v as i64) + } + + /// The input contains an `i16`. + /// + /// The default implementation forwards to [`visit_i64`]. + /// + /// [`visit_i64`]: #method.visit_i64 + fn visit_i16(self, v: i16) -> Result + where + E: Error, + { + self.visit_i64(v as i64) + } + + /// The input contains an `i32`. + /// + /// The default implementation forwards to [`visit_i64`]. + /// + /// [`visit_i64`]: #method.visit_i64 + fn visit_i32(self, v: i32) -> Result + where + E: Error, + { + self.visit_i64(v as i64) + } + + /// The input contains an `i64`. + /// + /// The default implementation fails with a type error. + fn visit_i64(self, v: i64) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Signed(v), &self)) + } + + /// The input contains a `i128`. + /// + /// The default implementation fails with a type error. + fn visit_i128(self, v: i128) -> Result + where + E: Error, + { + let mut buf = [0u8; 58]; + let mut writer = crate::format::Buf::new(&mut buf); + fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as i128", v)).unwrap(); + Err(Error::invalid_type( + Unexpected::Other(writer.as_str()), + &self, + )) + } + + /// The input contains a `u8`. + /// + /// The default implementation forwards to [`visit_u64`]. + /// + /// [`visit_u64`]: #method.visit_u64 + fn visit_u8(self, v: u8) -> Result + where + E: Error, + { + self.visit_u64(v as u64) + } + + /// The input contains a `u16`. + /// + /// The default implementation forwards to [`visit_u64`]. + /// + /// [`visit_u64`]: #method.visit_u64 + fn visit_u16(self, v: u16) -> Result + where + E: Error, + { + self.visit_u64(v as u64) + } + + /// The input contains a `u32`. + /// + /// The default implementation forwards to [`visit_u64`]. + /// + /// [`visit_u64`]: #method.visit_u64 + fn visit_u32(self, v: u32) -> Result + where + E: Error, + { + self.visit_u64(v as u64) + } + + /// The input contains a `u64`. + /// + /// The default implementation fails with a type error. + fn visit_u64(self, v: u64) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Unsigned(v), &self)) + } + + /// The input contains a `u128`. + /// + /// The default implementation fails with a type error. + fn visit_u128(self, v: u128) -> Result + where + E: Error, + { + let mut buf = [0u8; 57]; + let mut writer = crate::format::Buf::new(&mut buf); + fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as u128", v)).unwrap(); + Err(Error::invalid_type( + Unexpected::Other(writer.as_str()), + &self, + )) + } + + /// The input contains an `f32`. + /// + /// The default implementation forwards to [`visit_f64`]. + /// + /// [`visit_f64`]: #method.visit_f64 + fn visit_f32(self, v: f32) -> Result + where + E: Error, + { + self.visit_f64(v as f64) + } + + /// The input contains an `f64`. + /// + /// The default implementation fails with a type error. + fn visit_f64(self, v: f64) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Float(v), &self)) + } + + /// The input contains a `char`. + /// + /// The default implementation forwards to [`visit_str`] as a one-character + /// string. + /// + /// [`visit_str`]: #method.visit_str + #[inline] + fn visit_char(self, v: char) -> Result + where + E: Error, + { + self.visit_str(v.encode_utf8(&mut [0u8; 4])) + } + + /// The input contains a string. The lifetime of the string is ephemeral and + /// it may be destroyed after this method returns. + /// + /// This method allows the `Deserializer` to avoid a copy by retaining + /// ownership of any buffered data. `Deserialize` implementations that do + /// not benefit from taking ownership of `String` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_str` rather than + /// `Deserializer::deserialize_string`. + /// + /// It is never correct to implement `visit_string` without implementing + /// `visit_str`. Implement neither, both, or just `visit_str`. + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Str(v), &self)) + } + + /// The input contains a string that lives at least as long as the + /// `Deserializer`. + /// + /// This enables zero-copy deserialization of strings in some formats. For + /// example JSON input containing the JSON string `"borrowed"` can be + /// deserialized with zero copying into a `&'a str` as long as the input + /// data outlives `'a`. + /// + /// The default implementation forwards to `visit_str`. + #[inline] + fn visit_borrowed_str(self, v: &'de str) -> Result + where + E: Error, + { + self.visit_str(v) + } + + /// The input contains a string and ownership of the string is being given + /// to the `Visitor`. + /// + /// This method allows the `Visitor` to avoid a copy by taking ownership of + /// a string created by the `Deserializer`. `Deserialize` implementations + /// that benefit from taking ownership of `String` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_string` rather + /// than `Deserializer::deserialize_str`, although not every deserializer + /// will honor such a request. + /// + /// It is never correct to implement `visit_string` without implementing + /// `visit_str`. Implement neither, both, or just `visit_str`. + /// + /// The default implementation forwards to `visit_str` and then drops the + /// `String`. + #[inline] + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + fn visit_string(self, v: String) -> Result + where + E: Error, + { + self.visit_str(&v) + } + + /// The input contains a byte array. The lifetime of the byte array is + /// ephemeral and it may be destroyed after this method returns. + /// + /// This method allows the `Deserializer` to avoid a copy by retaining + /// ownership of any buffered data. `Deserialize` implementations that do + /// not benefit from taking ownership of `Vec` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_bytes` rather + /// than `Deserializer::deserialize_byte_buf`. + /// + /// It is never correct to implement `visit_byte_buf` without implementing + /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Bytes(v), &self)) + } + + /// The input contains a byte array that lives at least as long as the + /// `Deserializer`. + /// + /// This enables zero-copy deserialization of bytes in some formats. For + /// example Postcard data containing bytes can be deserialized with zero + /// copying into a `&'a [u8]` as long as the input data outlives `'a`. + /// + /// The default implementation forwards to `visit_bytes`. + #[inline] + fn visit_borrowed_bytes(self, v: &'de [u8]) -> Result + where + E: Error, + { + self.visit_bytes(v) + } + + /// The input contains a byte array and ownership of the byte array is being + /// given to the `Visitor`. + /// + /// This method allows the `Visitor` to avoid a copy by taking ownership of + /// a byte buffer created by the `Deserializer`. `Deserialize` + /// implementations that benefit from taking ownership of `Vec` data + /// should indicate that to the deserializer by using + /// `Deserializer::deserialize_byte_buf` rather than + /// `Deserializer::deserialize_bytes`, although not every deserializer will + /// honor such a request. + /// + /// It is never correct to implement `visit_byte_buf` without implementing + /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. + /// + /// The default implementation forwards to `visit_bytes` and then drops the + /// `Vec`. + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + self.visit_bytes(&v) + } + + /// The input contains an optional that is absent. + /// + /// The default implementation fails with a type error. + fn visit_none(self) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Option, &self)) + } + + /// The input contains an optional that is present. + /// + /// The default implementation fails with a type error. + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let _ = deserializer; + Err(Error::invalid_type(Unexpected::Option, &self)) + } + + /// The input contains a unit `()`. + /// + /// The default implementation fails with a type error. + fn visit_unit(self) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Unit, &self)) + } + + /// The input contains a newtype struct. + /// + /// The content of the newtype struct may be read from the given + /// `Deserializer`. + /// + /// The default implementation fails with a type error. + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let _ = deserializer; + Err(Error::invalid_type(Unexpected::NewtypeStruct, &self)) + } + + /// The input contains a sequence of elements. + /// + /// The default implementation fails with a type error. + fn visit_seq(self, seq: A) -> Result + where + A: SeqAccess<'de>, + { + let _ = seq; + Err(Error::invalid_type(Unexpected::Seq, &self)) + } + + /// The input contains a key-value map. + /// + /// The default implementation fails with a type error. + fn visit_map(self, map: A) -> Result + where + A: MapAccess<'de>, + { + let _ = map; + Err(Error::invalid_type(Unexpected::Map, &self)) + } + + /// The input contains an enum. + /// + /// The default implementation fails with a type error. + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + let _ = data; + Err(Error::invalid_type(Unexpected::Enum, &self)) + } + + // Used when deserializing a flattened Option field. Not public API. + #[doc(hidden)] + fn __private_visit_untagged_option(self, _: D) -> Result + where + D: Deserializer<'de>, + { + Err(()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Provides a `Visitor` access to each element of a sequence in the input. +/// +/// This is a trait that a `Deserializer` passes to a `Visitor` implementation, +/// which deserializes each item in a sequence. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by deserialized sequence elements. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SeqAccess` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::SeqAccess<'de>` is not satisfied", + ) +)] +pub trait SeqAccess<'de> { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// This returns `Ok(Some(value))` for the next value in the sequence, or + /// `Ok(None)` if there are no more remaining items. + /// + /// `Deserialize` implementations should typically use + /// `SeqAccess::next_element` instead. + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>; + + /// This returns `Ok(Some(value))` for the next value in the sequence, or + /// `Ok(None)` if there are no more remaining items. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `SeqAccess` implementations should not override the default behavior. + #[inline] + fn next_element(&mut self) -> Result, Self::Error> + where + T: Deserialize<'de>, + { + self.next_element_seed(PhantomData) + } + + /// Returns the number of elements remaining in the sequence, if known. + #[inline] + fn size_hint(&self) -> Option { + None + } +} + +impl<'de, A> SeqAccess<'de> for &mut A +where + A: ?Sized + SeqAccess<'de>, +{ + type Error = A::Error; + + #[inline] + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>, + { + (**self).next_element_seed(seed) + } + + #[inline] + fn next_element(&mut self) -> Result, Self::Error> + where + T: Deserialize<'de>, + { + (**self).next_element() + } + + #[inline] + fn size_hint(&self) -> Option { + (**self).size_hint() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Provides a `Visitor` access to each entry of a map in the input. +/// +/// This is a trait that a `Deserializer` passes to a `Visitor` implementation. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by deserialized map entries. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `MapAccess` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::MapAccess<'de>` is not satisfied", + ) +)] +pub trait MapAccess<'de> { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` + /// if there are no more remaining entries. + /// + /// `Deserialize` implementations should typically use + /// `MapAccess::next_key` or `MapAccess::next_entry` instead. + fn next_key_seed(&mut self, seed: K) -> Result, Self::Error> + where + K: DeserializeSeed<'de>; + + /// This returns a `Ok(value)` for the next value in the map. + /// + /// `Deserialize` implementations should typically use + /// `MapAccess::next_value` instead. + /// + /// # Panics + /// + /// Calling `next_value_seed` before `next_key_seed` is incorrect and is + /// allowed to panic or return bogus results. + fn next_value_seed(&mut self, seed: V) -> Result + where + V: DeserializeSeed<'de>; + + /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in + /// the map, or `Ok(None)` if there are no more remaining items. + /// + /// `MapAccess` implementations should override the default behavior if a + /// more efficient implementation is possible. + /// + /// `Deserialize` implementations should typically use + /// `MapAccess::next_entry` instead. + #[inline] + fn next_entry_seed( + &mut self, + kseed: K, + vseed: V, + ) -> Result, Self::Error> + where + K: DeserializeSeed<'de>, + V: DeserializeSeed<'de>, + { + match tri!(self.next_key_seed(kseed)) { + Some(key) => { + let value = tri!(self.next_value_seed(vseed)); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` + /// if there are no more remaining entries. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapAccess` implementations should not override the default behavior. + #[inline] + fn next_key(&mut self) -> Result, Self::Error> + where + K: Deserialize<'de>, + { + self.next_key_seed(PhantomData) + } + + /// This returns a `Ok(value)` for the next value in the map. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapAccess` implementations should not override the default behavior. + /// + /// # Panics + /// + /// Calling `next_value` before `next_key` is incorrect and is allowed to + /// panic or return bogus results. + #[inline] + fn next_value(&mut self) -> Result + where + V: Deserialize<'de>, + { + self.next_value_seed(PhantomData) + } + + /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in + /// the map, or `Ok(None)` if there are no more remaining items. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapAccess` implementations should not override the default behavior. + #[inline] + fn next_entry(&mut self) -> Result, Self::Error> + where + K: Deserialize<'de>, + V: Deserialize<'de>, + { + self.next_entry_seed(PhantomData, PhantomData) + } + + /// Returns the number of entries remaining in the map, if known. + #[inline] + fn size_hint(&self) -> Option { + None + } +} + +impl<'de, A> MapAccess<'de> for &mut A +where + A: ?Sized + MapAccess<'de>, +{ + type Error = A::Error; + + #[inline] + fn next_key_seed(&mut self, seed: K) -> Result, Self::Error> + where + K: DeserializeSeed<'de>, + { + (**self).next_key_seed(seed) + } + + #[inline] + fn next_value_seed(&mut self, seed: V) -> Result + where + V: DeserializeSeed<'de>, + { + (**self).next_value_seed(seed) + } + + #[inline] + fn next_entry_seed( + &mut self, + kseed: K, + vseed: V, + ) -> Result, Self::Error> + where + K: DeserializeSeed<'de>, + V: DeserializeSeed<'de>, + { + (**self).next_entry_seed(kseed, vseed) + } + + #[inline] + fn next_entry(&mut self) -> Result, Self::Error> + where + K: Deserialize<'de>, + V: Deserialize<'de>, + { + (**self).next_entry() + } + + #[inline] + fn next_key(&mut self) -> Result, Self::Error> + where + K: Deserialize<'de>, + { + (**self).next_key() + } + + #[inline] + fn next_value(&mut self) -> Result + where + V: Deserialize<'de>, + { + (**self).next_value() + } + + #[inline] + fn size_hint(&self) -> Option { + (**self).size_hint() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Provides a `Visitor` access to the data of an enum in the input. +/// +/// `EnumAccess` is created by the `Deserializer` and passed to the +/// `Visitor` in order to identify which variant of an enum to deserialize. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by the deserialized enum variant. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `EnumAccess` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::EnumAccess<'de>` is not satisfied", + ) +)] +pub trait EnumAccess<'de>: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + /// The `Visitor` that will be used to deserialize the content of the enum + /// variant. + type Variant: VariantAccess<'de, Error = Self::Error>; + + /// `variant` is called to identify which variant to deserialize. + /// + /// `Deserialize` implementations should typically use `EnumAccess::variant` + /// instead. + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where + V: DeserializeSeed<'de>; + + /// `variant` is called to identify which variant to deserialize. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `EnumAccess` implementations should not override the default behavior. + #[inline] + fn variant(self) -> Result<(V, Self::Variant), Self::Error> + where + V: Deserialize<'de>, + { + self.variant_seed(PhantomData) + } +} + +/// `VariantAccess` is a visitor that is created by the `Deserializer` and +/// passed to the `Deserialize` to deserialize the content of a particular enum +/// variant. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by the deserialized enum variant. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `VariantAccess` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::de::VariantAccess<'de>` is not satisfied", + ) +)] +pub trait VariantAccess<'de>: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. Must match the error type of our `EnumAccess`. + type Error: Error; + + /// Called when deserializing a variant with no values. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```edition2021 + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// fn unit_variant(self) -> Result<(), Self::Error> { + /// // What the data actually contained; suppose it is a tuple variant. + /// let unexp = Unexpected::TupleVariant; + /// Err(de::Error::invalid_type(unexp, &"unit variant")) + /// } + /// # + /// # fn newtype_variant_seed(self, _: T) -> Result + /// # where + /// # T: DeserializeSeed<'de>, + /// # { unimplemented!() } + /// # + /// # fn tuple_variant(self, _: usize, _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # + /// # fn struct_variant(self, _: &[&str], _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # } + /// ``` + fn unit_variant(self) -> Result<(), Self::Error>; + + /// Called when deserializing a variant with a single value. + /// + /// `Deserialize` implementations should typically use + /// `VariantAccess::newtype_variant` instead. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```edition2021 + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// # fn unit_variant(self) -> Result<(), Self::Error> { + /// # unimplemented!() + /// # } + /// # + /// fn newtype_variant_seed(self, _seed: T) -> Result + /// where + /// T: DeserializeSeed<'de>, + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"newtype variant")) + /// } + /// # + /// # fn tuple_variant(self, _: usize, _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # + /// # fn struct_variant(self, _: &[&str], _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # } + /// ``` + fn newtype_variant_seed(self, seed: T) -> Result + where + T: DeserializeSeed<'de>; + + /// Called when deserializing a variant with a single value. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `VariantAccess` implementations should not override the default + /// behavior. + #[inline] + fn newtype_variant(self) -> Result + where + T: Deserialize<'de>, + { + self.newtype_variant_seed(PhantomData) + } + + /// Called when deserializing a tuple-like variant. + /// + /// The `len` is the number of fields expected in the tuple variant. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```edition2021 + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// # fn unit_variant(self) -> Result<(), Self::Error> { + /// # unimplemented!() + /// # } + /// # + /// # fn newtype_variant_seed(self, _: T) -> Result + /// # where + /// # T: DeserializeSeed<'de>, + /// # { unimplemented!() } + /// # + /// fn tuple_variant(self, _len: usize, _visitor: V) -> Result + /// where + /// V: Visitor<'de>, + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"tuple variant")) + /// } + /// # + /// # fn struct_variant(self, _: &[&str], _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # } + /// ``` + fn tuple_variant(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Called when deserializing a struct-like variant. + /// + /// The `fields` are the names of the fields of the struct variant. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```edition2021 + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// # fn unit_variant(self) -> Result<(), Self::Error> { + /// # unimplemented!() + /// # } + /// # + /// # fn newtype_variant_seed(self, _: T) -> Result + /// # where + /// # T: DeserializeSeed<'de>, + /// # { unimplemented!() } + /// # + /// # fn tuple_variant(self, _: usize, _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # + /// fn struct_variant( + /// self, + /// _fields: &'static [&'static str], + /// _visitor: V, + /// ) -> Result + /// where + /// V: Visitor<'de>, + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"struct variant")) + /// } + /// # } + /// ``` + fn struct_variant( + self, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Converts an existing value into a `Deserializer` from which other values can +/// be deserialized. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed from the resulting `Deserializer`. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example +/// +/// ```edition2021 +/// use serde::de::{value, Deserialize, IntoDeserializer}; +/// use serde_derive::Deserialize; +/// use std::str::FromStr; +/// +/// #[derive(Deserialize)] +/// enum Setting { +/// On, +/// Off, +/// } +/// +/// impl FromStr for Setting { +/// type Err = value::Error; +/// +/// fn from_str(s: &str) -> Result { +/// Self::deserialize(s.into_deserializer()) +/// } +/// } +/// ``` +pub trait IntoDeserializer<'de, E: Error = value::Error> { + /// The type of the deserializer being converted into. + type Deserializer: Deserializer<'de, Error = E>; + + /// Convert this value into a deserializer. + fn into_deserializer(self) -> Self::Deserializer; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Used in error messages. +/// +/// - expected `a` +/// - expected `a` or `b` +/// - expected one of `a`, `b`, `c` +/// +/// The slice of names must not be empty. +struct OneOf { + names: &'static [&'static str], +} + +impl Display for OneOf { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self.names.len() { + 0 => panic!(), // special case elsewhere + 1 => write!(formatter, "`{}`", self.names[0]), + 2 => write!(formatter, "`{}` or `{}`", self.names[0], self.names[1]), + _ => { + tri!(formatter.write_str("one of ")); + for (i, alt) in self.names.iter().enumerate() { + if i > 0 { + tri!(formatter.write_str(", ")); + } + tri!(write!(formatter, "`{}`", alt)); + } + Ok(()) + } + } + } +} + +struct WithDecimalPoint(f64); + +impl Display for WithDecimalPoint { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + struct LookForDecimalPoint<'f, 'a> { + formatter: &'f mut fmt::Formatter<'a>, + has_decimal_point: bool, + } + + impl<'f, 'a> fmt::Write for LookForDecimalPoint<'f, 'a> { + fn write_str(&mut self, fragment: &str) -> fmt::Result { + self.has_decimal_point |= fragment.contains('.'); + self.formatter.write_str(fragment) + } + + fn write_char(&mut self, ch: char) -> fmt::Result { + self.has_decimal_point |= ch == '.'; + self.formatter.write_char(ch) + } + } + + if self.0.is_finite() { + let mut writer = LookForDecimalPoint { + formatter, + has_decimal_point: false, + }; + tri!(write!(writer, "{}", self.0)); + if !writer.has_decimal_point { + tri!(formatter.write_str(".0")); + } + } else { + tri!(write!(formatter, "{}", self.0)); + } + Ok(()) + } +} diff --git a/pkg/installer/vendor/serde_core/src/de/value.rs b/pkg/installer/vendor/serde_core/src/de/value.rs new file mode 100644 index 00000000000..3d5475def12 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/de/value.rs @@ -0,0 +1,1895 @@ +//! Building blocks for deserializing basic values using the `IntoDeserializer` +//! trait. +//! +//! ```edition2021 +//! use serde::de::{value, Deserialize, IntoDeserializer}; +//! use serde_derive::Deserialize; +//! use std::str::FromStr; +//! +//! #[derive(Deserialize)] +//! enum Setting { +//! On, +//! Off, +//! } +//! +//! impl FromStr for Setting { +//! type Err = value::Error; +//! +//! fn from_str(s: &str) -> Result { +//! Self::deserialize(s.into_deserializer()) +//! } +//! } +//! ``` + +use crate::lib::*; + +use self::private::{First, Second}; +use crate::de::{self, Deserializer, Expected, IntoDeserializer, SeqAccess, Visitor}; +use crate::private::size_hint; +use crate::ser; + +//////////////////////////////////////////////////////////////////////////////// + +// For structs that contain a PhantomData. We do not want the trait +// bound `E: Clone` inferred by derive(Clone). +macro_rules! impl_copy_clone { + ($ty:ident $(<$lifetime:tt>)*) => { + impl<$($lifetime,)* E> Copy for $ty<$($lifetime,)* E> {} + + impl<$($lifetime,)* E> Clone for $ty<$($lifetime,)* E> { + fn clone(&self) -> Self { + *self + } + } + }; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A minimal representation of all possible errors that can occur using the +/// `IntoDeserializer` trait. +#[derive(Clone, PartialEq)] +pub struct Error { + err: ErrorImpl, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +type ErrorImpl = Box; +#[cfg(not(any(feature = "std", feature = "alloc")))] +type ErrorImpl = (); + +impl de::Error for Error { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cold] + fn custom(msg: T) -> Self + where + T: Display, + { + Error { + err: msg.to_string().into_boxed_str(), + } + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + #[cold] + fn custom(msg: T) -> Self + where + T: Display, + { + let _ = msg; + Error { err: () } + } +} + +impl ser::Error for Error { + #[cold] + fn custom(msg: T) -> Self + where + T: Display, + { + de::Error::custom(msg) + } +} + +impl Display for Error { + #[cfg(any(feature = "std", feature = "alloc"))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(&self.err) + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("Serde deserialization error") + } +} + +impl Debug for Error { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut debug = formatter.debug_tuple("Error"); + #[cfg(any(feature = "std", feature = "alloc"))] + debug.field(&self.err); + debug.finish() + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl error::Error for Error { + fn description(&self) -> &str { + &self.err + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, E> IntoDeserializer<'de, E> for () +where + E: de::Error, +{ + type Deserializer = UnitDeserializer; + + fn into_deserializer(self) -> UnitDeserializer { + UnitDeserializer::new() + } +} + +/// A deserializer holding a `()`. +pub struct UnitDeserializer { + marker: PhantomData, +} + +impl_copy_clone!(UnitDeserializer); + +impl UnitDeserializer { + #[allow(missing_docs)] + pub fn new() -> Self { + UnitDeserializer { + marker: PhantomData, + } + } +} + +impl<'de, E> de::Deserializer<'de> for UnitDeserializer +where + E: de::Error, +{ + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_unit() + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_none() + } +} + +impl<'de, E> IntoDeserializer<'de, E> for UnitDeserializer +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl Debug for UnitDeserializer { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.debug_struct("UnitDeserializer").finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer that cannot be instantiated. +#[cfg(feature = "unstable")] +#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] +pub struct NeverDeserializer { + never: !, + marker: PhantomData, +} + +#[cfg(feature = "unstable")] +#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] +impl<'de, E> IntoDeserializer<'de, E> for ! +where + E: de::Error, +{ + type Deserializer = NeverDeserializer; + + fn into_deserializer(self) -> Self::Deserializer { + self + } +} + +#[cfg(feature = "unstable")] +impl<'de, E> de::Deserializer<'de> for NeverDeserializer +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, _visitor: V) -> Result + where + V: de::Visitor<'de>, + { + self.never + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +#[cfg(feature = "unstable")] +impl<'de, E> IntoDeserializer<'de, E> for NeverDeserializer +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! primitive_deserializer { + ($ty:ty, $doc:tt, $name:ident, $method:ident $($cast:tt)*) => { + #[doc = "A deserializer holding"] + #[doc = $doc] + pub struct $name { + value: $ty, + marker: PhantomData + } + + impl_copy_clone!($name); + + impl<'de, E> IntoDeserializer<'de, E> for $ty + where + E: de::Error, + { + type Deserializer = $name; + + fn into_deserializer(self) -> $name { + $name::new(self) + } + } + + impl $name { + #[allow(missing_docs)] + pub fn new(value: $ty) -> Self { + $name { + value, + marker: PhantomData, + } + } + } + + impl<'de, E> de::Deserializer<'de> for $name + where + E: de::Error, + { + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str + string bytes byte_buf option unit unit_struct newtype_struct seq + tuple tuple_struct map struct enum identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.$method(self.value $($cast)*) + } + } + + impl<'de, E> IntoDeserializer<'de, E> for $name + where + E: de::Error, + { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } + } + + impl Debug for $name { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct(stringify!($name)) + .field("value", &self.value) + .finish() + } + } + } +} + +primitive_deserializer!(bool, "a `bool`.", BoolDeserializer, visit_bool); +primitive_deserializer!(i8, "an `i8`.", I8Deserializer, visit_i8); +primitive_deserializer!(i16, "an `i16`.", I16Deserializer, visit_i16); +primitive_deserializer!(i32, "an `i32`.", I32Deserializer, visit_i32); +primitive_deserializer!(i64, "an `i64`.", I64Deserializer, visit_i64); +primitive_deserializer!(i128, "an `i128`.", I128Deserializer, visit_i128); +primitive_deserializer!(isize, "an `isize`.", IsizeDeserializer, visit_i64 as i64); +primitive_deserializer!(u8, "a `u8`.", U8Deserializer, visit_u8); +primitive_deserializer!(u16, "a `u16`.", U16Deserializer, visit_u16); +primitive_deserializer!(u64, "a `u64`.", U64Deserializer, visit_u64); +primitive_deserializer!(u128, "a `u128`.", U128Deserializer, visit_u128); +primitive_deserializer!(usize, "a `usize`.", UsizeDeserializer, visit_u64 as u64); +primitive_deserializer!(f32, "an `f32`.", F32Deserializer, visit_f32); +primitive_deserializer!(f64, "an `f64`.", F64Deserializer, visit_f64); +primitive_deserializer!(char, "a `char`.", CharDeserializer, visit_char); + +/// A deserializer holding a `u32`. +pub struct U32Deserializer { + value: u32, + marker: PhantomData, +} + +impl_copy_clone!(U32Deserializer); + +impl<'de, E> IntoDeserializer<'de, E> for u32 +where + E: de::Error, +{ + type Deserializer = U32Deserializer; + + fn into_deserializer(self) -> U32Deserializer { + U32Deserializer::new(self) + } +} + +impl U32Deserializer { + #[allow(missing_docs)] + pub fn new(value: u32) -> Self { + U32Deserializer { + value, + marker: PhantomData, + } + } +} + +impl<'de, E> de::Deserializer<'de> for U32Deserializer +where + E: de::Error, +{ + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_u32(self.value) + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } +} + +impl<'de, E> IntoDeserializer<'de, E> for U32Deserializer +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl<'de, E> de::EnumAccess<'de> for U32Deserializer +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +impl Debug for U32Deserializer { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("U32Deserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `&str`. +pub struct StrDeserializer<'a, E> { + value: &'a str, + marker: PhantomData, +} + +impl_copy_clone!(StrDeserializer<'de>); + +impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a str +where + E: de::Error, +{ + type Deserializer = StrDeserializer<'a, E>; + + fn into_deserializer(self) -> StrDeserializer<'a, E> { + StrDeserializer::new(self) + } +} + +impl<'a, E> StrDeserializer<'a, E> { + #[allow(missing_docs)] + pub fn new(value: &'a str) -> Self { + StrDeserializer { + value, + marker: PhantomData, + } + } +} + +impl<'de, 'a, E> de::Deserializer<'de> for StrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_str(self.value) + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +impl<'de, 'a, E> IntoDeserializer<'de, E> for StrDeserializer<'a, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl<'de, 'a, E> de::EnumAccess<'de> for StrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +impl<'a, E> Debug for StrDeserializer<'a, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("StrDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `&str` with a lifetime tied to another +/// deserializer. +pub struct BorrowedStrDeserializer<'de, E> { + value: &'de str, + marker: PhantomData, +} + +impl_copy_clone!(BorrowedStrDeserializer<'de>); + +impl<'de, E> BorrowedStrDeserializer<'de, E> { + /// Create a new borrowed deserializer from the given string. + pub fn new(value: &'de str) -> BorrowedStrDeserializer<'de, E> { + BorrowedStrDeserializer { + value, + marker: PhantomData, + } + } +} + +impl<'de, E> de::Deserializer<'de> for BorrowedStrDeserializer<'de, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_borrowed_str(self.value) + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +impl<'de, E> IntoDeserializer<'de, E> for BorrowedStrDeserializer<'de, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl<'de, E> de::EnumAccess<'de> for BorrowedStrDeserializer<'de, E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +impl<'de, E> Debug for BorrowedStrDeserializer<'de, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("BorrowedStrDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `String`. +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +pub struct StringDeserializer { + value: String, + marker: PhantomData, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl Clone for StringDeserializer { + fn clone(&self) -> Self { + StringDeserializer { + value: self.value.clone(), + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, E> IntoDeserializer<'de, E> for String +where + E: de::Error, +{ + type Deserializer = StringDeserializer; + + fn into_deserializer(self) -> StringDeserializer { + StringDeserializer::new(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl StringDeserializer { + #[allow(missing_docs)] + pub fn new(value: String) -> Self { + StringDeserializer { + value, + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, E> de::Deserializer<'de> for StringDeserializer +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_string(self.value) + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, E> IntoDeserializer<'de, E> for StringDeserializer +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, E> de::EnumAccess<'de> for StringDeserializer +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl Debug for StringDeserializer { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("StringDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `Cow`. +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +pub struct CowStrDeserializer<'a, E> { + value: Cow<'a, str>, + marker: PhantomData, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, E> Clone for CowStrDeserializer<'a, E> { + fn clone(&self) -> Self { + CowStrDeserializer { + value: self.value.clone(), + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, 'a, E> IntoDeserializer<'de, E> for Cow<'a, str> +where + E: de::Error, +{ + type Deserializer = CowStrDeserializer<'a, E>; + + fn into_deserializer(self) -> CowStrDeserializer<'a, E> { + CowStrDeserializer::new(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, E> CowStrDeserializer<'a, E> { + #[allow(missing_docs)] + pub fn new(value: Cow<'a, str>) -> Self { + CowStrDeserializer { + value, + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> de::Deserializer<'de> for CowStrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + match self.value { + Cow::Borrowed(string) => visitor.visit_str(string), + Cow::Owned(string) => visitor.visit_string(string), + } + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> IntoDeserializer<'de, E> for CowStrDeserializer<'a, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> de::EnumAccess<'de> for CowStrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, E> Debug for CowStrDeserializer<'a, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("CowStrDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `&[u8]`. Always calls [`Visitor::visit_bytes`]. +pub struct BytesDeserializer<'a, E> { + value: &'a [u8], + marker: PhantomData, +} + +impl<'a, E> BytesDeserializer<'a, E> { + /// Create a new deserializer from the given bytes. + pub fn new(value: &'a [u8]) -> Self { + BytesDeserializer { + value, + marker: PhantomData, + } + } +} + +impl_copy_clone!(BytesDeserializer<'a>); + +impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a [u8] +where + E: de::Error, +{ + type Deserializer = BytesDeserializer<'a, E>; + + fn into_deserializer(self) -> BytesDeserializer<'a, E> { + BytesDeserializer::new(self) + } +} + +impl<'de, 'a, E> Deserializer<'de> for BytesDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_bytes(self.value) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de, 'a, E> IntoDeserializer<'de, E> for BytesDeserializer<'a, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl<'a, E> Debug for BytesDeserializer<'a, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("BytesDeserializer") + .field("value", &self.value) + .finish() + } +} + +/// A deserializer holding a `&[u8]` with a lifetime tied to another +/// deserializer. Always calls [`Visitor::visit_borrowed_bytes`]. +pub struct BorrowedBytesDeserializer<'de, E> { + value: &'de [u8], + marker: PhantomData, +} + +impl<'de, E> BorrowedBytesDeserializer<'de, E> { + /// Create a new borrowed deserializer from the given borrowed bytes. + pub fn new(value: &'de [u8]) -> Self { + BorrowedBytesDeserializer { + value, + marker: PhantomData, + } + } +} + +impl_copy_clone!(BorrowedBytesDeserializer<'de>); + +impl<'de, E> Deserializer<'de> for BorrowedBytesDeserializer<'de, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_borrowed_bytes(self.value) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de, E> IntoDeserializer<'de, E> for BorrowedBytesDeserializer<'de, E> +where + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl<'de, E> Debug for BorrowedBytesDeserializer<'de, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("BorrowedBytesDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer that iterates over a sequence. +#[derive(Clone)] +pub struct SeqDeserializer { + iter: iter::Fuse, + count: usize, + marker: PhantomData, +} + +impl SeqDeserializer +where + I: Iterator, +{ + /// Construct a new `SeqDeserializer`. + pub fn new(iter: I) -> Self { + SeqDeserializer { + iter: iter.fuse(), + count: 0, + marker: PhantomData, + } + } +} + +impl SeqDeserializer +where + I: Iterator, + E: de::Error, +{ + /// Check for remaining elements after passing a `SeqDeserializer` to + /// `Visitor::visit_seq`. + pub fn end(self) -> Result<(), E> { + let remaining = self.iter.count(); + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInSeq(self.count), + )) + } + } +} + +impl<'de, I, T, E> de::Deserializer<'de> for SeqDeserializer +where + I: Iterator, + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn deserialize_any(mut self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let v = tri!(visitor.visit_seq(&mut self)); + tri!(self.end()); + Ok(v) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de, I, T, E> IntoDeserializer<'de, E> for SeqDeserializer +where + I: Iterator, + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl<'de, I, T, E> de::SeqAccess<'de> for SeqDeserializer +where + I: Iterator, + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_element_seed(&mut self, seed: V) -> Result, Self::Error> + where + V: de::DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => { + self.count += 1; + seed.deserialize(value.into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } +} + +struct ExpectedInSeq(usize); + +impl Expected for ExpectedInSeq { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + formatter.write_str("1 element in sequence") + } else { + write!(formatter, "{} elements in sequence", self.0) + } + } +} + +impl Debug for SeqDeserializer +where + I: Debug, +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("SeqDeserializer") + .field("iter", &self.iter) + .field("count", &self.count) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, T, E> IntoDeserializer<'de, E> for Vec +where + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = SeqDeserializer<::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, T, E> IntoDeserializer<'de, E> for BTreeSet +where + T: IntoDeserializer<'de, E> + Eq + Ord, + E: de::Error, +{ + type Deserializer = SeqDeserializer<::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de, T, S, E> IntoDeserializer<'de, E> for HashSet +where + T: IntoDeserializer<'de, E> + Eq + Hash, + S: BuildHasher, + E: de::Error, +{ + type Deserializer = SeqDeserializer<::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `SeqAccess`. +#[derive(Clone, Debug)] +pub struct SeqAccessDeserializer { + seq: A, +} + +impl SeqAccessDeserializer { + /// Construct a new `SeqAccessDeserializer`. + pub fn new(seq: A) -> Self { + SeqAccessDeserializer { seq } + } +} + +impl<'de, A> de::Deserializer<'de> for SeqAccessDeserializer +where + A: de::SeqAccess<'de>, +{ + type Error = A::Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_seq(self.seq) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de, A> IntoDeserializer<'de, A::Error> for SeqAccessDeserializer +where + A: de::SeqAccess<'de>, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer that iterates over a map. +pub struct MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, +{ + iter: iter::Fuse, + value: Option>, + count: usize, + lifetime: PhantomData<&'de ()>, + error: PhantomData, +} + +impl<'de, I, E> MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, +{ + /// Construct a new `MapDeserializer`. + pub fn new(iter: I) -> Self { + MapDeserializer { + iter: iter.fuse(), + value: None, + count: 0, + lifetime: PhantomData, + error: PhantomData, + } + } +} + +impl<'de, I, E> MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + E: de::Error, +{ + /// Check for remaining elements after passing a `MapDeserializer` to + /// `Visitor::visit_map`. + pub fn end(self) -> Result<(), E> { + let remaining = self.iter.count(); + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInMap(self.count), + )) + } + } +} + +impl<'de, I, E> MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, +{ + fn next_pair(&mut self) -> Option<(First, Second)> { + match self.iter.next() { + Some(kv) => { + self.count += 1; + Some(private::Pair::split(kv)) + } + None => None, + } + } +} + +impl<'de, I, E> de::Deserializer<'de> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First: IntoDeserializer<'de, E>, + Second: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn deserialize_any(mut self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let value = tri!(visitor.visit_map(&mut self)); + tri!(self.end()); + Ok(value) + } + + fn deserialize_seq(mut self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let value = tri!(visitor.visit_seq(&mut self)); + tri!(self.end()); + Ok(value) + } + + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let _ = len; + self.deserialize_seq(visitor) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct tuple_struct map + struct enum identifier ignored_any + } +} + +impl<'de, I, E> IntoDeserializer<'de, E> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First: IntoDeserializer<'de, E>, + Second: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl<'de, I, E> de::MapAccess<'de> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First: IntoDeserializer<'de, E>, + Second: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_key_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(key.into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed(&mut self, seed: T) -> Result + where + T: de::DeserializeSeed<'de>, + { + let value = self.value.take(); + // Panic because this indicates a bug in the program rather than an + // expected failure. + let value = value.expect("MapAccess::next_value called before next_key"); + seed.deserialize(value.into_deserializer()) + } + + fn next_entry_seed( + &mut self, + kseed: TK, + vseed: TV, + ) -> Result, Self::Error> + where + TK: de::DeserializeSeed<'de>, + TV: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + let key = tri!(kseed.deserialize(key.into_deserializer())); + let value = tri!(vseed.deserialize(value.into_deserializer())); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } +} + +impl<'de, I, E> de::SeqAccess<'de> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First: IntoDeserializer<'de, E>, + Second: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((k, v)) => { + let de = PairDeserializer(k, v, PhantomData); + seed.deserialize(de).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } +} + +// Cannot #[derive(Clone)] because of the bound `Second: Clone`. +impl<'de, I, E> Clone for MapDeserializer<'de, I, E> +where + I: Iterator + Clone, + I::Item: private::Pair, + Second: Clone, +{ + fn clone(&self) -> Self { + MapDeserializer { + iter: self.iter.clone(), + value: self.value.clone(), + count: self.count, + lifetime: self.lifetime, + error: self.error, + } + } +} + +impl<'de, I, E> Debug for MapDeserializer<'de, I, E> +where + I: Iterator + Debug, + I::Item: private::Pair, + Second: Debug, +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("MapDeserializer") + .field("iter", &self.iter) + .field("value", &self.value) + .field("count", &self.count) + .finish() + } +} + +// Used in the `impl SeqAccess for MapDeserializer` to visit the map as a +// sequence of pairs. +struct PairDeserializer(A, B, PhantomData); + +impl<'de, A, B, E> de::Deserializer<'de> for PairDeserializer +where + A: IntoDeserializer<'de, E>, + B: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct tuple_struct map + struct enum identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData); + let pair = tri!(visitor.visit_seq(&mut pair_visitor)); + if pair_visitor.1.is_none() { + Ok(pair) + } else { + let remaining = pair_visitor.size_hint().unwrap(); + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining))) + } + } + + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + if len == 2 { + self.deserialize_seq(visitor) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(len))) + } + } +} + +struct PairVisitor(Option, Option, PhantomData); + +impl<'de, A, B, E> de::SeqAccess<'de> for PairVisitor +where + A: IntoDeserializer<'de, E>, + B: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + if let Some(k) = self.0.take() { + seed.deserialize(k.into_deserializer()).map(Some) + } else if let Some(v) = self.1.take() { + seed.deserialize(v.into_deserializer()).map(Some) + } else { + Ok(None) + } + } + + fn size_hint(&self) -> Option { + if self.0.is_some() { + Some(2) + } else if self.1.is_some() { + Some(1) + } else { + Some(0) + } + } +} + +struct ExpectedInMap(usize); + +impl Expected for ExpectedInMap { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + formatter.write_str("1 element in map") + } else { + write!(formatter, "{} elements in map", self.0) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, K, V, E> IntoDeserializer<'de, E> for BTreeMap +where + K: IntoDeserializer<'de, E> + Eq + Ord, + V: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = MapDeserializer<'de, ::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + MapDeserializer::new(self.into_iter()) + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de, K, V, S, E> IntoDeserializer<'de, E> for HashMap +where + K: IntoDeserializer<'de, E> + Eq + Hash, + V: IntoDeserializer<'de, E>, + S: BuildHasher, + E: de::Error, +{ + type Deserializer = MapDeserializer<'de, ::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + MapDeserializer::new(self.into_iter()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `MapAccess`. +#[derive(Clone, Debug)] +pub struct MapAccessDeserializer { + map: A, +} + +impl MapAccessDeserializer { + /// Construct a new `MapAccessDeserializer`. + pub fn new(map: A) -> Self { + MapAccessDeserializer { map } + } +} + +impl<'de, A> de::Deserializer<'de> for MapAccessDeserializer +where + A: de::MapAccess<'de>, +{ + type Error = A::Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_map(self.map) + } + + fn deserialize_enum( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +impl<'de, A> IntoDeserializer<'de, A::Error> for MapAccessDeserializer +where + A: de::MapAccess<'de>, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +impl<'de, A> de::EnumAccess<'de> for MapAccessDeserializer +where + A: de::MapAccess<'de>, +{ + type Error = A::Error; + type Variant = private::MapAsEnum; + + fn variant_seed(mut self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match tri!(self.map.next_key_seed(seed)) { + Some(key) => Ok((key, private::map_as_enum(self.map))), + None => Err(de::Error::invalid_type(de::Unexpected::Map, &"enum")), + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding an `EnumAccess`. +#[derive(Clone, Debug)] +pub struct EnumAccessDeserializer { + access: A, +} + +impl EnumAccessDeserializer { + /// Construct a new `EnumAccessDeserializer`. + pub fn new(access: A) -> Self { + EnumAccessDeserializer { access } + } +} + +impl<'de, A> de::Deserializer<'de> for EnumAccessDeserializer +where + A: de::EnumAccess<'de>, +{ + type Error = A::Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_enum(self.access) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de, A> IntoDeserializer<'de, A::Error> for EnumAccessDeserializer +where + A: de::EnumAccess<'de>, +{ + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +//////////////////////////////////////////////////////////////////////////////// + +mod private { + use crate::lib::*; + + use crate::de::{ + self, DeserializeSeed, Deserializer, MapAccess, Unexpected, VariantAccess, Visitor, + }; + + pub struct UnitOnly { + marker: PhantomData, + } + + pub fn unit_only(t: T) -> (T, UnitOnly) { + ( + t, + UnitOnly { + marker: PhantomData, + }, + ) + } + + impl<'de, E> de::VariantAccess<'de> for UnitOnly + where + E: de::Error, + { + type Error = E; + + fn unit_variant(self) -> Result<(), Self::Error> { + Ok(()) + } + + fn newtype_variant_seed(self, _seed: T) -> Result + where + T: de::DeserializeSeed<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"newtype variant", + )) + } + + fn tuple_variant(self, _len: usize, _visitor: V) -> Result + where + V: de::Visitor<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"tuple variant", + )) + } + + fn struct_variant( + self, + _fields: &'static [&'static str], + _visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"struct variant", + )) + } + } + + pub struct MapAsEnum { + map: A, + } + + pub fn map_as_enum(map: A) -> MapAsEnum { + MapAsEnum { map } + } + + impl<'de, A> VariantAccess<'de> for MapAsEnum + where + A: MapAccess<'de>, + { + type Error = A::Error; + + fn unit_variant(mut self) -> Result<(), Self::Error> { + self.map.next_value() + } + + fn newtype_variant_seed(mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + self.map.next_value_seed(seed) + } + + fn tuple_variant(mut self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.map.next_value_seed(SeedTupleVariant { len, visitor }) + } + + fn struct_variant( + mut self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.map.next_value_seed(SeedStructVariant { visitor }) + } + } + + struct SeedTupleVariant { + len: usize, + visitor: V, + } + + impl<'de, V> DeserializeSeed<'de> for SeedTupleVariant + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple(self.len, self.visitor) + } + } + + struct SeedStructVariant { + visitor: V, + } + + impl<'de, V> DeserializeSeed<'de> for SeedStructVariant + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_map(self.visitor) + } + } + + /// Avoid having to restate the generic types on `MapDeserializer`. The + /// `Iterator::Item` contains enough information to figure out K and V. + pub trait Pair { + type First; + type Second; + fn split(self) -> (Self::First, Self::Second); + } + + impl Pair for (A, B) { + type First = A; + type Second = B; + fn split(self) -> (A, B) { + self + } + } + + pub type First = ::First; + pub type Second = ::Second; +} diff --git a/pkg/installer/vendor/serde_core/src/format.rs b/pkg/installer/vendor/serde_core/src/format.rs new file mode 100644 index 00000000000..9053cc0704f --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/format.rs @@ -0,0 +1,30 @@ +use crate::lib::fmt::{self, Write}; +use crate::lib::str; + +pub(super) struct Buf<'a> { + bytes: &'a mut [u8], + offset: usize, +} + +impl<'a> Buf<'a> { + pub fn new(bytes: &'a mut [u8]) -> Self { + Buf { bytes, offset: 0 } + } + + pub fn as_str(&self) -> &str { + let slice = &self.bytes[..self.offset]; + unsafe { str::from_utf8_unchecked(slice) } + } +} + +impl<'a> Write for Buf<'a> { + fn write_str(&mut self, s: &str) -> fmt::Result { + if self.offset + s.len() > self.bytes.len() { + Err(fmt::Error) + } else { + self.bytes[self.offset..self.offset + s.len()].copy_from_slice(s.as_bytes()); + self.offset += s.len(); + Ok(()) + } + } +} diff --git a/pkg/installer/vendor/serde_core/src/lib.rs b/pkg/installer/vendor/serde_core/src/lib.rs new file mode 100644 index 00000000000..58d143d79f7 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/lib.rs @@ -0,0 +1,121 @@ +//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data +//! structures efficiently and generically. +//! +//! The `serde_core` crate contains Serde's trait definitions with **no support +//! for #\[derive()\]**. +//! +//! In crates that derive an implementation of `Serialize` or `Deserialize`, you +//! must depend on the [`serde`] crate, not `serde_core`. +//! +//! [`serde`]: https://crates.io/crates/serde +//! +//! In crates that handwrite implementations of Serde traits, or only use them +//! as trait bounds, depending on `serde_core` is permitted. But `serde` +//! re-exports all of these traits and can be used for this use case too. If in +//! doubt, disregard `serde_core` and always use `serde`. +//! +//! Crates that depend on `serde_core` instead of `serde` are able to compile in +//! parallel with `serde_derive` even when `serde`'s "derive" feature is turned on, +//! as shown in the following build timings. +//! +//!
+//! +//! +//! +//! +//!
When serde_json depends on serde
+//! +//!
+//! +//! +//! +//! +//!
When serde_json depends on serde_core
+ +//////////////////////////////////////////////////////////////////////////////// + +// Serde types in rustdoc of other crates get linked to here. +#![doc(html_root_url = "https://docs.rs/serde_core/1.0.228")] +// Support using Serde without the standard library! +#![cfg_attr(not(feature = "std"), no_std)] +// Show which crate feature enables conditionally compiled APIs in documentation. +#![cfg_attr(docsrs, feature(doc_cfg, rustdoc_internals))] +#![cfg_attr(docsrs, allow(internal_features))] +// Unstable functionality only if the user asks for it. For tracking and +// discussion of these features please refer to this issue: +// +// https://github.com/serde-rs/serde/issues/812 +#![cfg_attr(feature = "unstable", feature(never_type))] +#![allow(unknown_lints, bare_trait_objects, deprecated)] +// Ignored clippy and clippy_pedantic lints +#![allow( + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704 + clippy::unnested_or_patterns, + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7768 + clippy::semicolon_if_nothing_returned, + // not available in our oldest supported compiler + clippy::empty_enum, + clippy::type_repetition_in_bounds, // https://github.com/rust-lang/rust-clippy/issues/8772 + // integer and float ser/de requires these sorts of casts + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_precision_loss, + clippy::cast_sign_loss, + // things are often more readable this way + clippy::cast_lossless, + clippy::module_name_repetitions, + clippy::single_match_else, + clippy::type_complexity, + clippy::use_self, + clippy::zero_prefixed_literal, + // correctly used + clippy::derive_partial_eq_without_eq, + clippy::enum_glob_use, + clippy::explicit_auto_deref, + clippy::incompatible_msrv, + clippy::let_underscore_untyped, + clippy::map_err_ignore, + clippy::new_without_default, + clippy::result_unit_err, + clippy::wildcard_imports, + // not practical + clippy::needless_pass_by_value, + clippy::similar_names, + clippy::too_many_lines, + // preference + clippy::doc_markdown, + clippy::elidable_lifetime_names, + clippy::needless_lifetimes, + clippy::unseparated_literal_suffix, + // false positive + clippy::needless_doctest_main, + // noisy + clippy::missing_errors_doc, + clippy::must_use_candidate, +)] +// Restrictions +#![deny(clippy::question_mark_used)] +// Rustc lints. +#![deny(missing_docs, unused_imports)] + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "alloc")] +extern crate alloc; + +#[macro_use] +mod crate_root; +#[macro_use] +mod macros; + +crate_root!(); + +#[macro_export] +#[doc(hidden)] +macro_rules! __require_serde_not_serde_core { + () => { + ::core::compile_error!( + "Serde derive requires a dependency on the serde crate, not serde_core" + ); + }; +} diff --git a/pkg/installer/vendor/serde_core/src/macros.rs b/pkg/installer/vendor/serde_core/src/macros.rs new file mode 100644 index 00000000000..b9567305005 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/macros.rs @@ -0,0 +1,230 @@ +// Super explicit first paragraph because this shows up at the top level and +// trips up people who are just looking for basic Serialize / Deserialize +// documentation. +/// Helper macro when implementing the `Deserializer` part of a new data format +/// for Serde. +/// +/// Some [`Deserializer`] implementations for self-describing formats do not +/// care what hint the [`Visitor`] gives them, they just want to blindly call +/// the [`Visitor`] method corresponding to the data they can tell is in the +/// input. This requires repetitive implementations of all the [`Deserializer`] +/// trait methods. +/// +/// ```edition2021 +/// # use serde::forward_to_deserialize_any; +/// # use serde::de::{value, Deserializer, Visitor}; +/// # +/// # struct MyDeserializer; +/// # +/// # impl<'de> Deserializer<'de> for MyDeserializer { +/// # type Error = value::Error; +/// # +/// # fn deserialize_any(self, _: V) -> Result +/// # where +/// # V: Visitor<'de>, +/// # { +/// # unimplemented!() +/// # } +/// # +/// #[inline] +/// fn deserialize_bool(self, visitor: V) -> Result +/// where +/// V: Visitor<'de>, +/// { +/// self.deserialize_any(visitor) +/// } +/// # +/// # forward_to_deserialize_any! { +/// # i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string +/// # bytes byte_buf option unit unit_struct newtype_struct seq tuple +/// # tuple_struct map struct enum identifier ignored_any +/// # } +/// # } +/// ``` +/// +/// The `forward_to_deserialize_any!` macro implements these simple forwarding +/// methods so that they forward directly to [`Deserializer::deserialize_any`]. +/// You can choose which methods to forward. +/// +/// ```edition2021 +/// # use serde::forward_to_deserialize_any; +/// # use serde::de::{value, Deserializer, Visitor}; +/// # +/// # struct MyDeserializer; +/// # +/// impl<'de> Deserializer<'de> for MyDeserializer { +/// # type Error = value::Error; +/// # +/// fn deserialize_any(self, visitor: V) -> Result +/// where +/// V: Visitor<'de>, +/// { +/// /* ... */ +/// # let _ = visitor; +/// # unimplemented!() +/// } +/// +/// forward_to_deserialize_any! { +/// bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string +/// bytes byte_buf option unit unit_struct newtype_struct seq tuple +/// tuple_struct map struct enum identifier ignored_any +/// } +/// } +/// ``` +/// +/// The macro assumes the convention that your `Deserializer` lifetime parameter +/// is called `'de` and that the `Visitor` type parameters on each method are +/// called `V`. A different type parameter and a different lifetime can be +/// specified explicitly if necessary. +/// +/// ```edition2021 +/// # use serde::forward_to_deserialize_any; +/// # use serde::de::{value, Deserializer, Visitor}; +/// # use std::marker::PhantomData; +/// # +/// # struct MyDeserializer(PhantomData); +/// # +/// # impl<'q, V> Deserializer<'q> for MyDeserializer { +/// # type Error = value::Error; +/// # +/// # fn deserialize_any(self, visitor: W) -> Result +/// # where +/// # W: Visitor<'q>, +/// # { +/// # unimplemented!() +/// # } +/// # +/// forward_to_deserialize_any! { +/// > +/// bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string +/// bytes byte_buf option unit unit_struct newtype_struct seq tuple +/// tuple_struct map struct enum identifier ignored_any +/// } +/// # } +/// ``` +/// +/// [`Deserializer`]: crate::Deserializer +/// [`Visitor`]: crate::de::Visitor +/// [`Deserializer::deserialize_any`]: crate::Deserializer::deserialize_any +#[macro_export(local_inner_macros)] +macro_rules! forward_to_deserialize_any { + (<$visitor:ident: Visitor<$lifetime:tt>> $($func:ident)*) => { + $(forward_to_deserialize_any_helper!{$func<$lifetime, $visitor>})* + }; + // This case must be after the previous one. + ($($func:ident)*) => { + $(forward_to_deserialize_any_helper!{$func<'de, V>})* + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! forward_to_deserialize_any_method { + ($func:ident<$l:tt, $v:ident>($($arg:ident : $ty:ty),*)) => { + #[inline] + fn $func<$v>(self, $($arg: $ty,)* visitor: $v) -> $crate::__private::Result<$v::Value, >::Error> + where + $v: $crate::de::Visitor<$l>, + { + $( + let _ = $arg; + )* + self.deserialize_any(visitor) + } + }; +} + +#[doc(hidden)] +#[macro_export(local_inner_macros)] +macro_rules! forward_to_deserialize_any_helper { + (bool<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_bool<$l, $v>()} + }; + (i8<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i8<$l, $v>()} + }; + (i16<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i16<$l, $v>()} + }; + (i32<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i32<$l, $v>()} + }; + (i64<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i64<$l, $v>()} + }; + (i128<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i128<$l, $v>()} + }; + (u8<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u8<$l, $v>()} + }; + (u16<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u16<$l, $v>()} + }; + (u32<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u32<$l, $v>()} + }; + (u64<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u64<$l, $v>()} + }; + (u128<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u128<$l, $v>()} + }; + (f32<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_f32<$l, $v>()} + }; + (f64<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_f64<$l, $v>()} + }; + (char<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_char<$l, $v>()} + }; + (str<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_str<$l, $v>()} + }; + (string<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_string<$l, $v>()} + }; + (bytes<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_bytes<$l, $v>()} + }; + (byte_buf<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_byte_buf<$l, $v>()} + }; + (option<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_option<$l, $v>()} + }; + (unit<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_unit<$l, $v>()} + }; + (unit_struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_unit_struct<$l, $v>(name: &'static str)} + }; + (newtype_struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_newtype_struct<$l, $v>(name: &'static str)} + }; + (seq<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_seq<$l, $v>()} + }; + (tuple<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_tuple<$l, $v>(len: usize)} + }; + (tuple_struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_tuple_struct<$l, $v>(name: &'static str, len: usize)} + }; + (map<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_map<$l, $v>()} + }; + (struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_struct<$l, $v>(name: &'static str, fields: &'static [&'static str])} + }; + (enum<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_enum<$l, $v>(name: &'static str, variants: &'static [&'static str])} + }; + (identifier<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_identifier<$l, $v>()} + }; + (ignored_any<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_ignored_any<$l, $v>()} + }; +} diff --git a/pkg/installer/vendor/serde_core/src/private/content.rs b/pkg/installer/vendor/serde_core/src/private/content.rs new file mode 100644 index 00000000000..f29a9b527d6 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/private/content.rs @@ -0,0 +1,39 @@ +use crate::lib::*; + +// Used from generated code to buffer the contents of the Deserializer when +// deserializing untagged enums and internally tagged enums. +// +// Not public API. Use serde-value instead. +// +// Obsoleted by format-specific buffer types (https://github.com/serde-rs/serde/pull/2912). +#[doc(hidden)] +pub enum Content<'de> { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Str(&'de str), + ByteBuf(Vec), + Bytes(&'de [u8]), + + None, + Some(Box>), + + Unit, + Newtype(Box>), + Seq(Vec>), + Map(Vec<(Content<'de>, Content<'de>)>), +} diff --git a/pkg/installer/vendor/serde_core/src/private/doc.rs b/pkg/installer/vendor/serde_core/src/private/doc.rs new file mode 100644 index 00000000000..2cc07f0d931 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/private/doc.rs @@ -0,0 +1,165 @@ +// Used only by Serde doc tests. Not public API. + +use crate::lib::*; + +use crate::ser; + +#[doc(hidden)] +#[derive(Debug)] +pub struct Error; + +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] +impl ser::Error for Error { + fn custom(_: T) -> Self + where + T: Display, + { + unimplemented!() + } +} + +#[cfg(feature = "std")] +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] +impl error::Error for Error { + fn description(&self) -> &str { + unimplemented!() + } +} + +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] +impl Display for Error { + fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __private_serialize { + () => { + trait Serialize { + fn serialize(&self, serializer: S) -> Result + where + S: $crate::Serializer; + } + }; +} + +#[doc(hidden)] +#[macro_export(local_inner_macros)] +macro_rules! __serialize_unimplemented { + ($($func:ident)*) => { + $( + __serialize_unimplemented_helper!($func); + )* + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __serialize_unimplemented_method { + ($func:ident $(<$t:ident>)* ($($arg:ty),*) -> $ret:ident) => { + fn $func $(<$t>)* (self $(, _: $arg)*) -> $crate::__private::Result + where + $($t: ?Sized + $crate::Serialize,)* + { + unimplemented!() + } + }; +} + +#[doc(hidden)] +#[macro_export(local_inner_macros)] +macro_rules! __serialize_unimplemented_helper { + (bool) => { + __serialize_unimplemented_method!(serialize_bool(bool) -> Ok); + }; + (i8) => { + __serialize_unimplemented_method!(serialize_i8(i8) -> Ok); + }; + (i16) => { + __serialize_unimplemented_method!(serialize_i16(i16) -> Ok); + }; + (i32) => { + __serialize_unimplemented_method!(serialize_i32(i32) -> Ok); + }; + (i64) => { + __serialize_unimplemented_method!(serialize_i64(i64) -> Ok); + }; + (u8) => { + __serialize_unimplemented_method!(serialize_u8(u8) -> Ok); + }; + (u16) => { + __serialize_unimplemented_method!(serialize_u16(u16) -> Ok); + }; + (u32) => { + __serialize_unimplemented_method!(serialize_u32(u32) -> Ok); + }; + (u64) => { + __serialize_unimplemented_method!(serialize_u64(u64) -> Ok); + }; + (f32) => { + __serialize_unimplemented_method!(serialize_f32(f32) -> Ok); + }; + (f64) => { + __serialize_unimplemented_method!(serialize_f64(f64) -> Ok); + }; + (char) => { + __serialize_unimplemented_method!(serialize_char(char) -> Ok); + }; + (str) => { + __serialize_unimplemented_method!(serialize_str(&str) -> Ok); + }; + (bytes) => { + __serialize_unimplemented_method!(serialize_bytes(&[u8]) -> Ok); + }; + (none) => { + __serialize_unimplemented_method!(serialize_none() -> Ok); + }; + (some) => { + __serialize_unimplemented_method!(serialize_some(&T) -> Ok); + }; + (unit) => { + __serialize_unimplemented_method!(serialize_unit() -> Ok); + }; + (unit_struct) => { + __serialize_unimplemented_method!(serialize_unit_struct(&str) -> Ok); + }; + (unit_variant) => { + __serialize_unimplemented_method!(serialize_unit_variant(&str, u32, &str) -> Ok); + }; + (newtype_struct) => { + __serialize_unimplemented_method!(serialize_newtype_struct(&str, &T) -> Ok); + }; + (newtype_variant) => { + __serialize_unimplemented_method!(serialize_newtype_variant(&str, u32, &str, &T) -> Ok); + }; + (seq) => { + type SerializeSeq = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_seq(Option) -> SerializeSeq); + }; + (tuple) => { + type SerializeTuple = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_tuple(usize) -> SerializeTuple); + }; + (tuple_struct) => { + type SerializeTupleStruct = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_tuple_struct(&str, usize) -> SerializeTupleStruct); + }; + (tuple_variant) => { + type SerializeTupleVariant = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_tuple_variant(&str, u32, &str, usize) -> SerializeTupleVariant); + }; + (map) => { + type SerializeMap = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_map(Option) -> SerializeMap); + }; + (struct) => { + type SerializeStruct = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_struct(&str, usize) -> SerializeStruct); + }; + (struct_variant) => { + type SerializeStructVariant = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_struct_variant(&str, u32, &str, usize) -> SerializeStructVariant); + }; +} diff --git a/pkg/installer/vendor/serde_core/src/private/mod.rs b/pkg/installer/vendor/serde_core/src/private/mod.rs new file mode 100644 index 00000000000..dd5f93fe963 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/private/mod.rs @@ -0,0 +1,21 @@ +#[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))] +mod content; +mod seed; + +// FIXME: #[cfg(doctest)] once https://github.com/rust-lang/rust/issues/67295 is fixed. +#[doc(hidden)] +pub mod doc; + +#[doc(hidden)] +pub mod size_hint; + +#[doc(hidden)] +pub mod string; + +#[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))] +#[doc(hidden)] +pub use self::content::Content; +#[doc(hidden)] +pub use self::seed::InPlaceSeed; +#[doc(hidden)] +pub use crate::lib::result::Result; diff --git a/pkg/installer/vendor/serde_core/src/private/seed.rs b/pkg/installer/vendor/serde_core/src/private/seed.rs new file mode 100644 index 00000000000..bcf267cb09b --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/private/seed.rs @@ -0,0 +1,20 @@ +use crate::de::{Deserialize, DeserializeSeed, Deserializer}; + +/// A DeserializeSeed helper for implementing deserialize_in_place Visitors. +/// +/// Wraps a mutable reference and calls deserialize_in_place on it. +pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T); + +#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)] +impl<'a, 'de, T> DeserializeSeed<'de> for InPlaceSeed<'a, T> +where + T: Deserialize<'de>, +{ + type Value = (); + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::deserialize_in_place(deserializer, self.0) + } +} diff --git a/pkg/installer/vendor/serde_core/src/private/size_hint.rs b/pkg/installer/vendor/serde_core/src/private/size_hint.rs new file mode 100644 index 00000000000..783281b46c4 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/private/size_hint.rs @@ -0,0 +1,30 @@ +#[cfg(any(feature = "std", feature = "alloc"))] +use crate::lib::*; + +pub fn from_bounds(iter: &I) -> Option +where + I: Iterator, +{ + helper(iter.size_hint()) +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub fn cautious(hint: Option) -> usize { + const MAX_PREALLOC_BYTES: usize = 1024 * 1024; + + if mem::size_of::() == 0 { + 0 + } else { + cmp::min( + hint.unwrap_or(0), + MAX_PREALLOC_BYTES / mem::size_of::(), + ) + } +} + +fn helper(bounds: (usize, Option)) -> Option { + match bounds { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } +} diff --git a/pkg/installer/vendor/serde_core/src/private/string.rs b/pkg/installer/vendor/serde_core/src/private/string.rs new file mode 100644 index 00000000000..c8121a0da71 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/private/string.rs @@ -0,0 +1,23 @@ +use crate::lib::*; + +#[cfg(any(feature = "std", feature = "alloc"))] +#[doc(hidden)] +pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<'_, str> { + String::from_utf8_lossy(bytes) +} + +// The generated code calls this like: +// +// let value = &_serde::__private::from_utf8_lossy(bytes); +// Err(_serde::de::Error::unknown_variant(value, VARIANTS)) +// +// so it is okay for the return type to be different from the std case as long +// as the above works. +#[cfg(not(any(feature = "std", feature = "alloc")))] +#[doc(hidden)] +pub fn from_utf8_lossy(bytes: &[u8]) -> &str { + // Three unicode replacement characters if it fails. They look like a + // white-on-black question mark. The user will recognize it as invalid + // UTF-8. + str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}") +} diff --git a/pkg/installer/vendor/serde_core/src/ser/fmt.rs b/pkg/installer/vendor/serde_core/src/ser/fmt.rs new file mode 100644 index 00000000000..4b1549f0897 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/ser/fmt.rs @@ -0,0 +1,170 @@ +use crate::lib::*; +use crate::ser::{Error, Impossible, Serialize, Serializer}; + +impl Error for fmt::Error { + fn custom(_msg: T) -> Self { + fmt::Error + } +} + +macro_rules! fmt_primitives { + ($($f:ident: $t:ty,)*) => { + $( + fn $f(self, v: $t) -> fmt::Result { + Display::fmt(&v, self) + } + )* + }; +} + +/// ```edition2021 +/// use serde::ser::Serialize; +/// use serde_derive::Serialize; +/// use std::fmt::{self, Display}; +/// +/// #[derive(Serialize)] +/// #[serde(rename_all = "kebab-case")] +/// pub enum MessageType { +/// StartRequest, +/// EndRequest, +/// } +/// +/// impl Display for MessageType { +/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +/// self.serialize(f) +/// } +/// } +/// ``` +impl<'a> Serializer for &mut fmt::Formatter<'a> { + type Ok = (); + type Error = fmt::Error; + type SerializeSeq = Impossible<(), fmt::Error>; + type SerializeTuple = Impossible<(), fmt::Error>; + type SerializeTupleStruct = Impossible<(), fmt::Error>; + type SerializeTupleVariant = Impossible<(), fmt::Error>; + type SerializeMap = Impossible<(), fmt::Error>; + type SerializeStruct = Impossible<(), fmt::Error>; + type SerializeStructVariant = Impossible<(), fmt::Error>; + + fmt_primitives! { + serialize_bool: bool, + serialize_i8: i8, + serialize_i16: i16, + serialize_i32: i32, + serialize_i64: i64, + serialize_i128: i128, + serialize_u8: u8, + serialize_u16: u16, + serialize_u32: u32, + serialize_u64: u64, + serialize_u128: u128, + serialize_f32: f32, + serialize_f64: f64, + serialize_char: char, + serialize_str: &str, + serialize_unit_struct: &'static str, + } + + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + ) -> fmt::Result { + Display::fmt(variant, self) + } + + fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> fmt::Result + where + T: ?Sized + Serialize, + { + Serialize::serialize(value, self) + } + + fn serialize_bytes(self, _v: &[u8]) -> fmt::Result { + Err(fmt::Error) + } + + fn serialize_none(self) -> fmt::Result { + Err(fmt::Error) + } + + fn serialize_some(self, _value: &T) -> fmt::Result + where + T: ?Sized + Serialize, + { + Err(fmt::Error) + } + + fn serialize_unit(self) -> fmt::Result { + Err(fmt::Error) + } + + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T, + ) -> fmt::Result + where + T: ?Sized + Serialize, + { + Err(fmt::Error) + } + + fn serialize_seq(self, _len: Option) -> Result { + Err(fmt::Error) + } + + fn serialize_tuple(self, _len: usize) -> Result { + Err(fmt::Error) + } + + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { + Err(fmt::Error) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { + Err(fmt::Error) + } + + fn serialize_map(self, _len: Option) -> Result { + Err(fmt::Error) + } + + fn serialize_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { + Err(fmt::Error) + } + + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { + Err(fmt::Error) + } + + fn collect_str(self, value: &T) -> fmt::Result + where + T: ?Sized + Display, + { + Display::fmt(value, self) + } +} diff --git a/pkg/installer/vendor/serde_core/src/ser/impls.rs b/pkg/installer/vendor/serde_core/src/ser/impls.rs new file mode 100644 index 00000000000..a7a175db946 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/ser/impls.rs @@ -0,0 +1,1045 @@ +use crate::lib::*; + +use crate::ser::{Error, Serialize, SerializeTuple, Serializer}; + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! primitive_impl { + ($ty:ident, $method:ident $($cast:tt)*) => { + impl Serialize for $ty { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.$method(*self $($cast)*) + } + } + } +} + +primitive_impl!(bool, serialize_bool); +primitive_impl!(isize, serialize_i64 as i64); +primitive_impl!(i8, serialize_i8); +primitive_impl!(i16, serialize_i16); +primitive_impl!(i32, serialize_i32); +primitive_impl!(i64, serialize_i64); +primitive_impl!(i128, serialize_i128); +primitive_impl!(usize, serialize_u64 as u64); +primitive_impl!(u8, serialize_u8); +primitive_impl!(u16, serialize_u16); +primitive_impl!(u32, serialize_u32); +primitive_impl!(u64, serialize_u64); +primitive_impl!(u128, serialize_u128); +primitive_impl!(f32, serialize_f32); +primitive_impl!(f64, serialize_f64); +primitive_impl!(char, serialize_char); + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for str { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl Serialize for String { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(self) + } +} + +impl<'a> Serialize for fmt::Arguments<'a> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_str(self) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", not(no_core_cstr)))] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for CStr { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_bytes(self.to_bytes()) + } +} + +#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl Serialize for CString { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_bytes(self.to_bytes()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Option +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Some(ref value) => serializer.serialize_some(value), + None => serializer.serialize_none(), + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for PhantomData +where + T: ?Sized, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_struct("PhantomData") + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Does not require T: Serialize. +impl Serialize for [T; 0] { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + tri!(serializer.serialize_tuple(0)).end() + } +} + +macro_rules! array_impls { + ($($len:tt)+) => { + $( + impl Serialize for [T; $len] + where + T: Serialize, + { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut seq = tri!(serializer.serialize_tuple($len)); + for e in self { + tri!(seq.serialize_element(e)); + } + seq.end() + } + } + )+ + } +} + +array_impls! { + 01 02 03 04 05 06 07 08 09 10 + 11 12 13 14 15 16 17 18 19 20 + 21 22 23 24 25 26 27 28 29 30 + 31 32 +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for [T] +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_seq(self) + } +} + +macro_rules! seq_impl { + ( + $(#[$attr:meta])* + $ty:ident + ) => { + $(#[$attr])* + impl Serialize for $ty + where + T: Serialize, + { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_seq(self) + } + } + } +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BinaryHeap +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BTreeSet +} + +seq_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + HashSet +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + LinkedList +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + Vec +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + VecDeque +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Range +where + Idx: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("Range", 2)); + tri!(state.serialize_field("start", &self.start)); + tri!(state.serialize_field("end", &self.end)); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for RangeFrom +where + Idx: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("RangeFrom", 1)); + tri!(state.serialize_field("start", &self.start)); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for RangeInclusive +where + Idx: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("RangeInclusive", 2)); + tri!(state.serialize_field("start", &self.start())); + tri!(state.serialize_field("end", &self.end())); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for RangeTo +where + Idx: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("RangeTo", 1)); + tri!(state.serialize_field("end", &self.end)); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Bound +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Bound::Unbounded => serializer.serialize_unit_variant("Bound", 0, "Unbounded"), + Bound::Included(ref value) => { + serializer.serialize_newtype_variant("Bound", 1, "Included", value) + } + Bound::Excluded(ref value) => { + serializer.serialize_newtype_variant("Bound", 2, "Excluded", value) + } + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for () { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit() + } +} + +#[cfg(feature = "unstable")] +#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] +impl Serialize for ! { + fn serialize(&self, _serializer: S) -> Result + where + S: Serializer, + { + *self + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! tuple_impls { + ($($len:expr => ($($n:tt $name:ident)+))+) => { + $( + #[cfg_attr(docsrs, doc(hidden))] + impl<$($name),+> Serialize for ($($name,)+) + where + $($name: Serialize,)+ + { + tuple_impl_body!($len => ($($n)+)); + } + )+ + }; +} + +macro_rules! tuple_impl_body { + ($len:expr => ($($n:tt)+)) => { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut tuple = tri!(serializer.serialize_tuple($len)); + $( + tri!(tuple.serialize_element(&self.$n)); + )+ + tuple.end() + } + }; +} + +#[cfg_attr(docsrs, doc(fake_variadic))] +#[cfg_attr( + docsrs, + doc = "This trait is implemented for tuples up to 16 items long." +)] +impl Serialize for (T,) +where + T: Serialize, +{ + tuple_impl_body!(1 => (0)); +} + +tuple_impls! { + 2 => (0 T0 1 T1) + 3 => (0 T0 1 T1 2 T2) + 4 => (0 T0 1 T1 2 T2 3 T3) + 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) + 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) + 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) + 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) + 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) + 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) + 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) + 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) + 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) + 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) + 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) + 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! map_impl { + ( + $(#[$attr:meta])* + $ty:ident + ) => { + $(#[$attr])* + impl Serialize for $ty + where + K: Serialize, + V: Serialize, + { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_map(self) + } + } + } +} + +map_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BTreeMap +} + +map_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + HashMap +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! deref_impl { + ( + $(#[$attr:meta])* + <$($desc:tt)+ + ) => { + $(#[$attr])* + impl <$($desc)+ { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + (**self).serialize(serializer) + } + } + }; +} + +deref_impl! { + <'a, T> Serialize for &'a T where T: ?Sized + Serialize +} + +deref_impl! { + <'a, T> Serialize for &'a mut T where T: ?Sized + Serialize +} + +deref_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + Serialize for Box where T: ?Sized + Serialize +} + +deref_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Serializing a data structure containing `Rc` will serialize a copy of + /// the contents of the `Rc` each time the `Rc` is referenced within the + /// data structure. Serialization will not attempt to deduplicate these + /// repeated data. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))] + Serialize for Rc where T: ?Sized + Serialize +} + +deref_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Serializing a data structure containing `Arc` will serialize a copy of + /// the contents of the `Arc` each time the `Arc` is referenced within the + /// data structure. Serialization will not attempt to deduplicate these + /// repeated data. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))] + Serialize for Arc where T: ?Sized + Serialize +} + +deref_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + <'a, T> Serialize for Cow<'a, T> where T: ?Sized + Serialize + ToOwned +} + +//////////////////////////////////////////////////////////////////////////////// + +/// This impl requires the [`"rc"`] Cargo feature of Serde. +/// +/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +#[cfg_attr( + docsrs, + doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))) +)] +impl Serialize for RcWeak +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.upgrade().serialize(serializer) + } +} + +/// This impl requires the [`"rc"`] Cargo feature of Serde. +/// +/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +#[cfg_attr( + docsrs, + doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))) +)] +impl Serialize for ArcWeak +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.upgrade().serialize(serializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! nonzero_integers { + ($($T:ident,)+) => { + $( + impl Serialize for num::$T { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.get().serialize(serializer) + } + } + )+ + } +} + +nonzero_integers! { + NonZeroI8, + NonZeroI16, + NonZeroI32, + NonZeroI64, + NonZeroI128, + NonZeroIsize, + NonZeroU8, + NonZeroU16, + NonZeroU32, + NonZeroU64, + NonZeroU128, + NonZeroUsize, +} + +impl Serialize for Cell +where + T: Serialize + Copy, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.get().serialize(serializer) + } +} + +impl Serialize for RefCell +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self.try_borrow() { + Ok(value) => value.serialize(serializer), + Err(_) => Err(S::Error::custom("already mutably borrowed")), + } + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for Mutex +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self.lock() { + Ok(locked) => locked.serialize(serializer), + Err(_) => Err(S::Error::custom("lock poison error while serializing")), + } + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for RwLock +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self.read() { + Ok(locked) => locked.serialize(serializer), + Err(_) => Err(S::Error::custom("lock poison error while serializing")), + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "result")] +#[cfg_attr(docsrs, doc(cfg(feature = "result")))] +impl Serialize for Result +where + T: Serialize, + E: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Result::Ok(ref value) => serializer.serialize_newtype_variant("Result", 0, "Ok", value), + Result::Err(ref value) => { + serializer.serialize_newtype_variant("Result", 1, "Err", value) + } + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Duration { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("Duration", 2)); + tri!(state.serialize_field("secs", &self.as_secs())); + tri!(state.serialize_field("nanos", &self.subsec_nanos())); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for SystemTime { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let duration_since_epoch = match self.duration_since(UNIX_EPOCH) { + Ok(duration_since_epoch) => duration_since_epoch, + Err(_) => return Err(S::Error::custom("SystemTime must be later than UNIX_EPOCH")), + }; + let mut state = tri!(serializer.serialize_struct("SystemTime", 2)); + tri!(state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs())); + tri!(state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos())); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Serialize a value that implements `Display` as a string, when that string is +/// statically known to never have more than a constant `MAX_LEN` bytes. +/// +/// Panics if the `Display` impl tries to write more than `MAX_LEN` bytes. +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! serialize_display_bounded_length { + ($value:expr, $max:expr, $serializer:expr) => {{ + let mut buffer = [0u8; $max]; + let mut writer = crate::format::Buf::new(&mut buffer); + write!(&mut writer, "{}", $value).unwrap(); + $serializer.serialize_str(writer.as_str()) + }}; +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::IpAddr { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + match *self { + net::IpAddr::V4(ref a) => a.serialize(serializer), + net::IpAddr::V6(ref a) => a.serialize(serializer), + } + } else { + match *self { + net::IpAddr::V4(ref a) => { + serializer.serialize_newtype_variant("IpAddr", 0, "V4", a) + } + net::IpAddr::V6(ref a) => { + serializer.serialize_newtype_variant("IpAddr", 1, "V6", a) + } + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +const DEC_DIGITS_LUT: &[u8] = b"\ + 0001020304050607080910111213141516171819\ + 2021222324252627282930313233343536373839\ + 4041424344454647484950515253545556575859\ + 6061626364656667686970717273747576777879\ + 8081828384858687888990919293949596979899"; + +#[cfg(any(feature = "std", not(no_core_net)))] +#[inline] +fn format_u8(mut n: u8, out: &mut [u8]) -> usize { + if n >= 100 { + let d1 = ((n % 100) << 1) as usize; + n /= 100; + out[0] = b'0' + n; + out[1] = DEC_DIGITS_LUT[d1]; + out[2] = DEC_DIGITS_LUT[d1 + 1]; + 3 + } else if n >= 10 { + let d1 = (n << 1) as usize; + out[0] = DEC_DIGITS_LUT[d1]; + out[1] = DEC_DIGITS_LUT[d1 + 1]; + 2 + } else { + out[0] = b'0' + n; + 1 + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +#[test] +fn test_format_u8() { + let mut i = 0u8; + + loop { + let mut buf = [0u8; 3]; + let written = format_u8(i, &mut buf); + assert_eq!(i.to_string().as_bytes(), &buf[..written]); + + match i.checked_add(1) { + Some(next) => i = next, + None => break, + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::Ipv4Addr { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 15; + debug_assert_eq!(MAX_LEN, "101.102.103.104".len()); + let mut buf = [b'.'; MAX_LEN]; + let mut written = format_u8(self.octets()[0], &mut buf); + for oct in &self.octets()[1..] { + // Skip over delimiters that we initialized buf with + written += format_u8(*oct, &mut buf[written + 1..]) + 1; + } + // Safety: We've only written ASCII bytes to the buffer, so it is valid UTF-8 + let buf = unsafe { str::from_utf8_unchecked(&buf[..written]) }; + serializer.serialize_str(buf) + } else { + self.octets().serialize(serializer) + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::Ipv6Addr { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 39; + debug_assert_eq!(MAX_LEN, "1001:1002:1003:1004:1005:1006:1007:1008".len()); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + self.octets().serialize(serializer) + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::SocketAddr { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + match *self { + net::SocketAddr::V4(ref addr) => addr.serialize(serializer), + net::SocketAddr::V6(ref addr) => addr.serialize(serializer), + } + } else { + match *self { + net::SocketAddr::V4(ref addr) => { + serializer.serialize_newtype_variant("SocketAddr", 0, "V4", addr) + } + net::SocketAddr::V6(ref addr) => { + serializer.serialize_newtype_variant("SocketAddr", 1, "V6", addr) + } + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::SocketAddrV4 { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 21; + debug_assert_eq!(MAX_LEN, "101.102.103.104:65000".len()); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + (self.ip(), self.port()).serialize(serializer) + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::SocketAddrV6 { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 58; + debug_assert_eq!( + MAX_LEN, + "[1001:1002:1003:1004:1005:1006:1007:1008%4294967295]:65000".len() + ); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + (self.ip(), self.port()).serialize(serializer) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for Path { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self.to_str() { + Some(s) => s.serialize(serializer), + None => Err(Error::custom("path contains invalid UTF-8 characters")), + } + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for PathBuf { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.as_path().serialize(serializer) + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))] +impl Serialize for OsStr { + #[cfg(unix)] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use std::os::unix::ffi::OsStrExt; + serializer.serialize_newtype_variant("OsString", 0, "Unix", self.as_bytes()) + } + + #[cfg(windows)] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use std::os::windows::ffi::OsStrExt; + let val = self.encode_wide().collect::>(); + serializer.serialize_newtype_variant("OsString", 1, "Windows", &val) + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))] +impl Serialize for OsString { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.as_os_str().serialize(serializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Wrapping +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.0.serialize(serializer) + } +} + +#[cfg(not(no_core_num_saturating))] +impl Serialize for Saturating +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.0.serialize(serializer) + } +} + +impl Serialize for Reverse +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.0.serialize(serializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(all(feature = "std", not(no_std_atomic)))] +macro_rules! atomic_impl { + ($($ty:ident $size:expr)*) => { + $( + #[cfg(any(no_target_has_atomic, target_has_atomic = $size))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "std", target_has_atomic = $size))))] + impl Serialize for $ty { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + // Matches the atomic ordering used in libcore for the Debug impl + self.load(Ordering::Relaxed).serialize(serializer) + } + } + )* + } +} + +#[cfg(all(feature = "std", not(no_std_atomic)))] +atomic_impl! { + AtomicBool "8" + AtomicI8 "8" + AtomicI16 "16" + AtomicI32 "32" + AtomicIsize "ptr" + AtomicU8 "8" + AtomicU16 "16" + AtomicU32 "32" + AtomicUsize "ptr" +} + +#[cfg(all(feature = "std", not(no_std_atomic64)))] +atomic_impl! { + AtomicI64 "64" + AtomicU64 "64" +} diff --git a/pkg/installer/vendor/serde_core/src/ser/impossible.rs b/pkg/installer/vendor/serde_core/src/ser/impossible.rs new file mode 100644 index 00000000000..fe69ae24e14 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/ser/impossible.rs @@ -0,0 +1,216 @@ +//! This module contains `Impossible` serializer and its implementations. + +use crate::lib::*; + +use crate::ser::{ + self, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, + SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, +}; + +/// Helper type for implementing a `Serializer` that does not support +/// serializing one of the compound types. +/// +/// This type cannot be instantiated, but implements every one of the traits +/// corresponding to the [`Serializer`] compound types: [`SerializeSeq`], +/// [`SerializeTuple`], [`SerializeTupleStruct`], [`SerializeTupleVariant`], +/// [`SerializeMap`], [`SerializeStruct`], and [`SerializeStructVariant`]. +/// +/// ```edition2021 +/// # use serde::ser::{Serializer, Impossible}; +/// # use serde_core::__private::doc::Error; +/// # +/// # struct MySerializer; +/// # +/// impl Serializer for MySerializer { +/// type Ok = (); +/// type Error = Error; +/// +/// type SerializeSeq = Impossible<(), Error>; +/// /* other associated types */ +/// +/// /// This data format does not support serializing sequences. +/// fn serialize_seq(self, +/// len: Option) +/// -> Result { +/// // Given Impossible cannot be instantiated, the only +/// // thing we can do here is to return an error. +/// # stringify! { +/// Err(...) +/// # }; +/// # unimplemented!() +/// } +/// +/// /* other Serializer methods */ +/// # serde_core::__serialize_unimplemented! { +/// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none some +/// # unit unit_struct unit_variant newtype_struct newtype_variant +/// # tuple tuple_struct tuple_variant map struct struct_variant +/// # } +/// } +/// ``` +/// +/// [`Serializer`]: crate::Serializer +/// [`SerializeSeq`]: crate::ser::SerializeSeq +/// [`SerializeTuple`]: crate::ser::SerializeTuple +/// [`SerializeTupleStruct`]: crate::ser::SerializeTupleStruct +/// [`SerializeTupleVariant`]: crate::ser::SerializeTupleVariant +/// [`SerializeMap`]: crate::ser::SerializeMap +/// [`SerializeStruct`]: crate::ser::SerializeStruct +/// [`SerializeStructVariant`]: crate::ser::SerializeStructVariant +pub struct Impossible { + void: Void, + ok: PhantomData, + error: PhantomData, +} + +enum Void {} + +impl SerializeSeq for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_element(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeTuple for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_element(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeTupleStruct for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeTupleVariant for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeMap for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_key(&mut self, key: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = key; + match self.void {} + } + + fn serialize_value(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeStruct for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = key; + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeStructVariant for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = key; + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} diff --git a/pkg/installer/vendor/serde_core/src/ser/mod.rs b/pkg/installer/vendor/serde_core/src/ser/mod.rs new file mode 100644 index 00000000000..62e59d981d4 --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/ser/mod.rs @@ -0,0 +1,2010 @@ +//! Generic data structure serialization framework. +//! +//! The two most important traits in this module are [`Serialize`] and +//! [`Serializer`]. +//! +//! - **A type that implements `Serialize` is a data structure** that can be +//! serialized to any data format supported by Serde, and conversely +//! - **A type that implements `Serializer` is a data format** that can +//! serialize any data structure supported by Serde. +//! +//! # The Serialize trait +//! +//! Serde provides [`Serialize`] implementations for many Rust primitive and +//! standard library types. The complete list is below. All of these can be +//! serialized using Serde out of the box. +//! +//! Additionally, Serde provides a procedural macro called [`serde_derive`] to +//! automatically generate [`Serialize`] implementations for structs and enums +//! in your program. See the [derive section of the manual] for how to use this. +//! +//! In rare cases it may be necessary to implement [`Serialize`] manually for +//! some type in your program. See the [Implementing `Serialize`] section of the +//! manual for more about this. +//! +//! Third-party crates may provide [`Serialize`] implementations for types that +//! they expose. For example the [`linked-hash-map`] crate provides a +//! [`LinkedHashMap`] type that is serializable by Serde because the crate +//! provides an implementation of [`Serialize`] for it. +//! +//! # The Serializer trait +//! +//! [`Serializer`] implementations are provided by third-party crates, for +//! example [`serde_json`], [`serde_yaml`] and [`postcard`]. +//! +//! A partial list of well-maintained formats is given on the [Serde +//! website][data formats]. +//! +//! # Implementations of Serialize provided by Serde +//! +//! - **Primitive types**: +//! - bool +//! - i8, i16, i32, i64, i128, isize +//! - u8, u16, u32, u64, u128, usize +//! - f32, f64 +//! - char +//! - str +//! - &T and &mut T +//! - **Compound types**: +//! - \[T\] +//! - \[T; 0\] through \[T; 32\] +//! - tuples up to size 16 +//! - **Common standard library types**: +//! - String +//! - Option\ +//! - Result\ +//! - PhantomData\ +//! - **Wrapper types**: +//! - Box\ +//! - Cow\<'a, T\> +//! - Cell\ +//! - RefCell\ +//! - Mutex\ +//! - RwLock\ +//! - Rc\ *(if* features = \["rc"\] *is enabled)* +//! - Arc\ *(if* features = \["rc"\] *is enabled)* +//! - **Collection types**: +//! - BTreeMap\ +//! - BTreeSet\ +//! - BinaryHeap\ +//! - HashMap\ +//! - HashSet\ +//! - LinkedList\ +//! - VecDeque\ +//! - Vec\ +//! - **FFI types**: +//! - CStr +//! - CString +//! - OsStr +//! - OsString +//! - **Miscellaneous standard library types**: +//! - Duration +//! - SystemTime +//! - Path +//! - PathBuf +//! - Range\ +//! - RangeInclusive\ +//! - Bound\ +//! - num::NonZero* +//! - `!` *(unstable)* +//! - **Net types**: +//! - IpAddr +//! - Ipv4Addr +//! - Ipv6Addr +//! - SocketAddr +//! - SocketAddrV4 +//! - SocketAddrV6 +//! +//! [Implementing `Serialize`]: https://serde.rs/impl-serialize.html +//! [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +//! [`Serialize`]: crate::Serialize +//! [`Serializer`]: crate::Serializer +//! [`postcard`]: https://github.com/jamesmunns/postcard +//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map +//! [`serde_derive`]: https://crates.io/crates/serde_derive +//! [`serde_json`]: https://github.com/serde-rs/json +//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml +//! [derive section of the manual]: https://serde.rs/derive.html +//! [data formats]: https://serde.rs/#data-formats + +use crate::lib::*; + +mod fmt; +mod impls; +mod impossible; + +pub use self::impossible::Impossible; + +#[cfg(all(not(feature = "std"), no_core_error))] +#[doc(no_inline)] +pub use crate::std_error::Error as StdError; +#[cfg(not(any(feature = "std", no_core_error)))] +#[doc(no_inline)] +pub use core::error::Error as StdError; +#[cfg(feature = "std")] +#[doc(no_inline)] +pub use std::error::Error as StdError; + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! declare_error_trait { + (Error: Sized $(+ $($supertrait:ident)::+)*) => { + /// Trait used by `Serialize` implementations to generically construct + /// errors belonging to the `Serializer` against which they are + /// currently running. + /// + /// # Example implementation + /// + /// The [example data format] presented on the website shows an error + /// type appropriate for a basic JSON data format. + /// + /// [example data format]: https://serde.rs/data-format.html + #[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::Error` is not satisfied", + ) + )] + pub trait Error: Sized $(+ $($supertrait)::+)* { + /// Used when a [`Serialize`] implementation encounters any error + /// while serializing a type. + /// + /// The message should not be capitalized and should not end with a + /// period. + /// + /// For example, a filesystem [`Path`] may refuse to serialize + /// itself if it contains invalid UTF-8 data. + /// + /// ```edition2021 + /// # struct Path; + /// # + /// # impl Path { + /// # fn to_str(&self) -> Option<&str> { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::ser::{self, Serialize, Serializer}; + /// + /// impl Serialize for Path { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match self.to_str() { + /// Some(s) => serializer.serialize_str(s), + /// None => Err(ser::Error::custom("path contains invalid UTF-8 characters")), + /// } + /// } + /// } + /// ``` + /// + /// [`Path`]: std::path::Path + /// [`Serialize`]: crate::Serialize + fn custom(msg: T) -> Self + where + T: Display; + } + } +} + +#[cfg(feature = "std")] +declare_error_trait!(Error: Sized + StdError); + +#[cfg(not(feature = "std"))] +declare_error_trait!(Error: Sized + Debug + Display); + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data structure** that can be serialized into any data format supported +/// by Serde. +/// +/// Serde provides `Serialize` implementations for many Rust primitive and +/// standard library types. The complete list is [here][crate::ser]. All of +/// these can be serialized using Serde out of the box. +/// +/// Additionally, Serde provides a procedural macro called [`serde_derive`] to +/// automatically generate `Serialize` implementations for structs and enums in +/// your program. See the [derive section of the manual] for how to use this. +/// +/// In rare cases it may be necessary to implement `Serialize` manually for some +/// type in your program. See the [Implementing `Serialize`] section of the +/// manual for more about this. +/// +/// Third-party crates may provide `Serialize` implementations for types that +/// they expose. For example the [`linked-hash-map`] crate provides a +/// [`LinkedHashMap`] type that is serializable by Serde because the crate +/// provides an implementation of `Serialize` for it. +/// +/// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html +/// [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +/// [`linked-hash-map`]: https://crates.io/crates/linked-hash-map +/// [`serde_derive`]: https://crates.io/crates/serde_derive +/// [derive section of the manual]: https://serde.rs/derive.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + // Prevents `serde_core::ser::Serialize` appearing in the error message + // in projects with no direct dependency on serde_core. + message = "the trait bound `{Self}: serde::Serialize` is not satisfied", + note = "for local types consider adding `#[derive(serde::Serialize)]` to your `{Self}` type", + note = "for types from other crates check whether the crate offers a `serde` feature flag", + ) +)] +pub trait Serialize { + /// Serialize this value into the given Serde serializer. + /// + /// See the [Implementing `Serialize`] section of the manual for more + /// information about how to implement this method. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeStruct, Serializer}; + /// + /// struct Person { + /// name: String, + /// age: u8, + /// phones: Vec, + /// } + /// + /// // This is what #[derive(Serialize)] would generate. + /// impl Serialize for Person { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut s = serializer.serialize_struct("Person", 3)?; + /// s.serialize_field("name", &self.name)?; + /// s.serialize_field("age", &self.age)?; + /// s.serialize_field("phones", &self.phones)?; + /// s.end() + /// } + /// } + /// ``` + /// + /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html + fn serialize(&self, serializer: S) -> Result + where + S: Serializer; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data format** that can serialize any data structure supported by Serde. +/// +/// The role of this trait is to define the serialization half of the [Serde +/// data model], which is a way to categorize every Rust data structure into one +/// of 29 possible types. Each method of the `Serializer` trait corresponds to +/// one of the types of the data model. +/// +/// Implementations of `Serialize` map themselves into this data model by +/// invoking exactly one of the `Serializer` methods. +/// +/// The types that make up the Serde data model are: +/// +/// - **14 primitive types** +/// - bool +/// - i8, i16, i32, i64, i128 +/// - u8, u16, u32, u64, u128 +/// - f32, f64 +/// - char +/// - **string** +/// - UTF-8 bytes with a length and no null terminator. +/// - When serializing, all strings are handled equally. When deserializing, +/// there are three flavors of strings: transient, owned, and borrowed. +/// - **byte array** - \[u8\] +/// - Similar to strings, during deserialization byte arrays can be +/// transient, owned, or borrowed. +/// - **option** +/// - Either none or some value. +/// - **unit** +/// - The type of `()` in Rust. It represents an anonymous value containing +/// no data. +/// - **unit_struct** +/// - For example `struct Unit` or `PhantomData`. It represents a named +/// value containing no data. +/// - **unit_variant** +/// - For example the `E::A` and `E::B` in `enum E { A, B }`. +/// - **newtype_struct** +/// - For example `struct Millimeters(u8)`. +/// - **newtype_variant** +/// - For example the `E::N` in `enum E { N(u8) }`. +/// - **seq** +/// - A variably sized heterogeneous sequence of values, for example +/// `Vec` or `HashSet`. When serializing, the length may or may not +/// be known before iterating through all the data. When deserializing, +/// the length is determined by looking at the serialized data. +/// - **tuple** +/// - A statically sized heterogeneous sequence of values for which the +/// length will be known at deserialization time without looking at the +/// serialized data, for example `(u8,)` or `(String, u64, Vec)` or +/// `[u64; 10]`. +/// - **tuple_struct** +/// - A named tuple, for example `struct Rgb(u8, u8, u8)`. +/// - **tuple_variant** +/// - For example the `E::T` in `enum E { T(u8, u8) }`. +/// - **map** +/// - A heterogeneous key-value pairing, for example `BTreeMap`. +/// - **struct** +/// - A heterogeneous key-value pairing in which the keys are strings and +/// will be known at deserialization time without looking at the +/// serialized data, for example `struct S { r: u8, g: u8, b: u8 }`. +/// - **struct_variant** +/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. +/// +/// Many Serde serializers produce text or binary data as output, for example +/// JSON or Postcard. This is not a requirement of the `Serializer` trait, and +/// there are serializers that do not produce text or binary output. One example +/// is the `serde_json::value::Serializer` (distinct from the main `serde_json` +/// serializer) that produces a `serde_json::Value` data structure in memory as +/// output. +/// +/// [Serde data model]: https://serde.rs/data-model.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website contains example code for +/// a basic JSON `Serializer`. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::Serializer` is not satisfied", + ) +)] +pub trait Serializer: Sized { + /// The output type produced by this `Serializer` during successful + /// serialization. Most serializers that produce text or binary output + /// should set `Ok = ()` and serialize into an [`io::Write`] or buffer + /// contained within the `Serializer` instance. Serializers that build + /// in-memory data structures may be simplified by using `Ok` to propagate + /// the data structure around. + /// + /// [`io::Write`]: std::io::Write + type Ok; + + /// The error type when some error occurs during serialization. + type Error: Error; + + /// Type returned from [`serialize_seq`] for serializing the content of the + /// sequence. + /// + /// [`serialize_seq`]: #tymethod.serialize_seq + type SerializeSeq: SerializeSeq; + + /// Type returned from [`serialize_tuple`] for serializing the content of + /// the tuple. + /// + /// [`serialize_tuple`]: #tymethod.serialize_tuple + type SerializeTuple: SerializeTuple; + + /// Type returned from [`serialize_tuple_struct`] for serializing the + /// content of the tuple struct. + /// + /// [`serialize_tuple_struct`]: #tymethod.serialize_tuple_struct + type SerializeTupleStruct: SerializeTupleStruct; + + /// Type returned from [`serialize_tuple_variant`] for serializing the + /// content of the tuple variant. + /// + /// [`serialize_tuple_variant`]: #tymethod.serialize_tuple_variant + type SerializeTupleVariant: SerializeTupleVariant; + + /// Type returned from [`serialize_map`] for serializing the content of the + /// map. + /// + /// [`serialize_map`]: #tymethod.serialize_map + type SerializeMap: SerializeMap; + + /// Type returned from [`serialize_struct`] for serializing the content of + /// the struct. + /// + /// [`serialize_struct`]: #tymethod.serialize_struct + type SerializeStruct: SerializeStruct; + + /// Type returned from [`serialize_struct_variant`] for serializing the + /// content of the struct variant. + /// + /// [`serialize_struct_variant`]: #tymethod.serialize_struct_variant + type SerializeStructVariant: SerializeStructVariant; + + /// Serialize a `bool` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for bool { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_bool(*self) + /// } + /// } + /// ``` + fn serialize_bool(self, v: bool) -> Result; + + /// Serialize an `i8` value. + /// + /// If the format does not differentiate between `i8` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for i8 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i8(*self) + /// } + /// } + /// ``` + fn serialize_i8(self, v: i8) -> Result; + + /// Serialize an `i16` value. + /// + /// If the format does not differentiate between `i16` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for i16 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i16(*self) + /// } + /// } + /// ``` + fn serialize_i16(self, v: i16) -> Result; + + /// Serialize an `i32` value. + /// + /// If the format does not differentiate between `i32` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for i32 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i32(*self) + /// } + /// } + /// ``` + fn serialize_i32(self, v: i32) -> Result; + + /// Serialize an `i64` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for i64 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i64(*self) + /// } + /// } + /// ``` + fn serialize_i64(self, v: i64) -> Result; + + /// Serialize an `i128` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for i128 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i128(*self) + /// } + /// } + /// ``` + /// + /// The default behavior unconditionally returns an error. + fn serialize_i128(self, v: i128) -> Result { + let _ = v; + Err(Error::custom("i128 is not supported")) + } + + /// Serialize a `u8` value. + /// + /// If the format does not differentiate between `u8` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for u8 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u8(*self) + /// } + /// } + /// ``` + fn serialize_u8(self, v: u8) -> Result; + + /// Serialize a `u16` value. + /// + /// If the format does not differentiate between `u16` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for u16 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u16(*self) + /// } + /// } + /// ``` + fn serialize_u16(self, v: u16) -> Result; + + /// Serialize a `u32` value. + /// + /// If the format does not differentiate between `u32` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for u32 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u32(*self) + /// } + /// } + /// ``` + fn serialize_u32(self, v: u32) -> Result; + + /// Serialize a `u64` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for u64 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u64(*self) + /// } + /// } + /// ``` + fn serialize_u64(self, v: u64) -> Result; + + /// Serialize a `u128` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for u128 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u128(*self) + /// } + /// } + /// ``` + /// + /// The default behavior unconditionally returns an error. + fn serialize_u128(self, v: u128) -> Result { + let _ = v; + Err(Error::custom("u128 is not supported")) + } + + /// Serialize an `f32` value. + /// + /// If the format does not differentiate between `f32` and `f64`, a + /// reasonable implementation would be to cast the value to `f64` and + /// forward to `serialize_f64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for f32 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_f32(*self) + /// } + /// } + /// ``` + fn serialize_f32(self, v: f32) -> Result; + + /// Serialize an `f64` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for f64 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_f64(*self) + /// } + /// } + /// ``` + fn serialize_f64(self, v: f64) -> Result; + + /// Serialize a character. + /// + /// If the format does not support characters, it is reasonable to serialize + /// it as a single element `str` or a `u32`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for char { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_char(*self) + /// } + /// } + /// ``` + fn serialize_char(self, v: char) -> Result; + + /// Serialize a `&str`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for str { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_str(self) + /// } + /// } + /// ``` + fn serialize_str(self, v: &str) -> Result; + + /// Serialize a chunk of raw byte data. + /// + /// Enables serializers to serialize byte slices more compactly or more + /// efficiently than other types of slices. If no efficient implementation + /// is available, a reasonable implementation would be to forward to + /// `serialize_seq`. If forwarded, the implementation looks usually just + /// like this: + /// + /// ```edition2021 + /// # use serde::ser::{Serializer, SerializeSeq}; + /// # use serde_core::__private::doc::Error; + /// # + /// # struct MySerializer; + /// # + /// # impl Serializer for MySerializer { + /// # type Ok = (); + /// # type Error = Error; + /// # + /// fn serialize_bytes(self, v: &[u8]) -> Result { + /// let mut seq = self.serialize_seq(Some(v.len()))?; + /// for b in v { + /// seq.serialize_element(b)?; + /// } + /// seq.end() + /// } + /// # + /// # serde_core::__serialize_unimplemented! { + /// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some + /// # unit unit_struct unit_variant newtype_struct newtype_variant + /// # seq tuple tuple_struct tuple_variant map struct struct_variant + /// # } + /// # } + /// ``` + fn serialize_bytes(self, v: &[u8]) -> Result; + + /// Serialize a [`None`] value. + /// + /// ```edition2021 + /// # use serde::{Serialize, Serializer}; + /// # + /// # enum Option { + /// # Some(T), + /// # None, + /// # } + /// # + /// # use self::Option::{Some, None}; + /// # + /// impl Serialize for Option + /// where + /// T: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// Some(ref value) => serializer.serialize_some(value), + /// None => serializer.serialize_none(), + /// } + /// } + /// } + /// # + /// # fn main() {} + /// ``` + /// + /// [`None`]: core::option::Option::None + fn serialize_none(self) -> Result; + + /// Serialize a [`Some(T)`] value. + /// + /// ```edition2021 + /// # use serde::{Serialize, Serializer}; + /// # + /// # enum Option { + /// # Some(T), + /// # None, + /// # } + /// # + /// # use self::Option::{Some, None}; + /// # + /// impl Serialize for Option + /// where + /// T: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// Some(ref value) => serializer.serialize_some(value), + /// None => serializer.serialize_none(), + /// } + /// } + /// } + /// # + /// # fn main() {} + /// ``` + /// + /// [`Some(T)`]: core::option::Option::Some + fn serialize_some(self, value: &T) -> Result + where + T: ?Sized + Serialize; + + /// Serialize a `()` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde_core::__private_serialize!(); + /// # + /// impl Serialize for () { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_unit() + /// } + /// } + /// ``` + fn serialize_unit(self) -> Result; + + /// Serialize a unit struct like `struct Unit` or `PhantomData`. + /// + /// A reasonable implementation would be to forward to `serialize_unit`. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// struct Nothing; + /// + /// impl Serialize for Nothing { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_unit_struct("Nothing") + /// } + /// } + /// ``` + fn serialize_unit_struct(self, name: &'static str) -> Result; + + /// Serialize a unit variant like `E::A` in `enum E { A, B }`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, and the `variant` is the name of the + /// variant. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// enum E { + /// A, + /// B, + /// } + /// + /// impl Serialize for E { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// E::A => serializer.serialize_unit_variant("E", 0, "A"), + /// E::B => serializer.serialize_unit_variant("E", 1, "B"), + /// } + /// } + /// } + /// ``` + fn serialize_unit_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + ) -> Result; + + /// Serialize a newtype struct like `struct Millimeters(u8)`. + /// + /// Serializers are encouraged to treat newtype structs as insignificant + /// wrappers around the data they contain. A reasonable implementation would + /// be to forward to `value.serialize(self)`. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// struct Millimeters(u8); + /// + /// impl Serialize for Millimeters { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_newtype_struct("Millimeters", &self.0) + /// } + /// } + /// ``` + fn serialize_newtype_struct( + self, + name: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize; + + /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, and the `variant` is the name of the + /// variant. The `value` is the data contained within this newtype variant. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// enum E { + /// M(String), + /// N(u8), + /// } + /// + /// impl Serialize for E { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s), + /// E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n), + /// } + /// } + /// } + /// ``` + fn serialize_newtype_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize; + + /// Begin to serialize a variably sized sequence. This call must be + /// followed by zero or more calls to `serialize_element`, then a call to + /// `end`. + /// + /// The argument is the number of elements in the sequence, which may or may + /// not be computable before the sequence is iterated. Some serializers only + /// support sequences whose length is known up front. + /// + /// ```edition2021 + /// # use std::marker::PhantomData; + /// # + /// # struct Vec(PhantomData); + /// # + /// # impl Vec { + /// # fn len(&self) -> usize { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # impl<'a, T> IntoIterator for &'a Vec { + /// # type Item = &'a T; + /// # type IntoIter = Box>; + /// # + /// # fn into_iter(self) -> Self::IntoIter { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::ser::{Serialize, SerializeSeq, Serializer}; + /// + /// impl Serialize for Vec + /// where + /// T: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut seq = serializer.serialize_seq(Some(self.len()))?; + /// for element in self { + /// seq.serialize_element(element)?; + /// } + /// seq.end() + /// } + /// } + /// ``` + fn serialize_seq(self, len: Option) -> Result; + + /// Begin to serialize a statically sized sequence whose length will be + /// known at deserialization time without looking at the serialized data. + /// This call must be followed by zero or more calls to `serialize_element`, + /// then a call to `end`. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeTuple, Serializer}; + /// + /// # mod fool { + /// # trait Serialize {} + /// impl Serialize for (A, B, C) + /// # {} + /// # } + /// # + /// # struct Tuple3(A, B, C); + /// # + /// # impl Serialize for Tuple3 + /// where + /// A: Serialize, + /// B: Serialize, + /// C: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut tup = serializer.serialize_tuple(3)?; + /// tup.serialize_element(&self.0)?; + /// tup.serialize_element(&self.1)?; + /// tup.serialize_element(&self.2)?; + /// tup.end() + /// } + /// } + /// ``` + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeTuple, Serializer}; + /// + /// const VRAM_SIZE: usize = 386; + /// struct Vram([u16; VRAM_SIZE]); + /// + /// impl Serialize for Vram { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut seq = serializer.serialize_tuple(VRAM_SIZE)?; + /// for element in &self.0[..] { + /// seq.serialize_element(element)?; + /// } + /// seq.end() + /// } + /// } + /// ``` + fn serialize_tuple(self, len: usize) -> Result; + + /// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This + /// call must be followed by zero or more calls to `serialize_field`, then a + /// call to `end`. + /// + /// The `name` is the name of the tuple struct and the `len` is the number + /// of data fields that will be serialized. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; + /// + /// struct Rgb(u8, u8, u8); + /// + /// impl Serialize for Rgb { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; + /// ts.serialize_field(&self.0)?; + /// ts.serialize_field(&self.1)?; + /// ts.serialize_field(&self.2)?; + /// ts.end() + /// } + /// } + /// ``` + fn serialize_tuple_struct( + self, + name: &'static str, + len: usize, + ) -> Result; + + /// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8) + /// }`. This call must be followed by zero or more calls to + /// `serialize_field`, then a call to `end`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, the `variant` is the name of the variant, + /// and the `len` is the number of data fields that will be serialized. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer}; + /// + /// enum E { + /// T(u8, u8), + /// U(String, u32, u32), + /// } + /// + /// impl Serialize for E { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// E::T(ref a, ref b) => { + /// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; + /// tv.serialize_field(a)?; + /// tv.serialize_field(b)?; + /// tv.end() + /// } + /// E::U(ref a, ref b, ref c) => { + /// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; + /// tv.serialize_field(a)?; + /// tv.serialize_field(b)?; + /// tv.serialize_field(c)?; + /// tv.end() + /// } + /// } + /// } + /// } + /// ``` + fn serialize_tuple_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result; + + /// Begin to serialize a map. This call must be followed by zero or more + /// calls to `serialize_key` and `serialize_value`, then a call to `end`. + /// + /// The argument is the number of elements in the map, which may or may not + /// be computable before the map is iterated. Some serializers only support + /// maps whose length is known up front. + /// + /// ```edition2021 + /// # use std::marker::PhantomData; + /// # + /// # struct HashMap(PhantomData, PhantomData); + /// # + /// # impl HashMap { + /// # fn len(&self) -> usize { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # impl<'a, K, V> IntoIterator for &'a HashMap { + /// # type Item = (&'a K, &'a V); + /// # type IntoIter = Box>; + /// # + /// # fn into_iter(self) -> Self::IntoIter { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::ser::{Serialize, SerializeMap, Serializer}; + /// + /// impl Serialize for HashMap + /// where + /// K: Serialize, + /// V: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut map = serializer.serialize_map(Some(self.len()))?; + /// for (k, v) in self { + /// map.serialize_entry(k, v)?; + /// } + /// map.end() + /// } + /// } + /// ``` + fn serialize_map(self, len: Option) -> Result; + + /// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`. + /// This call must be followed by zero or more calls to `serialize_field`, + /// then a call to `end`. + /// + /// The `name` is the name of the struct and the `len` is the number of + /// data fields that will be serialized. `len` does not include fields + /// which are skipped with [`SerializeStruct::skip_field`]. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeStruct, Serializer}; + /// + /// struct Rgb { + /// r: u8, + /// g: u8, + /// b: u8, + /// } + /// + /// impl Serialize for Rgb { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut rgb = serializer.serialize_struct("Rgb", 3)?; + /// rgb.serialize_field("r", &self.r)?; + /// rgb.serialize_field("g", &self.g)?; + /// rgb.serialize_field("b", &self.b)?; + /// rgb.end() + /// } + /// } + /// ``` + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result; + + /// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8, + /// g: u8, b: u8 } }`. This call must be followed by zero or more calls to + /// `serialize_field`, then a call to `end`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, the `variant` is the name of the variant, + /// and the `len` is the number of data fields that will be serialized. + /// `len` does not include fields which are skipped with + /// [`SerializeStructVariant::skip_field`]. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeStructVariant, Serializer}; + /// + /// enum E { + /// S { r: u8, g: u8, b: u8 }, + /// } + /// + /// impl Serialize for E { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// E::S { + /// ref r, + /// ref g, + /// ref b, + /// } => { + /// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; + /// sv.serialize_field("r", r)?; + /// sv.serialize_field("g", g)?; + /// sv.serialize_field("b", b)?; + /// sv.end() + /// } + /// } + /// } + /// } + /// ``` + fn serialize_struct_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result; + + /// Collect an iterator as a sequence. + /// + /// The default implementation serializes each item yielded by the iterator + /// using [`serialize_seq`]. Implementors should not need to override this + /// method. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// struct SecretlyOneHigher { + /// data: Vec, + /// } + /// + /// impl Serialize for SecretlyOneHigher { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.collect_seq(self.data.iter().map(|x| x + 1)) + /// } + /// } + /// ``` + /// + /// [`serialize_seq`]: #tymethod.serialize_seq + fn collect_seq(self, iter: I) -> Result + where + I: IntoIterator, + ::Item: Serialize, + { + let mut iter = iter.into_iter(); + let mut serializer = tri!(self.serialize_seq(iterator_len_hint(&iter))); + tri!(iter.try_for_each(|item| serializer.serialize_element(&item))); + serializer.end() + } + + /// Collect an iterator as a map. + /// + /// The default implementation serializes each pair yielded by the iterator + /// using [`serialize_map`]. Implementors should not need to override this + /// method. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// use std::collections::BTreeSet; + /// + /// struct MapToUnit { + /// keys: BTreeSet, + /// } + /// + /// // Serializes as a map in which the values are all unit. + /// impl Serialize for MapToUnit { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.collect_map(self.keys.iter().map(|k| (k, ()))) + /// } + /// } + /// ``` + /// + /// [`serialize_map`]: #tymethod.serialize_map + fn collect_map(self, iter: I) -> Result + where + K: Serialize, + V: Serialize, + I: IntoIterator, + { + let mut iter = iter.into_iter(); + let mut serializer = tri!(self.serialize_map(iterator_len_hint(&iter))); + tri!(iter.try_for_each(|(key, value)| serializer.serialize_entry(&key, &value))); + serializer.end() + } + + /// Serialize a string produced by an implementation of `Display`. + /// + /// The default implementation builds a heap-allocated [`String`] and + /// delegates to [`serialize_str`]. Serializers are encouraged to provide a + /// more efficient implementation if possible. + /// + /// ```edition2021 + /// # struct DateTime; + /// # + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// # + /// use serde::{Serialize, Serializer}; + /// + /// impl Serialize for DateTime { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset())) + /// } + /// } + /// ``` + /// + /// [`serialize_str`]: Self::serialize_str + #[cfg(any(feature = "std", feature = "alloc"))] + fn collect_str(self, value: &T) -> Result + where + T: ?Sized + Display, + { + self.serialize_str(&value.to_string()) + } + + /// Serialize a string produced by an implementation of `Display`. + /// + /// Serializers that use `no_std` are required to provide an implementation + /// of this method. If no more sensible behavior is possible, the + /// implementation is expected to return an error. + /// + /// ```edition2021 + /// # struct DateTime; + /// # + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// # + /// use serde::{Serialize, Serializer}; + /// + /// impl Serialize for DateTime { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset())) + /// } + /// } + /// ``` + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn collect_str(self, value: &T) -> Result + where + T: ?Sized + Display; + + /// Determine whether `Serialize` implementations should serialize in + /// human-readable form. + /// + /// Some types have a human-readable form that may be somewhat expensive to + /// construct, as well as a binary form that is compact and efficient. + /// Generally text-based formats like JSON and YAML will prefer to use the + /// human-readable one and binary formats like Postcard will prefer the + /// compact one. + /// + /// ```edition2021 + /// # use std::fmt::{self, Display}; + /// # + /// # struct Timestamp; + /// # + /// # impl Timestamp { + /// # fn seconds_since_epoch(&self) -> u64 { unimplemented!() } + /// # } + /// # + /// # impl Display for Timestamp { + /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::{Serialize, Serializer}; + /// + /// impl Serialize for Timestamp { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// if serializer.is_human_readable() { + /// // Serialize to a human-readable string "2015-05-15T17:01:00Z". + /// self.to_string().serialize(serializer) + /// } else { + /// // Serialize to a compact binary representation. + /// self.seconds_since_epoch().serialize(serializer) + /// } + /// } + /// } + /// ``` + /// + /// The default implementation of this method returns `true`. Data formats + /// may override this to `false` to request a compact form for types that + /// support one. Note that modifying this method to change a format from + /// human-readable to compact or vice versa should be regarded as a breaking + /// change, as a value serialized in human-readable mode is not required to + /// deserialize from the same data in compact mode. + #[inline] + fn is_human_readable(&self) -> bool { + true + } +} + +/// Returned from `Serializer::serialize_seq`. +/// +/// # Example use +/// +/// ```edition2021 +/// # use std::marker::PhantomData; +/// # +/// # struct Vec(PhantomData); +/// # +/// # impl Vec { +/// # fn len(&self) -> usize { +/// # unimplemented!() +/// # } +/// # } +/// # +/// # impl<'a, T> IntoIterator for &'a Vec { +/// # type Item = &'a T; +/// # type IntoIter = Box>; +/// # fn into_iter(self) -> Self::IntoIter { +/// # unimplemented!() +/// # } +/// # } +/// # +/// use serde::ser::{Serialize, SerializeSeq, Serializer}; +/// +/// impl Serialize for Vec +/// where +/// T: Serialize, +/// { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut seq = serializer.serialize_seq(Some(self.len()))?; +/// for element in self { +/// seq.serialize_element(element)?; +/// } +/// seq.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeSeq` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeSeq` is not satisfied", + ) +)] +pub trait SerializeSeq { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a sequence element. + fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Finish serializing a sequence. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_tuple`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeTuple, Serializer}; +/// +/// # mod fool { +/// # trait Serialize {} +/// impl Serialize for (A, B, C) +/// # {} +/// # } +/// # +/// # struct Tuple3(A, B, C); +/// # +/// # impl Serialize for Tuple3 +/// where +/// A: Serialize, +/// B: Serialize, +/// C: Serialize, +/// { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut tup = serializer.serialize_tuple(3)?; +/// tup.serialize_element(&self.0)?; +/// tup.serialize_element(&self.1)?; +/// tup.serialize_element(&self.2)?; +/// tup.end() +/// } +/// } +/// ``` +/// +/// ```edition2021 +/// # use std::marker::PhantomData; +/// # +/// # struct Array(PhantomData); +/// # +/// # impl Array { +/// # fn len(&self) -> usize { +/// # unimplemented!() +/// # } +/// # } +/// # +/// # impl<'a, T> IntoIterator for &'a Array { +/// # type Item = &'a T; +/// # type IntoIter = Box>; +/// # fn into_iter(self) -> Self::IntoIter { +/// # unimplemented!() +/// # } +/// # } +/// # +/// use serde::ser::{Serialize, SerializeTuple, Serializer}; +/// +/// # mod fool { +/// # trait Serialize {} +/// impl Serialize for [T; 16] +/// # {} +/// # } +/// # +/// # impl Serialize for Array +/// where +/// T: Serialize, +/// { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut seq = serializer.serialize_tuple(16)?; +/// for element in self { +/// seq.serialize_element(element)?; +/// } +/// seq.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeTuple` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeTuple` is not satisfied", + ) +)] +pub trait SerializeTuple { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple element. + fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Finish serializing a tuple. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_tuple_struct`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; +/// +/// struct Rgb(u8, u8, u8); +/// +/// impl Serialize for Rgb { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; +/// ts.serialize_field(&self.0)?; +/// ts.serialize_field(&self.1)?; +/// ts.serialize_field(&self.2)?; +/// ts.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeTupleStruct` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeTupleStruct` is not satisfied", + ) +)] +pub trait SerializeTupleStruct { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple struct field. + fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Finish serializing a tuple struct. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_tuple_variant`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeTupleVariant, Serializer}; +/// +/// enum E { +/// T(u8, u8), +/// U(String, u32, u32), +/// } +/// +/// impl Serialize for E { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// match *self { +/// E::T(ref a, ref b) => { +/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; +/// tv.serialize_field(a)?; +/// tv.serialize_field(b)?; +/// tv.end() +/// } +/// E::U(ref a, ref b, ref c) => { +/// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; +/// tv.serialize_field(a)?; +/// tv.serialize_field(b)?; +/// tv.serialize_field(c)?; +/// tv.end() +/// } +/// } +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeTupleVariant` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeTupleVariant` is not satisfied", + ) +)] +pub trait SerializeTupleVariant { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple variant field. + fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Finish serializing a tuple variant. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_map`. +/// +/// # Example use +/// +/// ```edition2021 +/// # use std::marker::PhantomData; +/// # +/// # struct HashMap(PhantomData, PhantomData); +/// # +/// # impl HashMap { +/// # fn len(&self) -> usize { +/// # unimplemented!() +/// # } +/// # } +/// # +/// # impl<'a, K, V> IntoIterator for &'a HashMap { +/// # type Item = (&'a K, &'a V); +/// # type IntoIter = Box>; +/// # +/// # fn into_iter(self) -> Self::IntoIter { +/// # unimplemented!() +/// # } +/// # } +/// # +/// use serde::ser::{Serialize, SerializeMap, Serializer}; +/// +/// impl Serialize for HashMap +/// where +/// K: Serialize, +/// V: Serialize, +/// { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut map = serializer.serialize_map(Some(self.len()))?; +/// for (k, v) in self { +/// map.serialize_entry(k, v)?; +/// } +/// map.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeMap` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeMap` is not satisfied", + ) +)] +pub trait SerializeMap { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a map key. + /// + /// If possible, `Serialize` implementations are encouraged to use + /// `serialize_entry` instead as it may be implemented more efficiently in + /// some formats compared to a pair of calls to `serialize_key` and + /// `serialize_value`. + fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Serialize a map value. + /// + /// # Panics + /// + /// Calling `serialize_value` before `serialize_key` is incorrect and is + /// allowed to panic or produce bogus results. + fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Serialize a map entry consisting of a key and a value. + /// + /// Some [`Serialize`] types are not able to hold a key and value in memory + /// at the same time so `SerializeMap` implementations are required to + /// support [`serialize_key`] and [`serialize_value`] individually. The + /// `serialize_entry` method allows serializers to optimize for the case + /// where key and value are both available. [`Serialize`] implementations + /// are encouraged to use `serialize_entry` if possible. + /// + /// The default implementation delegates to [`serialize_key`] and + /// [`serialize_value`]. This is appropriate for serializers that do not + /// care about performance or are not able to optimize `serialize_entry` any + /// better than this. + /// + /// [`Serialize`]: crate::Serialize + /// [`serialize_key`]: Self::serialize_key + /// [`serialize_value`]: Self::serialize_value + fn serialize_entry(&mut self, key: &K, value: &V) -> Result<(), Self::Error> + where + K: ?Sized + Serialize, + V: ?Sized + Serialize, + { + tri!(self.serialize_key(key)); + self.serialize_value(value) + } + + /// Finish serializing a map. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_struct`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeStruct, Serializer}; +/// +/// struct Rgb { +/// r: u8, +/// g: u8, +/// b: u8, +/// } +/// +/// impl Serialize for Rgb { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut rgb = serializer.serialize_struct("Rgb", 3)?; +/// rgb.serialize_field("r", &self.r)?; +/// rgb.serialize_field("g", &self.g)?; +/// rgb.serialize_field("b", &self.b)?; +/// rgb.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeStruct` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeStruct` is not satisfied", + ) +)] +pub trait SerializeStruct { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a struct field. + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Indicate that a struct field has been skipped. + /// + /// The default implementation does nothing. + #[inline] + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + let _ = key; + Ok(()) + } + + /// Finish serializing a struct. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_struct_variant`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeStructVariant, Serializer}; +/// +/// enum E { +/// S { r: u8, g: u8, b: u8 }, +/// } +/// +/// impl Serialize for E { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// match *self { +/// E::S { +/// ref r, +/// ref g, +/// ref b, +/// } => { +/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; +/// sv.serialize_field("r", r)?; +/// sv.serialize_field("g", g)?; +/// sv.serialize_field("b", b)?; +/// sv.end() +/// } +/// } +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeStructVariant` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "the trait bound `{Self}: serde::ser::SerializeStructVariant` is not satisfied", + ) +)] +pub trait SerializeStructVariant { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a struct variant field. + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Indicate that a struct variant field has been skipped. + /// + /// The default implementation does nothing. + #[inline] + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + let _ = key; + Ok(()) + } + + /// Finish serializing a struct variant. + fn end(self) -> Result; +} + +fn iterator_len_hint(iter: &I) -> Option +where + I: Iterator, +{ + match iter.size_hint() { + (lo, Some(hi)) if lo == hi => Some(lo), + _ => None, + } +} diff --git a/pkg/installer/vendor/serde_core/src/std_error.rs b/pkg/installer/vendor/serde_core/src/std_error.rs new file mode 100644 index 00000000000..e026ace100f --- /dev/null +++ b/pkg/installer/vendor/serde_core/src/std_error.rs @@ -0,0 +1,48 @@ +use crate::lib::{Debug, Display}; + +/// Either a re-export of std::error::Error or a new identical trait, depending +/// on whether Serde's "std" feature is enabled. +/// +/// Serde's error traits [`serde::ser::Error`] and [`serde::de::Error`] require +/// [`std::error::Error`] as a supertrait, but only when Serde is built with +/// "std" enabled. Data formats that don't care about no\_std support should +/// generally provide their error types with a `std::error::Error` impl +/// directly: +/// +/// ```edition2021 +/// #[derive(Debug)] +/// struct MySerError {...} +/// +/// impl serde::ser::Error for MySerError {...} +/// +/// impl std::fmt::Display for MySerError {...} +/// +/// // We don't support no_std! +/// impl std::error::Error for MySerError {} +/// ``` +/// +/// Data formats that *do* support no\_std may either have a "std" feature of +/// their own: +/// +/// ```toml +/// [features] +/// std = ["serde/std"] +/// ``` +/// +/// ```edition2021 +/// #[cfg(feature = "std")] +/// impl std::error::Error for MySerError {} +/// ``` +/// +/// ... or else provide the std Error impl unconditionally via Serde's +/// re-export: +/// +/// ```edition2021 +/// impl serde::ser::StdError for MySerError {} +/// ``` +pub trait Error: Debug + Display { + /// The underlying cause of this error, if any. + fn source(&self) -> Option<&(dyn Error + 'static)> { + None + } +} diff --git a/pkg/installer/vendor/serde_derive/.cargo-checksum.json b/pkg/installer/vendor/serde_derive/.cargo-checksum.json index 8d96a71bf8b..5162ab5db00 100644 --- a/pkg/installer/vendor/serde_derive/.cargo-checksum.json +++ b/pkg/installer/vendor/serde_derive/.cargo-checksum.json @@ -1 +1 @@ -{"files":{".cargo_vcs_info.json":"eb79f5a3c60fab8b5f3224b7354fe9832c463adaf6193425f66ade62a180e126","Cargo.toml":"11126b13c2d5c1204be4dfab7bd35a2e8acae0f99768d55696f237b17dd98e2a","Cargo.toml.orig":"cec1eb79c66706f49404b3dfc7d1eddfb7449a96e785d9222124c0508c560b3d","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"731c044fc5f98b37a89e9049c9214267db98763309cb63146b45c029640f82a3","crates-io.md":"407d92b2932923f8708aaf31db266fd7db32e2b0afa6c569d134b680b74a1920","src/bound.rs":"6c5c20785ac95af9480f8d0de35a7e844cc36a16012f6468db148acd03cb15c2","src/de.rs":"e0a2186fb31e24b95cdfc499b1adad295bb3eac0448a41fc37f7609cadda52c7","src/dummy.rs":"9533dfee23f20d92ea75734c739022820c2787ded0d54f459feacdeb770ec912","src/fragment.rs":"6757cb4c3131d4300f093572efc273c4ab5a20e3e1efb54a311dcfa52d0bd6eb","src/internals/ast.rs":"171478e83d203193cd96f2c9c922bd240214e05fdf76add73fb7e029784bace8","src/internals/attr.rs":"8ab89c54ec7713a16767971507733f6692eff1919fe7add6911b33c40dfc45a7","src/internals/case.rs":"10c8dda2b32d8c6c6b63cf09cdc63d02375af7e95ecefe8fecb34f93b65191bb","src/internals/check.rs":"d842eb9912fd29311060b67f3bc62c438eb7b5d86093355acb4de7eee02a0ef8","src/internals/ctxt.rs":"83a4e6fbe0e439d578478883594407e03f2f340541be479bdf0b04a202633a37","src/internals/mod.rs":"ed021ca635c18132a0e5c3d90f21b7f65def0a61e946421a30200b5b9ab6ad43","src/internals/receiver.rs":"710f875da3bad3e2a7fc1df40ab6805bb5e971b6a2a04c1b643b8a0aa29e8496","src/internals/respan.rs":"899753859c58ce5f532a3ec4584796a52f13ed5a0533191e48c953ba5c1b52ff","src/internals/symbol.rs":"d619e88caa3c7a09b03014257f2b349ee922290062d9b97b4dd19d0e64532690","src/lib.rs":"344cb97f0b9f2f7f5870815964d08eb0db22aa9b147ba06ba2375bf5daf65be5","src/pretend.rs":"7facc10a5b805564dd95735ae11118ec17ca6adcc49a59764e7c920e27b9fc4a","src/ser.rs":"120588172988a1078af4a090fbe6ffc2f9ba3ac6993f9baebea17cfe5ac6e7fa","src/this.rs":"87818dc80cbb521b51938a653d09daf10aafc220bb10425948de82ad670fcb85"},"package":"6aea2634c86b0e8ef2cfdc0c340baede54ec27b1e46febd7f80dffb2aa44a00e"} \ No newline at end of file +{"files":{".cargo_vcs_info.json":"d038f5a25f55fed9c444c3467b487399424245456a006a1be7bfe43ba1151e44","Cargo.lock":"2587fa1b2a1bcdc634da77a72bce52c3cc3f9e7c75c2c12b363db625085e2135","Cargo.toml":"3de014980e9645f2e33779acd06919c9f3b717a79e10f56004918d12c4365c27","Cargo.toml.orig":"548722e43a11e723d1be4ef17867f7256543715435e7fe03ef1b62d0f8fad253","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"d40eb47c3c6e3780359df6fe40d40a35725c843df0e3b845e10ecf2a15048664","crates-io.md":"00b72e63d4f3393e28f9a219c8cb8c122013d82f0d10d6d551e239b13c5ba9e4","src/bound.rs":"eda458b2adf8d4b75eccba18621301f846e2a84a04ef2b54e7421f69574e24bc","src/de.rs":"08fc2db0db3e7263ccfb8999ecc6249e5a8c3d9d3a3b85ea3b8995e865f08c83","src/de/enum_.rs":"5a099a25034e4f9364d421a53cfb4428ea8a94fd66515c66207bf8bfb7c4db4f","src/de/enum_adjacently.rs":"3105e85ab86ece0483ac811da2dca41f8580ac59859719a6592c87bc1424d4b0","src/de/enum_externally.rs":"891e764f988cea31d63f9c7a78395ff66377c6b1b79c7339670322dd9d48993a","src/de/enum_internally.rs":"9d898dbc1c46262f695ef7ba1660b2af70de48e07bbac8f44b740326b7c5b303","src/de/enum_untagged.rs":"b66ad3cea36ee786d50270f6648f1075c1e615b5f04173b47f034a251df5220e","src/de/identifier.rs":"b653c26f4274e5c323e3f893c6f9a2b21bd5c873abdc2a801f0289a5e56a9f6c","src/de/struct_.rs":"7b26982ce59504a9bb5a18c3ab56eee2d75e70fd465774ff035d15c50452c118","src/de/tuple.rs":"5496ee711b935b17269960f4a0cfcb7d23de668db9489dfca7276ce1fcdf0f6f","src/de/unit.rs":"b792db7952fc2e4719fdce9552fe4ba1836086cc967ae9a5b919c28b30f2b4a0","src/deprecated.rs":"cff374e86ea5f134913a2a194a68d7c2510ffd5214956d10b9c496e90a20a952","src/dummy.rs":"dce9d53f7f6efb41043d6dbd741e03e65fe0a56b2f739a041184036cd7491b16","src/fragment.rs":"6757cb4c3131d4300f093572efc273c4ab5a20e3e1efb54a311dcfa52d0bd6eb","src/internals/ast.rs":"b170c3b6a1afd72e01b461f6f802b00056baf998a24a1f5c421cad60ef8daa71","src/internals/attr.rs":"29d42a925ecff984643b79e6f4f10964e85121a2f6a971b5ba03ce719a8ca3c8","src/internals/case.rs":"10c8dda2b32d8c6c6b63cf09cdc63d02375af7e95ecefe8fecb34f93b65191bb","src/internals/check.rs":"86ea817316638ec33f70ecdf9634a31c934fd3df84533e3e315816dc130f0bff","src/internals/ctxt.rs":"83a4e6fbe0e439d578478883594407e03f2f340541be479bdf0b04a202633a37","src/internals/mod.rs":"c1ece6bbce5a5e8a2bf5d6d9a29e85551258db9c610fab73ac19c6b7d8cf98fd","src/internals/name.rs":"9bc1553d7b493794cd436664ee6b43fccb914f271fa86705ae2937ae923a876f","src/internals/receiver.rs":"901c12f5b5d3935f2757f4cfcb05f4fcdb36a2520f62167679410099e44510c0","src/internals/respan.rs":"899753859c58ce5f532a3ec4584796a52f13ed5a0533191e48c953ba5c1b52ff","src/internals/symbol.rs":"d2590f1c8356d6a10923476b558c39a85b77392ba09c92fa97e05e2c403e73c7","src/lib.rs":"44748f94c0a3fe25972e6386365f836e79a61d731845265a1aaaddb1c818fb9b","src/pretend.rs":"e13e44242c5c0a805ddc6ce51762bb44367b5ed08ba04eabfcb207ea5c474d4e","src/ser.rs":"d43be68a3c1d5d4617c30baebe06aceeaf012097ffa343102328ff94349e35e9","src/this.rs":"87818dc80cbb521b51938a653d09daf10aafc220bb10425948de82ad670fcb85"},"package":"d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"} \ No newline at end of file diff --git a/pkg/installer/vendor/serde_derive/.cargo_vcs_info.json b/pkg/installer/vendor/serde_derive/.cargo_vcs_info.json index 0b8124161f5..af8298f14c2 100644 --- a/pkg/installer/vendor/serde_derive/.cargo_vcs_info.json +++ b/pkg/installer/vendor/serde_derive/.cargo_vcs_info.json @@ -1,6 +1,6 @@ { "git": { - "sha1": "1b4da41f970555e111f471633205bbcb4dadbc63" + "sha1": "a866b336f14aa57a07f0d0be9f8762746e64ecb4" }, "path_in_vcs": "serde_derive" } \ No newline at end of file diff --git a/pkg/installer/vendor/serde_derive/Cargo.lock b/pkg/installer/vendor/serde_derive/Cargo.lock new file mode 100644 index 00000000000..4def135b7d9 --- /dev/null +++ b/pkg/installer/vendor/serde_derive/Cargo.lock @@ -0,0 +1,77 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.227" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80ece43fc6fbed4eb5392ab50c07334d3e577cbf40997ee896fe7af40bba4245" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.227" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a576275b607a2c86ea29e410193df32bc680303c82f31e275bbfcafe8b33be5" +dependencies = [ + "serde_derive 1.0.227", +] + +[[package]] +name = "serde_derive" +version = "1.0.227" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51e694923b8824cf0e9b382adf0f60d4e05f348f357b38833a3fa5ed7c2ede04" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn", +] + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" diff --git a/pkg/installer/vendor/serde_derive/Cargo.toml b/pkg/installer/vendor/serde_derive/Cargo.toml index 50c67929976..b8045e659ee 100644 --- a/pkg/installer/vendor/serde_derive/Cargo.toml +++ b/pkg/installer/vendor/serde_derive/Cargo.toml @@ -10,16 +10,17 @@ # See Cargo.toml.orig for the original contents. [package] -edition = "2015" -rust-version = "1.56" +edition = "2021" +rust-version = "1.61" name = "serde_derive" -version = "1.0.207" +version = "1.0.228" authors = [ "Erick Tryzelaar ", "David Tolnay ", ] build = false exclude = ["build.rs"] +autolib = false autobins = false autoexamples = false autotests = false @@ -42,8 +43,19 @@ license = "MIT OR Apache-2.0" repository = "https://github.com/serde-rs/serde" [package.metadata.docs.rs] -rustdoc-args = ["--generate-link-to-definition"] targets = ["x86_64-unknown-linux-gnu"] +rustdoc-args = [ + "--generate-link-to-definition", + "--generate-macro-expansion", + "--extern-html-root-url=core=https://doc.rust-lang.org", + "--extern-html-root-url=alloc=https://doc.rust-lang.org", + "--extern-html-root-url=std=https://doc.rust-lang.org", + "--extern-html-root-url=proc_macro=https://doc.rust-lang.org", +] + +[features] +default = [] +deserialize_in_place = [] [lib] name = "serde_derive" @@ -61,7 +73,7 @@ features = ["proc-macro"] default-features = false [dependencies.syn] -version = "2.0.46" +version = "2.0.81" features = [ "clone-impls", "derive", @@ -73,7 +85,3 @@ default-features = false [dev-dependencies.serde] version = "1" - -[features] -default = [] -deserialize_in_place = [] diff --git a/pkg/installer/vendor/serde_derive/Cargo.toml.orig b/pkg/installer/vendor/serde_derive/Cargo.toml.orig index 17648eb88b6..88f8f6a4360 100644 --- a/pkg/installer/vendor/serde_derive/Cargo.toml.orig +++ b/pkg/installer/vendor/serde_derive/Cargo.toml.orig @@ -1,18 +1,18 @@ [package] name = "serde_derive" -version = "1.0.207" +version = "1.0.228" authors = ["Erick Tryzelaar ", "David Tolnay "] categories = ["no-std", "no-std::no-alloc"] description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]" documentation = "https://serde.rs/derive.html" -edition = "2015" +edition = "2021" exclude = ["build.rs"] homepage = "https://serde.rs" keywords = ["serde", "serialization", "no_std", "derive"] license = "MIT OR Apache-2.0" readme = "crates-io.md" repository = "https://github.com/serde-rs/serde" -rust-version = "1.56" +rust-version = "1.61" [features] default = [] @@ -32,4 +32,11 @@ serde = { version = "1", path = "../serde" } [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] -rustdoc-args = ["--generate-link-to-definition"] +rustdoc-args = [ + "--generate-link-to-definition", + "--generate-macro-expansion", + "--extern-html-root-url=core=https://doc.rust-lang.org", + "--extern-html-root-url=alloc=https://doc.rust-lang.org", + "--extern-html-root-url=std=https://doc.rust-lang.org", + "--extern-html-root-url=proc_macro=https://doc.rust-lang.org", +] diff --git a/pkg/installer/vendor/serde_derive/README.md b/pkg/installer/vendor/serde_derive/README.md index 31292944af0..bf83d766272 100644 --- a/pkg/installer/vendor/serde_derive/README.md +++ b/pkg/installer/vendor/serde_derive/README.md @@ -1,4 +1,4 @@ -# Serde   [![Build Status]][actions] [![Latest Version]][crates.io] [![serde msrv]][Rust 1.31] [![serde_derive msrv]][Rust 1.56] +# Serde   [![Build Status]][actions] [![Latest Version]][crates.io] [![serde msrv]][Rust 1.56] [![serde_derive msrv]][Rust 1.61] [Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/serde/ci.yml?branch=master [actions]: https://github.com/serde-rs/serde/actions?query=branch%3Amaster @@ -6,8 +6,8 @@ [crates.io]: https://crates.io/crates/serde [serde msrv]: https://img.shields.io/crates/msrv/serde.svg?label=serde%20msrv&color=lightgray [serde_derive msrv]: https://img.shields.io/crates/msrv/serde_derive.svg?label=serde_derive%20msrv&color=lightgray -[Rust 1.31]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html [Rust 1.56]: https://blog.rust-lang.org/2021/10/21/Rust-1.56.0.html +[Rust 1.61]: https://blog.rust-lang.org/2022/05/19/Rust-1.61.0.html **Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** @@ -15,7 +15,7 @@ You may be looking for: -- [An overview of Serde](https://serde.rs/) +- [An overview of Serde](https://serde.rs) - [Data formats supported by Serde](https://serde.rs/#data-formats) - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) - [Examples](https://serde.rs/examples.html) @@ -27,7 +27,7 @@ You may be looking for:
Click to show Cargo.toml. -Run this code in the playground. +Run this code in the playground. ```toml diff --git a/pkg/installer/vendor/serde_derive/crates-io.md b/pkg/installer/vendor/serde_derive/crates-io.md index b49a5483b91..e6e7d9fb6d6 100644 --- a/pkg/installer/vendor/serde_derive/crates-io.md +++ b/pkg/installer/vendor/serde_derive/crates-io.md @@ -6,7 +6,7 @@ You may be looking for: -- [An overview of Serde](https://serde.rs/) +- [An overview of Serde](https://serde.rs) - [Data formats supported by Serde](https://serde.rs/#data-formats) - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) - [Examples](https://serde.rs/examples.html) diff --git a/pkg/installer/vendor/serde_derive/src/bound.rs b/pkg/installer/vendor/serde_derive/src/bound.rs index fe8ccfff5b2..2ff6521fe3f 100644 --- a/pkg/installer/vendor/serde_derive/src/bound.rs +++ b/pkg/installer/vendor/serde_derive/src/bound.rs @@ -227,7 +227,9 @@ pub fn with_bound( match bound { #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] syn::TypeParamBound::Trait(bound) => self.visit_path(&bound.path), - syn::TypeParamBound::Lifetime(_) | syn::TypeParamBound::Verbatim(_) => {} + syn::TypeParamBound::Lifetime(_) + | syn::TypeParamBound::PreciseCapture(_) + | syn::TypeParamBound::Verbatim(_) => {} _ => {} } } diff --git a/pkg/installer/vendor/serde_derive/src/de.rs b/pkg/installer/vendor/serde_derive/src/de.rs index 996e97e869d..ca19bb6f722 100644 --- a/pkg/installer/vendor/serde_derive/src/de.rs +++ b/pkg/installer/vendor/serde_derive/src/de.rs @@ -1,8 +1,10 @@ -use crate::fragment::{Expr, Fragment, Match, Stmts}; +use crate::deprecated::allow_deprecated; +use crate::fragment::{Expr, Fragment, Stmts}; use crate::internals::ast::{Container, Data, Field, Style, Variant}; +use crate::internals::name::Name; use crate::internals::{attr, replace_receiver, ungroup, Ctxt, Derive}; -use crate::{bound, dummy, pretend, this}; -use proc_macro2::{Literal, Span, TokenStream}; +use crate::{bound, dummy, pretend, private, this}; +use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use std::collections::BTreeSet; use std::ptr; @@ -10,11 +12,21 @@ use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{parse_quote, Ident, Index, Member}; +mod enum_; +mod enum_adjacently; +mod enum_externally; +mod enum_internally; +mod enum_untagged; +mod identifier; +mod struct_; +mod tuple; +mod unit; + pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result { replace_receiver(input); let ctxt = Ctxt::new(); - let cont = match Container::from_ast(&ctxt, input, Derive::Deserialize) { + let cont = match Container::from_ast(&ctxt, input, Derive::Deserialize, &private.ident()) { Some(cont) => cont, None => return Err(ctxt.check().unwrap_err()), }; @@ -23,19 +35,21 @@ pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result(__deserializer: __D) -> #serde::__private::Result<#remote #ty_generics, __D::Error> + #vis fn deserialize<__D>(__deserializer: __D) -> _serde::#private::Result<#remote #ty_generics, __D::Error> where - __D: #serde::Deserializer<#delife>, + __D: _serde::Deserializer<#delife>, { #used #body @@ -47,10 +61,11 @@ pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result for #ident #ty_generics #where_clause { - fn deserialize<__D>(__deserializer: __D) -> #serde::__private::Result + #allow_deprecated + impl #de_impl_generics _serde::Deserialize<#delife> for #ident #ty_generics #where_clause { + fn deserialize<__D>(__deserializer: __D) -> _serde::#private::Result where - __D: #serde::Deserializer<#delife>, + __D: _serde::Deserializer<#delife>, { #body } @@ -152,6 +167,23 @@ impl Parameters { fn type_name(&self) -> String { self.this_type.segments.last().unwrap().ident.to_string() } + + /// Split the data structure's generics into the pieces to use for its + /// `Deserialize` impl, augmented with an additional `'de` lifetime for use + /// as the `Deserialize` trait's lifetime. + fn generics_with_de_lifetime( + &self, + ) -> ( + DeImplGenerics, + DeTypeGenerics, + syn::TypeGenerics, + Option<&syn::WhereClause>, + ) { + let de_impl_generics = DeImplGenerics(self); + let de_ty_generics = DeTypeGenerics(self); + let (_, ty_generics, where_clause) = self.generics.split_for_impl(); + (de_impl_generics, de_ty_generics, ty_generics, where_clause) + } } // All the generics in the input, plus a bound `T: Deserialize` for each generic @@ -172,7 +204,7 @@ fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generi attr::Default::Default => bound::with_self_bound( cont, &generics, - &parse_quote!(_serde::__private::Default), + &parse_quote!(_serde::#private::Default), ), attr::Default::None | attr::Default::Path(_) => generics, }; @@ -189,7 +221,7 @@ fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generi cont, &generics, requires_default, - &parse_quote!(_serde::__private::Default), + &parse_quote!(_serde::#private::Default), ) } } @@ -280,18 +312,18 @@ fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment { deserialize_try_from(type_try_from) } else if let attr::Identifier::No = cont.attrs.identifier() { match &cont.data { - Data::Enum(variants) => deserialize_enum(params, variants, &cont.attrs), + Data::Enum(variants) => enum_::deserialize(params, variants, &cont.attrs), Data::Struct(Style::Struct, fields) => { - deserialize_struct(params, fields, &cont.attrs, StructForm::Struct) + struct_::deserialize(params, fields, &cont.attrs, StructForm::Struct) } Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => { - deserialize_tuple(params, fields, &cont.attrs, TupleForm::Tuple) + tuple::deserialize(params, fields, &cont.attrs, TupleForm::Tuple) } - Data::Struct(Style::Unit, _) => deserialize_unit_struct(params, &cont.attrs), + Data::Struct(Style::Unit, _) => unit::deserialize(params, &cont.attrs), } } else { match &cont.data { - Data::Enum(variants) => deserialize_custom_identifier(params, variants, &cont.attrs), + Data::Enum(variants) => identifier::deserialize_custom(params, variants, &cont.attrs), Data::Struct(_, _) => unreachable!("checked in serde_derive_internals"), } } @@ -317,10 +349,10 @@ fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option { - deserialize_struct_in_place(params, fields, &cont.attrs)? + struct_::deserialize_in_place(params, fields, &cont.attrs)? } Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => { - deserialize_tuple_in_place(params, fields, &cont.attrs) + tuple::deserialize_in_place(params, fields, &cont.attrs) } Data::Enum(_) | Data::Struct(Style::Unit, _) => { return None; @@ -331,7 +363,7 @@ fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option(__deserializer: __D, __place: &mut Self) -> _serde::__private::Result<(), __D::Error> + fn deserialize_in_place<__D>(__deserializer: __D, __place: &mut Self) -> _serde::#private::Result<(), __D::Error> where __D: _serde::Deserializer<#delife>, { @@ -347,6 +379,7 @@ fn deserialize_in_place_body(_cont: &Container, _params: &Parameters) -> Option< None } +/// Generates `Deserialize::deserialize` body for a type with `#[serde(transparent)]` attribute fn deserialize_transparent(cont: &Container, params: &Parameters) -> Fragment { let fields = match &cont.data { Data::Struct(_, fields) => fields, @@ -370,79 +403,40 @@ fn deserialize_transparent(cont: &Container, params: &Parameters) -> Fragment { quote!(#member: __transparent) } else { let value = match field.attrs.default() { - attr::Default::Default => quote!(_serde::__private::Default::default()), - attr::Default::Path(path) => quote!(#path()), - attr::Default::None => quote!(_serde::__private::PhantomData), + attr::Default::Default => quote!(_serde::#private::Default::default()), + // If #path returns wrong type, error will be reported here (^^^^^). + // We attach span of the path to the function so it will be reported + // on the #[serde(default = "...")] + // ^^^^^ + attr::Default::Path(path) => quote_spanned!(path.span()=> #path()), + attr::Default::None => quote!(_serde::#private::PhantomData), }; quote!(#member: #value) } }); quote_block! { - _serde::__private::Result::map( + _serde::#private::Result::map( #path(__deserializer), |__transparent| #this_value { #(#assign),* }) } } +/// Generates `Deserialize::deserialize` body for a type with `#[serde(from)]` attribute fn deserialize_from(type_from: &syn::Type) -> Fragment { quote_block! { - _serde::__private::Result::map( + _serde::#private::Result::map( <#type_from as _serde::Deserialize>::deserialize(__deserializer), - _serde::__private::From::from) + _serde::#private::From::from) } } +/// Generates `Deserialize::deserialize` body for a type with `#[serde(try_from)]` attribute fn deserialize_try_from(type_try_from: &syn::Type) -> Fragment { quote_block! { - _serde::__private::Result::and_then( + _serde::#private::Result::and_then( <#type_try_from as _serde::Deserialize>::deserialize(__deserializer), - |v| _serde::__private::TryFrom::try_from(v).map_err(_serde::de::Error::custom)) - } -} - -fn deserialize_unit_struct(params: &Parameters, cattrs: &attr::Container) -> Fragment { - let this_type = ¶ms.this_type; - let this_value = ¶ms.this_value; - let type_name = cattrs.name().deserialize_name(); - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let expecting = format!("unit struct {}", params.type_name()); - let expecting = cattrs.expecting().unwrap_or(&expecting); - - quote_block! { - #[doc(hidden)] - struct __Visitor #de_impl_generics #where_clause { - marker: _serde::__private::PhantomData<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this_type #ty_generics; - - fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { - _serde::__private::Formatter::write_str(__formatter, #expecting) - } - - #[inline] - fn visit_unit<__E>(self) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(#this_value) - } - } - - _serde::Deserializer::deserialize_unit_struct( - __deserializer, - #type_name, - __Visitor { - marker: _serde::__private::PhantomData::<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData, - }, - ) + |v| _serde::#private::TryFrom::try_from(v).map_err(_serde::de::Error::custom)) } } @@ -450,229 +444,8 @@ enum TupleForm<'a> { Tuple, /// Contains a variant name ExternallyTagged(&'a syn::Ident), - /// Contains a variant name and an intermediate deserializer from which actual - /// deserialization will be performed - Untagged(&'a syn::Ident, TokenStream), -} - -fn deserialize_tuple( - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, - form: TupleForm, -) -> Fragment { - assert!( - !has_flatten(fields), - "tuples and tuple variants cannot have flatten fields" - ); - - let field_count = fields - .iter() - .filter(|field| !field.attrs.skip_deserializing()) - .count(); - - let this_type = ¶ms.this_type; - let this_value = ¶ms.this_value; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - // If there are getters (implying private fields), construct the local type - // and use an `Into` conversion to get the remote type. If there are no - // getters then construct the target type directly. - let construct = if params.has_getter { - let local = ¶ms.local; - quote!(#local) - } else { - quote!(#this_value) - }; - - let type_path = match form { - TupleForm::Tuple => construct, - TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident, _) => { - quote!(#construct::#variant_ident) - } - }; - let expecting = match form { - TupleForm::Tuple => format!("tuple struct {}", params.type_name()), - TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident, _) => { - format!("tuple variant {}::{}", params.type_name(), variant_ident) - } - }; - let expecting = cattrs.expecting().unwrap_or(&expecting); - - let nfields = fields.len(); - - let visit_newtype_struct = match form { - TupleForm::Tuple if nfields == 1 => { - Some(deserialize_newtype_struct(&type_path, params, &fields[0])) - } - _ => None, - }; - - let visit_seq = Stmts(deserialize_seq( - &type_path, params, fields, false, cattrs, expecting, - )); - - let visitor_expr = quote! { - __Visitor { - marker: _serde::__private::PhantomData::<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData, - } - }; - let dispatch = match form { - TupleForm::Tuple if nfields == 1 => { - let type_name = cattrs.name().deserialize_name(); - quote! { - _serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr) - } - } - TupleForm::Tuple => { - let type_name = cattrs.name().deserialize_name(); - quote! { - _serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #field_count, #visitor_expr) - } - } - TupleForm::ExternallyTagged(_) => quote! { - _serde::de::VariantAccess::tuple_variant(__variant, #field_count, #visitor_expr) - }, - TupleForm::Untagged(_, deserializer) => quote! { - _serde::Deserializer::deserialize_tuple(#deserializer, #field_count, #visitor_expr) - }, - }; - - let visitor_var = if field_count == 0 { - quote!(_) - } else { - quote!(mut __seq) - }; - - quote_block! { - #[doc(hidden)] - struct __Visitor #de_impl_generics #where_clause { - marker: _serde::__private::PhantomData<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this_type #ty_generics; - - fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { - _serde::__private::Formatter::write_str(__formatter, #expecting) - } - - #visit_newtype_struct - - #[inline] - fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::__private::Result - where - __A: _serde::de::SeqAccess<#delife>, - { - #visit_seq - } - } - - #dispatch - } -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_tuple_in_place( - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, -) -> Fragment { - assert!( - !has_flatten(fields), - "tuples and tuple variants cannot have flatten fields" - ); - - let field_count = fields - .iter() - .filter(|field| !field.attrs.skip_deserializing()) - .count(); - - let this_type = ¶ms.this_type; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let expecting = format!("tuple struct {}", params.type_name()); - let expecting = cattrs.expecting().unwrap_or(&expecting); - - let nfields = fields.len(); - - let visit_newtype_struct = if nfields == 1 { - // We do not generate deserialize_in_place if every field has a - // deserialize_with. - assert!(fields[0].attrs.deserialize_with().is_none()); - - Some(quote! { - #[inline] - fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::__private::Result - where - __E: _serde::Deserializer<#delife>, - { - _serde::Deserialize::deserialize_in_place(__e, &mut self.place.0) - } - }) - } else { - None - }; - - let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs, expecting)); - - let visitor_expr = quote! { - __Visitor { - place: __place, - lifetime: _serde::__private::PhantomData, - } - }; - - let type_name = cattrs.name().deserialize_name(); - let dispatch = if nfields == 1 { - quote!(_serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr)) - } else { - quote!(_serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #field_count, #visitor_expr)) - }; - - let visitor_var = if field_count == 0 { - quote!(_) - } else { - quote!(mut __seq) - }; - - let in_place_impl_generics = de_impl_generics.in_place(); - let in_place_ty_generics = de_ty_generics.in_place(); - let place_life = place_lifetime(); - - quote_block! { - #[doc(hidden)] - struct __Visitor #in_place_impl_generics #where_clause { - place: &#place_life mut #this_type #ty_generics, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { - type Value = (); - - fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { - _serde::__private::Formatter::write_str(__formatter, #expecting) - } - - #visit_newtype_struct - - #[inline] - fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::__private::Result - where - __A: _serde::de::SeqAccess<#delife>, - { - #visit_seq - } - } - - #dispatch - } + /// Contains a variant name + Untagged(&'a syn::Ident), } fn deserialize_seq( @@ -716,7 +489,7 @@ fn deserialize_seq( let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); quote!({ #wrapper - _serde::__private::Option::map( + _serde::#private::Option::map( _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)?, |__wrap| __wrap.value) }) @@ -725,8 +498,8 @@ fn deserialize_seq( let value_if_none = expr_is_missing_seq(None, index_in_seq, field, cattrs, expecting); let assign = quote! { let #var = match #visit { - _serde::__private::Some(__value) => __value, - _serde::__private::None => #value_if_none, + _serde::#private::Some(__value) => __value, + _serde::#private::None => #value_if_none, }; }; index_in_seq += 1; @@ -749,15 +522,19 @@ fn deserialize_seq( let this_type = ¶ms.this_type; let (_, ty_generics, _) = params.generics.split_for_impl(); result = quote! { - _serde::__private::Into::<#this_type #ty_generics>::into(#result) + _serde::#private::Into::<#this_type #ty_generics>::into(#result) }; } let let_default = match cattrs.default() { attr::Default::Default => Some(quote!( - let __default: Self::Value = _serde::__private::Default::default(); + let __default: Self::Value = _serde::#private::Default::default(); )), - attr::Default::Path(path) => Some(quote!( + // If #path returns wrong type, error will be reported here (^^^^^). + // We attach span of the path to the function so it will be reported + // on the #[serde(default = "...")] + // ^^^^^ + attr::Default::Path(path) => Some(quote_spanned!(path.span()=> let __default: Self::Value = #path(); )), attr::Default::None => { @@ -770,7 +547,7 @@ fn deserialize_seq( quote_block! { #let_default #(#let_values)* - _serde::__private::Ok(#result) + _serde::#private::Ok(#result) } } @@ -806,8 +583,8 @@ fn deserialize_seq_in_place( let write = match field.attrs.deserialize_with() { None => { quote! { - if let _serde::__private::None = _serde::de::SeqAccess::next_element_seed(&mut __seq, - _serde::__private::de::InPlaceSeed(&mut self.place.#member))? + if let _serde::#private::None = _serde::de::SeqAccess::next_element_seed(&mut __seq, + _serde::#private::de::InPlaceSeed(&mut self.place.#member))? { #value_if_none; } @@ -818,10 +595,10 @@ fn deserialize_seq_in_place( quote!({ #wrapper match _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)? { - _serde::__private::Some(__wrap) => { + _serde::#private::Some(__wrap) => { self.place.#member = __wrap.value; } - _serde::__private::None => { + _serde::#private::None => { #value_if_none; } } @@ -837,9 +614,13 @@ fn deserialize_seq_in_place( let (_, ty_generics, _) = params.generics.split_for_impl(); let let_default = match cattrs.default() { attr::Default::Default => Some(quote!( - let __default: #this_type #ty_generics = _serde::__private::Default::default(); + let __default: #this_type #ty_generics = _serde::#private::Default::default(); )), - attr::Default::Path(path) => Some(quote!( + // If #path returns wrong type, error will be reported here (^^^^^). + // We attach span of the path to the function so it will be reported + // on the #[serde(default = "...")] + // ^^^^^ + attr::Default::Path(path) => Some(quote_spanned!(path.span()=> let __default: #this_type #ty_generics = #path(); )), attr::Default::None => { @@ -852,51 +633,7 @@ fn deserialize_seq_in_place( quote_block! { #let_default #(#write_values)* - _serde::__private::Ok(()) - } -} - -fn deserialize_newtype_struct( - type_path: &TokenStream, - params: &Parameters, - field: &Field, -) -> TokenStream { - let delife = params.borrowed.de_lifetime(); - let field_ty = field.ty; - - let value = match field.attrs.deserialize_with() { - None => { - let span = field.original.span(); - let func = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize); - quote! { - #func(__e)? - } - } - Some(path) => { - quote! { - #path(__e)? - } - } - }; - - let mut result = quote!(#type_path(__field0)); - if params.has_getter { - let this_type = ¶ms.this_type; - let (_, ty_generics, _) = params.generics.split_for_impl(); - result = quote! { - _serde::__private::Into::<#this_type #ty_generics>::into(#result) - }; - } - - quote! { - #[inline] - fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::__private::Result - where - __E: _serde::Deserializer<#delife>, - { - let __field0: #field_ty = #value; - _serde::__private::Ok(#result) - } + _serde::#private::Ok(()) } } @@ -904,2035 +641,105 @@ enum StructForm<'a> { Struct, /// Contains a variant name ExternallyTagged(&'a syn::Ident), - /// Contains a variant name and an intermediate deserializer from which actual - /// deserialization will be performed - InternallyTagged(&'a syn::Ident, TokenStream), - /// Contains a variant name and an intermediate deserializer from which actual - /// deserialization will be performed - Untagged(&'a syn::Ident, TokenStream), + /// Contains a variant name + InternallyTagged(&'a syn::Ident), + /// Contains a variant name + Untagged(&'a syn::Ident), +} + +struct FieldWithAliases<'a> { + ident: Ident, + aliases: &'a BTreeSet, +} + +fn field_i(i: usize) -> Ident { + Ident::new(&format!("__field{}", i), Span::call_site()) } -fn deserialize_struct( +/// This function wraps the expression in `#[serde(deserialize_with = "...")]` +/// in a trait to prevent it from accessing the internal `Deserialize` state. +fn wrap_deserialize_with( params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, - form: StructForm, -) -> Fragment { + value_ty: &TokenStream, + deserialize_with: &syn::ExprPath, +) -> (TokenStream, TokenStream) { let this_type = ¶ms.this_type; - let this_value = ¶ms.this_value; let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); + params.generics_with_de_lifetime(); let delife = params.borrowed.de_lifetime(); + let deserializer_var = quote!(__deserializer); - // If there are getters (implying private fields), construct the local type - // and use an `Into` conversion to get the remote type. If there are no - // getters then construct the target type directly. - let construct = if params.has_getter { - let local = ¶ms.local; - quote!(#local) - } else { - quote!(#this_value) + // If #deserialize_with returns wrong type, error will be reported here (^^^^^). + // We attach span of the path to the function so it will be reported + // on the #[serde(with = "...")] + // ^^^^^ + let value = quote_spanned! {deserialize_with.span()=> + #deserialize_with(#deserializer_var)? }; + let wrapper = quote! { + #[doc(hidden)] + struct __DeserializeWith #de_impl_generics #where_clause { + value: #value_ty, + phantom: _serde::#private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } - let type_path = match form { - StructForm::Struct => construct, - StructForm::ExternallyTagged(variant_ident) - | StructForm::InternallyTagged(variant_ident, _) - | StructForm::Untagged(variant_ident, _) => quote!(#construct::#variant_ident), - }; - let expecting = match form { - StructForm::Struct => format!("struct {}", params.type_name()), - StructForm::ExternallyTagged(variant_ident) - | StructForm::InternallyTagged(variant_ident, _) - | StructForm::Untagged(variant_ident, _) => { - format!("struct variant {}::{}", params.type_name(), variant_ident) + #[automatically_derived] + impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause { + fn deserialize<__D>(#deserializer_var: __D) -> _serde::#private::Result + where + __D: _serde::Deserializer<#delife>, + { + _serde::#private::Ok(__DeserializeWith { + value: #value, + phantom: _serde::#private::PhantomData, + lifetime: _serde::#private::PhantomData, + }) + } } }; - let expecting = cattrs.expecting().unwrap_or(&expecting); - let field_names_idents: Vec<_> = fields - .iter() - .enumerate() - // Skip fields that shouldn't be deserialized or that were flattened, - // so they don't appear in the storage in their literal form - .filter(|&(_, field)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) - .map(|(i, field)| { - ( - field.attrs.name().deserialize_name(), - field_i(i), - field.attrs.aliases(), - ) - }) - .collect(); - - let has_flatten = has_flatten(fields); - let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs, has_flatten); - - // untagged struct variants do not get a visit_seq method. The same applies to - // structs that only have a map representation. - let visit_seq = match form { - StructForm::Untagged(..) => None, - _ if has_flatten => None, - _ => { - let mut_seq = if field_names_idents.is_empty() { - quote!(_) - } else { - quote!(mut __seq) - }; + let wrapper_ty = quote!(__DeserializeWith #de_ty_generics); - let visit_seq = Stmts(deserialize_seq( - &type_path, params, fields, true, cattrs, expecting, - )); + (wrapper, wrapper_ty) +} - Some(quote! { - #[inline] - fn visit_seq<__A>(self, #mut_seq: __A) -> _serde::__private::Result - where - __A: _serde::de::SeqAccess<#delife>, - { - #visit_seq - } - }) - } - }; - let visit_map = Stmts(deserialize_map( - &type_path, - params, - fields, - cattrs, - has_flatten, - )); - - let visitor_seed = match form { - StructForm::ExternallyTagged(..) if has_flatten => Some(quote! { - impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this_type #ty_generics; - - fn deserialize<__D>(self, __deserializer: __D) -> _serde::__private::Result - where - __D: _serde::Deserializer<#delife>, - { - _serde::Deserializer::deserialize_map(__deserializer, self) - } - } - }), - _ => None, - }; +fn wrap_deserialize_field_with( + params: &Parameters, + field_ty: &syn::Type, + deserialize_with: &syn::ExprPath, +) -> (TokenStream, TokenStream) { + wrap_deserialize_with(params, "e!(#field_ty), deserialize_with) +} + +// Generates closure that converts single input parameter to the final value. +fn unwrap_to_variant_closure( + params: &Parameters, + variant: &Variant, + with_wrapper: bool, +) -> TokenStream { + let this_value = ¶ms.this_value; + let variant_ident = &variant.ident; - let fields_stmt = if has_flatten { - None + let (arg, wrapper) = if with_wrapper { + (quote! { __wrap }, quote! { __wrap.value }) } else { - let field_names = field_names_idents - .iter() - .flat_map(|&(_, _, aliases)| aliases); + let field_tys = variant.fields.iter().map(|field| field.ty); + (quote! { __wrap: (#(#field_tys),*) }, quote! { __wrap }) + }; - Some(quote! { - #[doc(hidden)] - const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; + let field_access = (0..variant.fields.len()).map(|n| { + Member::Unnamed(Index { + index: n as u32, + span: Span::call_site(), }) - }; + }); - let visitor_expr = quote! { - __Visitor { - marker: _serde::__private::PhantomData::<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData, - } - }; - let dispatch = match form { - StructForm::Struct if has_flatten => quote! { - _serde::Deserializer::deserialize_map(__deserializer, #visitor_expr) - }, - StructForm::Struct => { - let type_name = cattrs.name().deserialize_name(); + match variant.style { + Style::Struct if variant.fields.len() == 1 => { + let member = &variant.fields[0].member; quote! { - _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, #visitor_expr) - } - } - StructForm::ExternallyTagged(_) if has_flatten => quote! { - _serde::de::VariantAccess::newtype_variant_seed(__variant, #visitor_expr) - }, - StructForm::ExternallyTagged(_) => quote! { - _serde::de::VariantAccess::struct_variant(__variant, FIELDS, #visitor_expr) - }, - StructForm::InternallyTagged(_, deserializer) => quote! { - _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) - }, - StructForm::Untagged(_, deserializer) => quote! { - _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) - }, - }; - - quote_block! { - #field_visitor - - #[doc(hidden)] - struct __Visitor #de_impl_generics #where_clause { - marker: _serde::__private::PhantomData<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this_type #ty_generics; - - fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { - _serde::__private::Formatter::write_str(__formatter, #expecting) - } - - #visit_seq - - #[inline] - fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result - where - __A: _serde::de::MapAccess<#delife>, - { - #visit_map - } - } - - #visitor_seed - - #fields_stmt - - #dispatch - } -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_struct_in_place( - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, -) -> Option { - // for now we do not support in_place deserialization for structs that - // are represented as map. - if has_flatten(fields) { - return None; - } - - let this_type = ¶ms.this_type; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let expecting = format!("struct {}", params.type_name()); - let expecting = cattrs.expecting().unwrap_or(&expecting); - - let field_names_idents: Vec<_> = fields - .iter() - .enumerate() - .filter(|&(_, field)| !field.attrs.skip_deserializing()) - .map(|(i, field)| { - ( - field.attrs.name().deserialize_name(), - field_i(i), - field.attrs.aliases(), - ) - }) - .collect(); - - let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs, false); - - let mut_seq = if field_names_idents.is_empty() { - quote!(_) - } else { - quote!(mut __seq) - }; - let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs, expecting)); - let visit_map = Stmts(deserialize_map_in_place(params, fields, cattrs)); - let field_names = field_names_idents - .iter() - .flat_map(|&(_, _, aliases)| aliases); - let type_name = cattrs.name().deserialize_name(); - - let in_place_impl_generics = de_impl_generics.in_place(); - let in_place_ty_generics = de_ty_generics.in_place(); - let place_life = place_lifetime(); - - Some(quote_block! { - #field_visitor - - #[doc(hidden)] - struct __Visitor #in_place_impl_generics #where_clause { - place: &#place_life mut #this_type #ty_generics, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { - type Value = (); - - fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { - _serde::__private::Formatter::write_str(__formatter, #expecting) - } - - #[inline] - fn visit_seq<__A>(self, #mut_seq: __A) -> _serde::__private::Result - where - __A: _serde::de::SeqAccess<#delife>, - { - #visit_seq - } - - #[inline] - fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result - where - __A: _serde::de::MapAccess<#delife>, - { - #visit_map - } - } - - #[doc(hidden)] - const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; - - _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, __Visitor { - place: __place, - lifetime: _serde::__private::PhantomData, - }) - }) -} - -fn deserialize_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, -) -> Fragment { - // The variants have already been checked (in ast.rs) that all untagged variants appear at the end - match variants.iter().position(|var| var.attrs.untagged()) { - Some(variant_idx) => { - let (tagged, untagged) = variants.split_at(variant_idx); - let tagged_frag = Expr(deserialize_homogeneous_enum(params, tagged, cattrs)); - deserialize_untagged_enum_after(params, untagged, cattrs, Some(tagged_frag)) - } - None => deserialize_homogeneous_enum(params, variants, cattrs), - } -} - -fn deserialize_homogeneous_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, -) -> Fragment { - match cattrs.tag() { - attr::TagType::External => deserialize_externally_tagged_enum(params, variants, cattrs), - attr::TagType::Internal { tag } => { - deserialize_internally_tagged_enum(params, variants, cattrs, tag) - } - attr::TagType::Adjacent { tag, content } => { - deserialize_adjacently_tagged_enum(params, variants, cattrs, tag, content) - } - attr::TagType::None => deserialize_untagged_enum(params, variants, cattrs), - } -} - -fn prepare_enum_variant_enum(variants: &[Variant]) -> (TokenStream, Stmts) { - let mut deserialized_variants = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()); - - let variant_names_idents: Vec<_> = deserialized_variants - .clone() - .map(|(i, variant)| { - ( - variant.attrs.name().deserialize_name(), - field_i(i), - variant.attrs.aliases(), - ) - }) - .collect(); - - let fallthrough = deserialized_variants - .position(|(_, variant)| variant.attrs.other()) - .map(|other_idx| { - let ignore_variant = variant_names_idents[other_idx].1.clone(); - quote!(_serde::__private::Ok(__Field::#ignore_variant)) - }); - - let variants_stmt = { - let variant_names = variant_names_idents.iter().map(|(name, _, _)| name); - quote! { - #[doc(hidden)] - const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; - } - }; - - let variant_visitor = Stmts(deserialize_generated_identifier( - &variant_names_idents, - false, // variant identifiers do not depend on the presence of flatten fields - true, - None, - fallthrough, - )); - - (variants_stmt, variant_visitor) -} - -fn deserialize_externally_tagged_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, -) -> Fragment { - let this_type = ¶ms.this_type; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let type_name = cattrs.name().deserialize_name(); - let expecting = format!("enum {}", params.type_name()); - let expecting = cattrs.expecting().unwrap_or(&expecting); - - let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants); - - // Match arms to extract a variant from a string - let variant_arms = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .map(|(i, variant)| { - let variant_name = field_i(i); - - let block = Match(deserialize_externally_tagged_variant( - params, variant, cattrs, - )); - - quote! { - (__Field::#variant_name, __variant) => #block - } - }); - - let all_skipped = variants - .iter() - .all(|variant| variant.attrs.skip_deserializing()); - let match_variant = if all_skipped { - // This is an empty enum like `enum Impossible {}` or an enum in which - // all variants have `#[serde(skip_deserializing)]`. - quote! { - // FIXME: Once feature(exhaustive_patterns) is stable: - // let _serde::__private::Err(__err) = _serde::de::EnumAccess::variant::<__Field>(__data); - // _serde::__private::Err(__err) - _serde::__private::Result::map( - _serde::de::EnumAccess::variant::<__Field>(__data), - |(__impossible, _)| match __impossible {}) - } - } else { - quote! { - match _serde::de::EnumAccess::variant(__data)? { - #(#variant_arms)* - } - } - }; - - quote_block! { - #variant_visitor - - #[doc(hidden)] - struct __Visitor #de_impl_generics #where_clause { - marker: _serde::__private::PhantomData<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this_type #ty_generics; - - fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { - _serde::__private::Formatter::write_str(__formatter, #expecting) - } - - fn visit_enum<__A>(self, __data: __A) -> _serde::__private::Result - where - __A: _serde::de::EnumAccess<#delife>, - { - #match_variant - } - } - - #variants_stmt - - _serde::Deserializer::deserialize_enum( - __deserializer, - #type_name, - VARIANTS, - __Visitor { - marker: _serde::__private::PhantomData::<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData, - }, - ) - } -} - -fn deserialize_internally_tagged_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, - tag: &str, -) -> Fragment { - let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants); - - // Match arms to extract a variant from a string - let variant_arms = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .map(|(i, variant)| { - let variant_name = field_i(i); - - let block = Match(deserialize_internally_tagged_variant( - params, - variant, - cattrs, - quote!(__deserializer), - )); - - quote! { - __Field::#variant_name => #block - } - }); - - let expecting = format!("internally tagged enum {}", params.type_name()); - let expecting = cattrs.expecting().unwrap_or(&expecting); - - quote_block! { - #variant_visitor - - #variants_stmt - - let (__tag, __content) = _serde::Deserializer::deserialize_any( - __deserializer, - _serde::__private::de::TaggedContentVisitor::<__Field>::new(#tag, #expecting))?; - let __deserializer = _serde::__private::de::ContentDeserializer::<__D::Error>::new(__content); - - match __tag { - #(#variant_arms)* - } - } -} - -fn deserialize_adjacently_tagged_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, - tag: &str, - content: &str, -) -> Fragment { - let this_type = ¶ms.this_type; - let this_value = ¶ms.this_value; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants); - - let variant_arms: &Vec<_> = &variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .map(|(i, variant)| { - let variant_index = field_i(i); - - let block = Match(deserialize_untagged_variant( - params, - variant, - cattrs, - quote!(__deserializer), - )); - - quote! { - __Field::#variant_index => #block - } - }) - .collect(); - - let rust_name = params.type_name(); - let expecting = format!("adjacently tagged enum {}", rust_name); - let expecting = cattrs.expecting().unwrap_or(&expecting); - let type_name = cattrs.name().deserialize_name(); - let deny_unknown_fields = cattrs.deny_unknown_fields(); - - // If unknown fields are allowed, we pick the visitor that can step over - // those. Otherwise we pick the visitor that fails on unknown keys. - let field_visitor_ty = if deny_unknown_fields { - quote! { _serde::__private::de::TagOrContentFieldVisitor } - } else { - quote! { _serde::__private::de::TagContentOtherFieldVisitor } - }; - - let tag_or_content = quote! { - #field_visitor_ty { - tag: #tag, - content: #content, - } - }; - - let variant_seed = quote! { - _serde::__private::de::AdjacentlyTaggedEnumVariantSeed::<__Field> { - enum_name: #rust_name, - variants: VARIANTS, - fields_enum: _serde::__private::PhantomData - } - }; - - let mut missing_content = quote! { - _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#content)) - }; - let mut missing_content_fallthrough = quote!(); - let missing_content_arms = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .filter_map(|(i, variant)| { - let variant_index = field_i(i); - let variant_ident = &variant.ident; - - let arm = match variant.style { - Style::Unit => quote! { - _serde::__private::Ok(#this_value::#variant_ident) - }, - Style::Newtype if variant.attrs.deserialize_with().is_none() => { - let span = variant.original.span(); - let func = quote_spanned!(span=> _serde::__private::de::missing_field); - quote! { - #func(#content).map(#this_value::#variant_ident) - } - } - _ => { - missing_content_fallthrough = quote!(_ => #missing_content); - return None; - } - }; - Some(quote! { - __Field::#variant_index => #arm, - }) - }) - .collect::>(); - if !missing_content_arms.is_empty() { - missing_content = quote! { - match __field { - #(#missing_content_arms)* - #missing_content_fallthrough - } - }; - } - - // Advance the map by one key, returning early in case of error. - let next_key = quote! { - _serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)? - }; - - let variant_from_map = quote! { - _serde::de::MapAccess::next_value_seed(&mut __map, #variant_seed)? - }; - - // When allowing unknown fields, we want to transparently step through keys - // we don't care about until we find `tag`, `content`, or run out of keys. - let next_relevant_key = if deny_unknown_fields { - next_key - } else { - quote!({ - let mut __rk : _serde::__private::Option<_serde::__private::de::TagOrContentField> = _serde::__private::None; - while let _serde::__private::Some(__k) = #next_key { - match __k { - _serde::__private::de::TagContentOtherField::Other => { - let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; - continue; - }, - _serde::__private::de::TagContentOtherField::Tag => { - __rk = _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag); - break; - } - _serde::__private::de::TagContentOtherField::Content => { - __rk = _serde::__private::Some(_serde::__private::de::TagOrContentField::Content); - break; - } - } - } - - __rk - }) - }; - - // Step through remaining keys, looking for duplicates of previously-seen - // keys. When unknown fields are denied, any key that isn't a duplicate will - // at this point immediately produce an error. - let visit_remaining_keys = quote! { - match #next_relevant_key { - _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { - _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) - } - _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { - _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) - } - _serde::__private::None => _serde::__private::Ok(__ret), - } - }; - - let finish_content_then_tag = if variant_arms.is_empty() { - quote! { - match #variant_from_map {} - } - } else { - quote! { - let __ret = match #variant_from_map { - // Deserialize the buffered content now that we know the variant. - #(#variant_arms)* - }?; - // Visit remaining keys, looking for duplicates. - #visit_remaining_keys - } - }; - - quote_block! { - #variant_visitor - - #variants_stmt - - #[doc(hidden)] - struct __Seed #de_impl_generics #where_clause { - field: __Field, - marker: _serde::__private::PhantomData<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Seed #de_ty_generics #where_clause { - type Value = #this_type #ty_generics; - - fn deserialize<__D>(self, __deserializer: __D) -> _serde::__private::Result - where - __D: _serde::Deserializer<#delife>, - { - match self.field { - #(#variant_arms)* - } - } - } - - #[doc(hidden)] - struct __Visitor #de_impl_generics #where_clause { - marker: _serde::__private::PhantomData<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this_type #ty_generics; - - fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { - _serde::__private::Formatter::write_str(__formatter, #expecting) - } - - fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result - where - __A: _serde::de::MapAccess<#delife>, - { - // Visit the first relevant key. - match #next_relevant_key { - // First key is the tag. - _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { - // Parse the tag. - let __field = #variant_from_map; - // Visit the second key. - match #next_relevant_key { - // Second key is a duplicate of the tag. - _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { - _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) - } - // Second key is the content. - _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { - let __ret = _serde::de::MapAccess::next_value_seed(&mut __map, - __Seed { - field: __field, - marker: _serde::__private::PhantomData, - lifetime: _serde::__private::PhantomData, - })?; - // Visit remaining keys, looking for duplicates. - #visit_remaining_keys - } - // There is no second key; might be okay if the we have a unit variant. - _serde::__private::None => #missing_content - } - } - // First key is the content. - _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { - // Buffer up the content. - let __content = _serde::de::MapAccess::next_value::<_serde::__private::de::Content>(&mut __map)?; - // Visit the second key. - match #next_relevant_key { - // Second key is the tag. - _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { - let __deserializer = _serde::__private::de::ContentDeserializer::<__A::Error>::new(__content); - #finish_content_then_tag - } - // Second key is a duplicate of the content. - _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { - _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) - } - // There is no second key. - _serde::__private::None => { - _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) - } - } - } - // There is no first key. - _serde::__private::None => { - _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) - } - } - } - - fn visit_seq<__A>(self, mut __seq: __A) -> _serde::__private::Result - where - __A: _serde::de::SeqAccess<#delife>, - { - // Visit the first element - the tag. - match _serde::de::SeqAccess::next_element(&mut __seq)? { - _serde::__private::Some(__field) => { - // Visit the second element - the content. - match _serde::de::SeqAccess::next_element_seed( - &mut __seq, - __Seed { - field: __field, - marker: _serde::__private::PhantomData, - lifetime: _serde::__private::PhantomData, - }, - )? { - _serde::__private::Some(__ret) => _serde::__private::Ok(__ret), - // There is no second element. - _serde::__private::None => { - _serde::__private::Err(_serde::de::Error::invalid_length(1, &self)) - } - } - } - // There is no first element. - _serde::__private::None => { - _serde::__private::Err(_serde::de::Error::invalid_length(0, &self)) - } - } - } - } - - #[doc(hidden)] - const FIELDS: &'static [&'static str] = &[#tag, #content]; - _serde::Deserializer::deserialize_struct( - __deserializer, - #type_name, - FIELDS, - __Visitor { - marker: _serde::__private::PhantomData::<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData, - }, - ) - } -} - -fn deserialize_untagged_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, -) -> Fragment { - let first_attempt = None; - deserialize_untagged_enum_after(params, variants, cattrs, first_attempt) -} - -fn deserialize_untagged_enum_after( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, - first_attempt: Option, -) -> Fragment { - let attempts = variants - .iter() - .filter(|variant| !variant.attrs.skip_deserializing()) - .map(|variant| { - Expr(deserialize_untagged_variant( - params, - variant, - cattrs, - quote!(__deserializer), - )) - }); - // TODO this message could be better by saving the errors from the failed - // attempts. The heuristic used by TOML was to count the number of fields - // processed before an error, and use the error that happened after the - // largest number of fields. I'm not sure I like that. Maybe it would be - // better to save all the errors and combine them into one message that - // explains why none of the variants matched. - let fallthrough_msg = format!( - "data did not match any variant of untagged enum {}", - params.type_name() - ); - let fallthrough_msg = cattrs.expecting().unwrap_or(&fallthrough_msg); - - // Ignore any error associated with non-untagged deserialization so that we - // can fall through to the untagged variants. This may be infallible so we - // need to provide the error type. - let first_attempt = first_attempt.map(|expr| { - quote! { - if let _serde::__private::Result::<_, __D::Error>::Ok(__ok) = (|| #expr)() { - return _serde::__private::Ok(__ok); - } - } - }); - - quote_block! { - let __content = <_serde::__private::de::Content as _serde::Deserialize>::deserialize(__deserializer)?; - let __deserializer = _serde::__private::de::ContentRefDeserializer::<__D::Error>::new(&__content); - - #first_attempt - - #( - if let _serde::__private::Ok(__ok) = #attempts { - return _serde::__private::Ok(__ok); - } - )* - - _serde::__private::Err(_serde::de::Error::custom(#fallthrough_msg)) - } -} - -fn deserialize_externally_tagged_variant( - params: &Parameters, - variant: &Variant, - cattrs: &attr::Container, -) -> Fragment { - if let Some(path) = variant.attrs.deserialize_with() { - let (wrapper, wrapper_ty, unwrap_fn) = wrap_deserialize_variant_with(params, variant, path); - return quote_block! { - #wrapper - _serde::__private::Result::map( - _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), #unwrap_fn) - }; - } - - let variant_ident = &variant.ident; - - match variant.style { - Style::Unit => { - let this_value = ¶ms.this_value; - quote_block! { - _serde::de::VariantAccess::unit_variant(__variant)?; - _serde::__private::Ok(#this_value::#variant_ident) - } - } - Style::Newtype => deserialize_externally_tagged_newtype_variant( - variant_ident, - params, - &variant.fields[0], - cattrs, - ), - Style::Tuple => deserialize_tuple( - params, - &variant.fields, - cattrs, - TupleForm::ExternallyTagged(variant_ident), - ), - Style::Struct => deserialize_struct( - params, - &variant.fields, - cattrs, - StructForm::ExternallyTagged(variant_ident), - ), - } -} - -// Generates significant part of the visit_seq and visit_map bodies of visitors -// for the variants of internally tagged enum. -fn deserialize_internally_tagged_variant( - params: &Parameters, - variant: &Variant, - cattrs: &attr::Container, - deserializer: TokenStream, -) -> Fragment { - if variant.attrs.deserialize_with().is_some() { - return deserialize_untagged_variant(params, variant, cattrs, deserializer); - } - - let variant_ident = &variant.ident; - - match effective_style(variant) { - Style::Unit => { - let this_value = ¶ms.this_value; - let type_name = params.type_name(); - let variant_name = variant.ident.to_string(); - let default = variant.fields.first().map(|field| { - let default = Expr(expr_is_missing(field, cattrs)); - quote!((#default)) - }); - quote_block! { - _serde::Deserializer::deserialize_any(#deserializer, _serde::__private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name))?; - _serde::__private::Ok(#this_value::#variant_ident #default) - } - } - Style::Newtype => deserialize_untagged_newtype_variant( - variant_ident, - params, - &variant.fields[0], - &deserializer, - ), - Style::Struct => deserialize_struct( - params, - &variant.fields, - cattrs, - StructForm::InternallyTagged(variant_ident, deserializer), - ), - Style::Tuple => unreachable!("checked in serde_derive_internals"), - } -} - -fn deserialize_untagged_variant( - params: &Parameters, - variant: &Variant, - cattrs: &attr::Container, - deserializer: TokenStream, -) -> Fragment { - if let Some(path) = variant.attrs.deserialize_with() { - let unwrap_fn = unwrap_to_variant_closure(params, variant, false); - return quote_block! { - _serde::__private::Result::map(#path(#deserializer), #unwrap_fn) - }; - } - - let variant_ident = &variant.ident; - - match effective_style(variant) { - Style::Unit => { - let this_value = ¶ms.this_value; - let type_name = params.type_name(); - let variant_name = variant.ident.to_string(); - let default = variant.fields.first().map(|field| { - let default = Expr(expr_is_missing(field, cattrs)); - quote!((#default)) - }); - quote_expr! { - match _serde::Deserializer::deserialize_any( - #deserializer, - _serde::__private::de::UntaggedUnitVisitor::new(#type_name, #variant_name) - ) { - _serde::__private::Ok(()) => _serde::__private::Ok(#this_value::#variant_ident #default), - _serde::__private::Err(__err) => _serde::__private::Err(__err), - } - } - } - Style::Newtype => deserialize_untagged_newtype_variant( - variant_ident, - params, - &variant.fields[0], - &deserializer, - ), - Style::Tuple => deserialize_tuple( - params, - &variant.fields, - cattrs, - TupleForm::Untagged(variant_ident, deserializer), - ), - Style::Struct => deserialize_struct( - params, - &variant.fields, - cattrs, - StructForm::Untagged(variant_ident, deserializer), - ), - } -} - -fn deserialize_externally_tagged_newtype_variant( - variant_ident: &syn::Ident, - params: &Parameters, - field: &Field, - cattrs: &attr::Container, -) -> Fragment { - let this_value = ¶ms.this_value; - - if field.attrs.skip_deserializing() { - let default = Expr(expr_is_missing(field, cattrs)); - return quote_block! { - _serde::de::VariantAccess::unit_variant(__variant)?; - _serde::__private::Ok(#this_value::#variant_ident(#default)) - }; - } - - match field.attrs.deserialize_with() { - None => { - let field_ty = field.ty; - let span = field.original.span(); - let func = - quote_spanned!(span=> _serde::de::VariantAccess::newtype_variant::<#field_ty>); - quote_expr! { - _serde::__private::Result::map(#func(__variant), #this_value::#variant_ident) - } - } - Some(path) => { - let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); - quote_block! { - #wrapper - _serde::__private::Result::map( - _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), - |__wrapper| #this_value::#variant_ident(__wrapper.value)) - } - } - } -} - -fn deserialize_untagged_newtype_variant( - variant_ident: &syn::Ident, - params: &Parameters, - field: &Field, - deserializer: &TokenStream, -) -> Fragment { - let this_value = ¶ms.this_value; - let field_ty = field.ty; - match field.attrs.deserialize_with() { - None => { - let span = field.original.span(); - let func = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize); - quote_expr! { - _serde::__private::Result::map(#func(#deserializer), #this_value::#variant_ident) - } - } - Some(path) => { - quote_block! { - let __value: _serde::__private::Result<#field_ty, _> = #path(#deserializer); - _serde::__private::Result::map(__value, #this_value::#variant_ident) - } - } - } -} - -fn deserialize_generated_identifier( - fields: &[(&str, Ident, &BTreeSet)], - has_flatten: bool, - is_variant: bool, - ignore_variant: Option, - fallthrough: Option, -) -> Fragment { - let this_value = quote!(__Field); - let field_idents: &Vec<_> = &fields.iter().map(|(_, ident, _)| ident).collect(); - - let visitor_impl = Stmts(deserialize_identifier( - &this_value, - fields, - is_variant, - fallthrough, - None, - !is_variant && has_flatten, - None, - )); - - let lifetime = if !is_variant && has_flatten { - Some(quote!(<'de>)) - } else { - None - }; - - quote_block! { - #[allow(non_camel_case_types)] - #[doc(hidden)] - enum __Field #lifetime { - #(#field_idents,)* - #ignore_variant - } - - #[doc(hidden)] - struct __FieldVisitor; - - impl<'de> _serde::de::Visitor<'de> for __FieldVisitor { - type Value = __Field #lifetime; - - #visitor_impl - } - - impl<'de> _serde::Deserialize<'de> for __Field #lifetime { - #[inline] - fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result - where - __D: _serde::Deserializer<'de>, - { - _serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor) - } - } - } -} - -/// Generates enum and its `Deserialize` implementation that represents each -/// non-skipped field of the struct -fn deserialize_field_identifier( - fields: &[(&str, Ident, &BTreeSet)], - cattrs: &attr::Container, - has_flatten: bool, -) -> Stmts { - let (ignore_variant, fallthrough) = if has_flatten { - let ignore_variant = quote!(__other(_serde::__private::de::Content<'de>),); - let fallthrough = quote!(_serde::__private::Ok(__Field::__other(__value))); - (Some(ignore_variant), Some(fallthrough)) - } else if cattrs.deny_unknown_fields() { - (None, None) - } else { - let ignore_variant = quote!(__ignore,); - let fallthrough = quote!(_serde::__private::Ok(__Field::__ignore)); - (Some(ignore_variant), Some(fallthrough)) - }; - - Stmts(deserialize_generated_identifier( - fields, - has_flatten, - false, - ignore_variant, - fallthrough, - )) -} - -// Generates `Deserialize::deserialize` body for an enum with -// `serde(field_identifier)` or `serde(variant_identifier)` attribute. -fn deserialize_custom_identifier( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, -) -> Fragment { - let is_variant = match cattrs.identifier() { - attr::Identifier::Variant => true, - attr::Identifier::Field => false, - attr::Identifier::No => unreachable!(), - }; - - let this_type = params.this_type.to_token_stream(); - let this_value = params.this_value.to_token_stream(); - - let (ordinary, fallthrough, fallthrough_borrowed) = if let Some(last) = variants.last() { - let last_ident = &last.ident; - if last.attrs.other() { - // Process `serde(other)` attribute. It would always be found on the - // last variant (checked in `check_identifier`), so all preceding - // are ordinary variants. - let ordinary = &variants[..variants.len() - 1]; - let fallthrough = quote!(_serde::__private::Ok(#this_value::#last_ident)); - (ordinary, Some(fallthrough), None) - } else if let Style::Newtype = last.style { - let ordinary = &variants[..variants.len() - 1]; - let fallthrough = |value| { - quote! { - _serde::__private::Result::map( - _serde::Deserialize::deserialize( - _serde::__private::de::IdentifierDeserializer::from(#value) - ), - #this_value::#last_ident) - } - }; - ( - ordinary, - Some(fallthrough(quote!(__value))), - Some(fallthrough(quote!(_serde::__private::de::Borrowed( - __value - )))), - ) - } else { - (variants, None, None) - } - } else { - (variants, None, None) - }; - - let names_idents: Vec<_> = ordinary - .iter() - .map(|variant| { - ( - variant.attrs.name().deserialize_name(), - variant.ident.clone(), - variant.attrs.aliases(), - ) - }) - .collect(); - - let names = names_idents.iter().flat_map(|&(_, _, aliases)| aliases); - - let names_const = if fallthrough.is_some() { - None - } else if is_variant { - let variants = quote! { - #[doc(hidden)] - const VARIANTS: &'static [&'static str] = &[ #(#names),* ]; - }; - Some(variants) - } else { - let fields = quote! { - #[doc(hidden)] - const FIELDS: &'static [&'static str] = &[ #(#names),* ]; - }; - Some(fields) - }; - - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - let visitor_impl = Stmts(deserialize_identifier( - &this_value, - &names_idents, - is_variant, - fallthrough, - fallthrough_borrowed, - false, - cattrs.expecting(), - )); - - quote_block! { - #names_const - - #[doc(hidden)] - struct __FieldVisitor #de_impl_generics #where_clause { - marker: _serde::__private::PhantomData<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __FieldVisitor #de_ty_generics #where_clause { - type Value = #this_type #ty_generics; - - #visitor_impl - } - - let __visitor = __FieldVisitor { - marker: _serde::__private::PhantomData::<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData, - }; - _serde::Deserializer::deserialize_identifier(__deserializer, __visitor) - } -} - -fn deserialize_identifier( - this_value: &TokenStream, - fields: &[(&str, Ident, &BTreeSet)], - is_variant: bool, - fallthrough: Option, - fallthrough_borrowed: Option, - collect_other_fields: bool, - expecting: Option<&str>, -) -> Fragment { - let str_mapping = fields.iter().map(|(_, ident, aliases)| { - // `aliases` also contains a main name - quote!(#(#aliases)|* => _serde::__private::Ok(#this_value::#ident)) - }); - let bytes_mapping = fields.iter().map(|(_, ident, aliases)| { - // `aliases` also contains a main name - let aliases = aliases - .iter() - .map(|alias| Literal::byte_string(alias.as_bytes())); - quote!(#(#aliases)|* => _serde::__private::Ok(#this_value::#ident)) - }); - - let expecting = expecting.unwrap_or(if is_variant { - "variant identifier" - } else { - "field identifier" - }); - - let bytes_to_str = if fallthrough.is_some() || collect_other_fields { - None - } else { - Some(quote! { - let __value = &_serde::__private::from_utf8_lossy(__value); - }) - }; - - let ( - value_as_str_content, - value_as_borrowed_str_content, - value_as_bytes_content, - value_as_borrowed_bytes_content, - ) = if collect_other_fields { - ( - Some(quote! { - let __value = _serde::__private::de::Content::String(_serde::__private::ToString::to_string(__value)); - }), - Some(quote! { - let __value = _serde::__private::de::Content::Str(__value); - }), - Some(quote! { - let __value = _serde::__private::de::Content::ByteBuf(__value.to_vec()); - }), - Some(quote! { - let __value = _serde::__private::de::Content::Bytes(__value); - }), - ) - } else { - (None, None, None, None) - }; - - let fallthrough_arm_tokens; - let fallthrough_arm = if let Some(fallthrough) = &fallthrough { - fallthrough - } else if is_variant { - fallthrough_arm_tokens = quote! { - _serde::__private::Err(_serde::de::Error::unknown_variant(__value, VARIANTS)) - }; - &fallthrough_arm_tokens - } else { - fallthrough_arm_tokens = quote! { - _serde::__private::Err(_serde::de::Error::unknown_field(__value, FIELDS)) - }; - &fallthrough_arm_tokens - }; - - let visit_other = if collect_other_fields { - quote! { - fn visit_bool<__E>(self, __value: bool) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Bool(__value))) - } - - fn visit_i8<__E>(self, __value: i8) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I8(__value))) - } - - fn visit_i16<__E>(self, __value: i16) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I16(__value))) - } - - fn visit_i32<__E>(self, __value: i32) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I32(__value))) - } - - fn visit_i64<__E>(self, __value: i64) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I64(__value))) - } - - fn visit_u8<__E>(self, __value: u8) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U8(__value))) - } - - fn visit_u16<__E>(self, __value: u16) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U16(__value))) - } - - fn visit_u32<__E>(self, __value: u32) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U32(__value))) - } - - fn visit_u64<__E>(self, __value: u64) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U64(__value))) - } - - fn visit_f32<__E>(self, __value: f32) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::F32(__value))) - } - - fn visit_f64<__E>(self, __value: f64) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::F64(__value))) - } - - fn visit_char<__E>(self, __value: char) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Char(__value))) - } - - fn visit_unit<__E>(self) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Unit)) - } - } - } else { - let u64_mapping = fields.iter().enumerate().map(|(i, (_, ident, _))| { - let i = i as u64; - quote!(#i => _serde::__private::Ok(#this_value::#ident)) - }); - - let u64_fallthrough_arm_tokens; - let u64_fallthrough_arm = if let Some(fallthrough) = &fallthrough { - fallthrough - } else { - let index_expecting = if is_variant { "variant" } else { "field" }; - let fallthrough_msg = format!("{} index 0 <= i < {}", index_expecting, fields.len()); - u64_fallthrough_arm_tokens = quote! { - _serde::__private::Err(_serde::de::Error::invalid_value( - _serde::de::Unexpected::Unsigned(__value), - &#fallthrough_msg, - )) - }; - &u64_fallthrough_arm_tokens - }; - - quote! { - fn visit_u64<__E>(self, __value: u64) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - match __value { - #(#u64_mapping,)* - _ => #u64_fallthrough_arm, - } - } - } - }; - - let visit_borrowed = if fallthrough_borrowed.is_some() || collect_other_fields { - let str_mapping = str_mapping.clone(); - let bytes_mapping = bytes_mapping.clone(); - let fallthrough_borrowed_arm = fallthrough_borrowed.as_ref().unwrap_or(fallthrough_arm); - Some(quote! { - fn visit_borrowed_str<__E>(self, __value: &'de str) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - match __value { - #(#str_mapping,)* - _ => { - #value_as_borrowed_str_content - #fallthrough_borrowed_arm - } - } - } - - fn visit_borrowed_bytes<__E>(self, __value: &'de [u8]) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - match __value { - #(#bytes_mapping,)* - _ => { - #bytes_to_str - #value_as_borrowed_bytes_content - #fallthrough_borrowed_arm - } - } - } - }) - } else { - None - }; - - quote_block! { - fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { - _serde::__private::Formatter::write_str(__formatter, #expecting) - } - - #visit_other - - fn visit_str<__E>(self, __value: &str) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - match __value { - #(#str_mapping,)* - _ => { - #value_as_str_content - #fallthrough_arm - } - } - } - - fn visit_bytes<__E>(self, __value: &[u8]) -> _serde::__private::Result - where - __E: _serde::de::Error, - { - match __value { - #(#bytes_mapping,)* - _ => { - #bytes_to_str - #value_as_bytes_content - #fallthrough_arm - } - } - } - - #visit_borrowed - } -} - -fn deserialize_map( - struct_path: &TokenStream, - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, - has_flatten: bool, -) -> Fragment { - // Create the field names for the fields. - let fields_names: Vec<_> = fields - .iter() - .enumerate() - .map(|(i, field)| (field, field_i(i))) - .collect(); - - // Declare each field that will be deserialized. - let let_values = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) - .map(|(field, name)| { - let field_ty = field.ty; - quote! { - let mut #name: _serde::__private::Option<#field_ty> = _serde::__private::None; - } - }); - - // Collect contents for flatten fields into a buffer - let let_collect = if has_flatten { - Some(quote! { - let mut __collect = _serde::__private::Vec::<_serde::__private::Option<( - _serde::__private::de::Content, - _serde::__private::de::Content - )>>::new(); - }) - } else { - None - }; - - // Match arms to extract a value for a field. - let value_arms = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) - .map(|(field, name)| { - let deser_name = field.attrs.name().deserialize_name(); - - let visit = match field.attrs.deserialize_with() { - None => { - let field_ty = field.ty; - let span = field.original.span(); - let func = - quote_spanned!(span=> _serde::de::MapAccess::next_value::<#field_ty>); - quote! { - #func(&mut __map)? - } - } - Some(path) => { - let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); - quote!({ - #wrapper - match _serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map) { - _serde::__private::Ok(__wrapper) => __wrapper.value, - _serde::__private::Err(__err) => { - return _serde::__private::Err(__err); - } - } - }) - } - }; - quote! { - __Field::#name => { - if _serde::__private::Option::is_some(&#name) { - return _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); - } - #name = _serde::__private::Some(#visit); - } - } - }); - - // Visit ignored values to consume them - let ignored_arm = if has_flatten { - Some(quote! { - __Field::__other(__name) => { - __collect.push(_serde::__private::Some(( - __name, - _serde::de::MapAccess::next_value(&mut __map)?))); - } - }) - } else if cattrs.deny_unknown_fields() { - None - } else { - Some(quote! { - _ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; } - }) - }; - - let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); - let match_keys = if cattrs.deny_unknown_fields() && all_skipped { - quote! { - // FIXME: Once feature(exhaustive_patterns) is stable: - // let _serde::__private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?; - _serde::__private::Option::map( - _serde::de::MapAccess::next_key::<__Field>(&mut __map)?, - |__impossible| match __impossible {}); - } - } else { - quote! { - while let _serde::__private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&mut __map)? { - match __key { - #(#value_arms)* - #ignored_arm - } - } - } - }; - - let extract_values = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) - .map(|(field, name)| { - let missing_expr = Match(expr_is_missing(field, cattrs)); - - quote! { - let #name = match #name { - _serde::__private::Some(#name) => #name, - _serde::__private::None => #missing_expr - }; - } - }); - - let extract_collected = fields_names - .iter() - .filter(|&&(field, _)| field.attrs.flatten() && !field.attrs.skip_deserializing()) - .map(|(field, name)| { - let field_ty = field.ty; - let func = match field.attrs.deserialize_with() { - None => { - let span = field.original.span(); - quote_spanned!(span=> _serde::de::Deserialize::deserialize) - } - Some(path) => quote!(#path), - }; - quote! { - let #name: #field_ty = #func( - _serde::__private::de::FlatMapDeserializer( - &mut __collect, - _serde::__private::PhantomData))?; - } - }); - - let collected_deny_unknown_fields = if has_flatten && cattrs.deny_unknown_fields() { - Some(quote! { - if let _serde::__private::Some(_serde::__private::Some((__key, _))) = - __collect.into_iter().filter(_serde::__private::Option::is_some).next() - { - if let _serde::__private::Some(__key) = __key.as_str() { - return _serde::__private::Err( - _serde::de::Error::custom(format_args!("unknown field `{}`", &__key))); - } else { - return _serde::__private::Err( - _serde::de::Error::custom(format_args!("unexpected map key"))); - } - } - }) - } else { - None - }; - - let result = fields_names.iter().map(|(field, name)| { - let member = &field.member; - if field.attrs.skip_deserializing() { - let value = Expr(expr_is_missing(field, cattrs)); - quote!(#member: #value) - } else { - quote!(#member: #name) - } - }); - - let let_default = match cattrs.default() { - attr::Default::Default => Some(quote!( - let __default: Self::Value = _serde::__private::Default::default(); - )), - attr::Default::Path(path) => Some(quote!( - let __default: Self::Value = #path(); - )), - attr::Default::None => { - // We don't need the default value, to prevent an unused variable warning - // we'll leave the line empty. - None - } - }; - - let mut result = quote!(#struct_path { #(#result),* }); - if params.has_getter { - let this_type = ¶ms.this_type; - let (_, ty_generics, _) = params.generics.split_for_impl(); - result = quote! { - _serde::__private::Into::<#this_type #ty_generics>::into(#result) - }; - } - - quote_block! { - #(#let_values)* - - #let_collect - - #match_keys - - #let_default - - #(#extract_values)* - - #(#extract_collected)* - - #collected_deny_unknown_fields - - _serde::__private::Ok(#result) - } -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_map_in_place( - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, -) -> Fragment { - assert!( - !has_flatten(fields), - "inplace deserialization of maps does not support flatten fields" - ); - - // Create the field names for the fields. - let fields_names: Vec<_> = fields - .iter() - .enumerate() - .map(|(i, field)| (field, field_i(i))) - .collect(); - - // For deserialize_in_place, declare booleans for each field that will be - // deserialized. - let let_flags = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing()) - .map(|(_, name)| { - quote! { - let mut #name: bool = false; - } - }); - - // Match arms to extract a value for a field. - let value_arms_from = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing()) - .map(|(field, name)| { - let deser_name = field.attrs.name().deserialize_name(); - let member = &field.member; - - let visit = match field.attrs.deserialize_with() { - None => { - quote! { - _serde::de::MapAccess::next_value_seed(&mut __map, _serde::__private::de::InPlaceSeed(&mut self.place.#member))? - } - } - Some(path) => { - let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); - quote!({ - #wrapper - self.place.#member = match _serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map) { - _serde::__private::Ok(__wrapper) => __wrapper.value, - _serde::__private::Err(__err) => { - return _serde::__private::Err(__err); - } - }; - }) - } - }; - quote! { - __Field::#name => { - if #name { - return _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); - } - #visit; - #name = true; - } - } - }); - - // Visit ignored values to consume them - let ignored_arm = if cattrs.deny_unknown_fields() { - None - } else { - Some(quote! { - _ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; } - }) - }; - - let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); - - let match_keys = if cattrs.deny_unknown_fields() && all_skipped { - quote! { - // FIXME: Once feature(exhaustive_patterns) is stable: - // let _serde::__private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?; - _serde::__private::Option::map( - _serde::de::MapAccess::next_key::<__Field>(&mut __map)?, - |__impossible| match __impossible {}); - } - } else { - quote! { - while let _serde::__private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&mut __map)? { - match __key { - #(#value_arms_from)* - #ignored_arm - } - } - } - }; - - let check_flags = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing()) - .map(|(field, name)| { - let missing_expr = expr_is_missing(field, cattrs); - // If missing_expr unconditionally returns an error, don't try - // to assign its value to self.place. - if field.attrs.default().is_none() - && cattrs.default().is_none() - && field.attrs.deserialize_with().is_some() - { - let missing_expr = Stmts(missing_expr); - quote! { - if !#name { - #missing_expr; - } - } - } else { - let member = &field.member; - let missing_expr = Expr(missing_expr); - quote! { - if !#name { - self.place.#member = #missing_expr; - }; - } - } - }); - - let this_type = ¶ms.this_type; - let (_, _, ty_generics, _) = split_with_de_lifetime(params); - - let let_default = match cattrs.default() { - attr::Default::Default => Some(quote!( - let __default: #this_type #ty_generics = _serde::__private::Default::default(); - )), - attr::Default::Path(path) => Some(quote!( - let __default: #this_type #ty_generics = #path(); - )), - attr::Default::None => { - // We don't need the default value, to prevent an unused variable warning - // we'll leave the line empty. - None - } - }; - - quote_block! { - #(#let_flags)* - - #match_keys - - #let_default - - #(#check_flags)* - - _serde::__private::Ok(()) - } -} - -fn field_i(i: usize) -> Ident { - Ident::new(&format!("__field{}", i), Span::call_site()) -} - -/// This function wraps the expression in `#[serde(deserialize_with = "...")]` -/// in a trait to prevent it from accessing the internal `Deserialize` state. -fn wrap_deserialize_with( - params: &Parameters, - value_ty: &TokenStream, - deserialize_with: &syn::ExprPath, -) -> (TokenStream, TokenStream) { - let this_type = ¶ms.this_type; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let wrapper = quote! { - #[doc(hidden)] - struct __DeserializeWith #de_impl_generics #where_clause { - value: #value_ty, - phantom: _serde::__private::PhantomData<#this_type #ty_generics>, - lifetime: _serde::__private::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause { - fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result - where - __D: _serde::Deserializer<#delife>, - { - _serde::__private::Ok(__DeserializeWith { - value: #deserialize_with(__deserializer)?, - phantom: _serde::__private::PhantomData, - lifetime: _serde::__private::PhantomData, - }) - } - } - }; - - let wrapper_ty = quote!(__DeserializeWith #de_ty_generics); - - (wrapper, wrapper_ty) -} - -fn wrap_deserialize_field_with( - params: &Parameters, - field_ty: &syn::Type, - deserialize_with: &syn::ExprPath, -) -> (TokenStream, TokenStream) { - wrap_deserialize_with(params, "e!(#field_ty), deserialize_with) -} - -fn wrap_deserialize_variant_with( - params: &Parameters, - variant: &Variant, - deserialize_with: &syn::ExprPath, -) -> (TokenStream, TokenStream, TokenStream) { - let field_tys = variant.fields.iter().map(|field| field.ty); - let (wrapper, wrapper_ty) = - wrap_deserialize_with(params, "e!((#(#field_tys),*)), deserialize_with); - - let unwrap_fn = unwrap_to_variant_closure(params, variant, true); - - (wrapper, wrapper_ty, unwrap_fn) -} - -// Generates closure that converts single input parameter to the final value. -fn unwrap_to_variant_closure( - params: &Parameters, - variant: &Variant, - with_wrapper: bool, -) -> TokenStream { - let this_value = ¶ms.this_value; - let variant_ident = &variant.ident; - - let (arg, wrapper) = if with_wrapper { - (quote! { __wrap }, quote! { __wrap.value }) - } else { - let field_tys = variant.fields.iter().map(|field| field.ty); - (quote! { __wrap: (#(#field_tys),*) }, quote! { __wrap }) - }; - - let field_access = (0..variant.fields.len()).map(|n| { - Member::Unnamed(Index { - index: n as u32, - span: Span::call_site(), - }) - }); - - match variant.style { - Style::Struct if variant.fields.len() == 1 => { - let member = &variant.fields[0].member; - quote! { - |#arg| #this_value::#variant_ident { #member: #wrapper } + |#arg| #this_value::#variant_ident { #member: #wrapper } } } Style::Struct => { @@ -2957,11 +764,15 @@ fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment { match field.attrs.default() { attr::Default::Default => { let span = field.original.span(); - let func = quote_spanned!(span=> _serde::__private::Default::default); + let func = quote_spanned!(span=> _serde::#private::Default::default); return quote_expr!(#func()); } attr::Default::Path(path) => { - return quote_expr!(#path()); + // If #path returns wrong type, error will be reported here (^^^^^). + // We attach span of the path to the function so it will be reported + // on the #[serde(default = "...")] + // ^^^^^ + return Fragment::Expr(quote_spanned!(path.span()=> #path())); } attr::Default::None => { /* below */ } } @@ -2978,14 +789,14 @@ fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment { match field.attrs.deserialize_with() { None => { let span = field.original.span(); - let func = quote_spanned!(span=> _serde::__private::de::missing_field); + let func = quote_spanned!(span=> _serde::#private::de::missing_field); quote_expr! { #func(#name)? } } Some(_) => { quote_expr! { - return _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#name)) + return _serde::#private::Err(<__A::Error as _serde::de::Error>::missing_field(#name)) } } } @@ -3001,9 +812,13 @@ fn expr_is_missing_seq( match field.attrs.default() { attr::Default::Default => { let span = field.original.span(); - return quote_spanned!(span=> #assign_to _serde::__private::Default::default()); + return quote_spanned!(span=> #assign_to _serde::#private::Default::default()); } attr::Default::Path(path) => { + // If #path returns wrong type, error will be reported here (^^^^^). + // We attach span of the path to the function so it will be reported + // on the #[serde(default = "...")] + // ^^^^^ return quote_spanned!(path.span()=> #assign_to #path()); } attr::Default::None => { /* below */ } @@ -3015,7 +830,7 @@ fn expr_is_missing_seq( quote!(#assign_to __default.#member) } attr::Default::None => quote!( - return _serde::__private::Err(_serde::de::Error::invalid_length(#index, &#expecting)) + return _serde::#private::Err(_serde::de::Error::invalid_length(#index, &#expecting)) ), } } @@ -3156,17 +971,3 @@ fn place_lifetime() -> syn::LifetimeParam { bounds: Punctuated::new(), } } - -fn split_with_de_lifetime( - params: &Parameters, -) -> ( - DeImplGenerics, - DeTypeGenerics, - syn::TypeGenerics, - Option<&syn::WhereClause>, -) { - let de_impl_generics = DeImplGenerics(params); - let de_ty_generics = DeTypeGenerics(params); - let (_, ty_generics, where_clause) = params.generics.split_for_impl(); - (de_impl_generics, de_ty_generics, ty_generics, where_clause) -} diff --git a/pkg/installer/vendor/serde_derive/src/de/enum_.rs b/pkg/installer/vendor/serde_derive/src/de/enum_.rs new file mode 100644 index 00000000000..6f5094ff4f7 --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/de/enum_.rs @@ -0,0 +1,96 @@ +use crate::de::enum_adjacently; +use crate::de::enum_externally; +use crate::de::enum_internally; +use crate::de::enum_untagged; +use crate::de::identifier; +use crate::de::{field_i, FieldWithAliases, Parameters}; +use crate::fragment::{Expr, Fragment, Stmts}; +use crate::internals::ast::Variant; +use crate::internals::attr; +use crate::private; +use proc_macro2::TokenStream; +use quote::quote; + +/// Generates `Deserialize::deserialize` body for an `enum Enum {...}` +pub(super) fn deserialize( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + // The variants have already been checked (in ast.rs) that all untagged variants appear at the end + match variants.iter().position(|var| var.attrs.untagged()) { + Some(variant_idx) => { + let (tagged, untagged) = variants.split_at(variant_idx); + let tagged_frag = Expr(deserialize_homogeneous_enum(params, tagged, cattrs)); + // Ignore any error associated with non-untagged deserialization so that we + // can fall through to the untagged variants. This may be infallible so we + // need to provide the error type. + let first_attempt = quote! { + if let _serde::#private::Result::<_, __D::Error>::Ok(__ok) = (|| #tagged_frag)() { + return _serde::#private::Ok(__ok); + } + }; + enum_untagged::deserialize(params, untagged, cattrs, Some(first_attempt)) + } + None => deserialize_homogeneous_enum(params, variants, cattrs), + } +} + +fn deserialize_homogeneous_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + match cattrs.tag() { + attr::TagType::External => enum_externally::deserialize(params, variants, cattrs), + attr::TagType::Internal { tag } => { + enum_internally::deserialize(params, variants, cattrs, tag) + } + attr::TagType::Adjacent { tag, content } => { + enum_adjacently::deserialize(params, variants, cattrs, tag, content) + } + attr::TagType::None => enum_untagged::deserialize(params, variants, cattrs, None), + } +} + +pub fn prepare_enum_variant_enum(variants: &[Variant]) -> (TokenStream, Stmts) { + let deserialized_variants = variants + .iter() + .enumerate() + .filter(|&(_i, variant)| !variant.attrs.skip_deserializing()); + + let fallthrough = deserialized_variants + .clone() + .find(|(_i, variant)| variant.attrs.other()) + .map(|(i, _variant)| { + let ignore_variant = field_i(i); + quote!(_serde::#private::Ok(__Field::#ignore_variant)) + }); + + let variants_stmt = { + let variant_names = deserialized_variants + .clone() + .flat_map(|(_i, variant)| variant.attrs.aliases()); + quote! { + #[doc(hidden)] + const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; + } + }; + + let deserialized_variants: Vec<_> = deserialized_variants + .map(|(i, variant)| FieldWithAliases { + ident: field_i(i), + aliases: variant.attrs.aliases(), + }) + .collect(); + + let variant_visitor = Stmts(identifier::deserialize_generated( + &deserialized_variants, + false, // variant identifiers do not depend on the presence of flatten fields + true, + None, + fallthrough, + )); + + (variants_stmt, variant_visitor) +} diff --git a/pkg/installer/vendor/serde_derive/src/de/enum_adjacently.rs b/pkg/installer/vendor/serde_derive/src/de/enum_adjacently.rs new file mode 100644 index 00000000000..467cfc0d753 --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/de/enum_adjacently.rs @@ -0,0 +1,323 @@ +//! Deserialization for adjacently tagged enums: +//! +//! ```ignore +//! #[serde(tag = "...", content = "...")] +//! enum Enum {} +//! ``` + +use crate::de::enum_; +use crate::de::enum_untagged; +use crate::de::{field_i, Parameters}; +use crate::fragment::{Fragment, Match}; +use crate::internals::ast::{Style, Variant}; +use crate::internals::attr; +use crate::private; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; + +/// Generates `Deserialize::deserialize` body for an `enum Enum {...}` with `#[serde(tag, content)]` attributes +pub(super) fn deserialize( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, + tag: &str, + content: &str, +) -> Fragment { + let this_type = ¶ms.this_type; + let this_value = ¶ms.this_value; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + params.generics_with_de_lifetime(); + let delife = params.borrowed.de_lifetime(); + + let (variants_stmt, variant_visitor) = enum_::prepare_enum_variant_enum(variants); + + let variant_arms: &Vec<_> = &variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| { + let variant_index = field_i(i); + + let block = Match(enum_untagged::deserialize_variant(params, variant, cattrs)); + + quote! { + __Field::#variant_index => #block + } + }) + .collect(); + + let rust_name = params.type_name(); + let expecting = format!("adjacently tagged enum {}", rust_name); + let expecting = cattrs.expecting().unwrap_or(&expecting); + let type_name = cattrs.name().deserialize_name(); + let deny_unknown_fields = cattrs.deny_unknown_fields(); + + // If unknown fields are allowed, we pick the visitor that can step over + // those. Otherwise we pick the visitor that fails on unknown keys. + let field_visitor_ty = if deny_unknown_fields { + quote! { _serde::#private::de::TagOrContentFieldVisitor } + } else { + quote! { _serde::#private::de::TagContentOtherFieldVisitor } + }; + + let mut missing_content = quote! { + _serde::#private::Err(<__A::Error as _serde::de::Error>::missing_field(#content)) + }; + let mut missing_content_fallthrough = quote!(); + let missing_content_arms = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .filter_map(|(i, variant)| { + let variant_index = field_i(i); + let variant_ident = &variant.ident; + + let arm = match variant.style { + Style::Unit => quote! { + _serde::#private::Ok(#this_value::#variant_ident) + }, + Style::Newtype if variant.attrs.deserialize_with().is_none() => { + let span = variant.original.span(); + let func = quote_spanned!(span=> _serde::#private::de::missing_field); + quote! { + #func(#content).map(#this_value::#variant_ident) + } + } + _ => { + missing_content_fallthrough = quote!(_ => #missing_content); + return None; + } + }; + Some(quote! { + __Field::#variant_index => #arm, + }) + }) + .collect::>(); + if !missing_content_arms.is_empty() { + missing_content = quote! { + match __field { + #(#missing_content_arms)* + #missing_content_fallthrough + } + }; + } + + // Advance the map by one key, returning early in case of error. + let next_key = quote! { + _serde::de::MapAccess::next_key_seed(&mut __map, #field_visitor_ty { + tag: #tag, + content: #content, + })? + }; + + let variant_from_map = quote! { + _serde::de::MapAccess::next_value_seed(&mut __map, _serde::#private::de::AdjacentlyTaggedEnumVariantSeed::<__Field> { + enum_name: #rust_name, + variants: VARIANTS, + fields_enum: _serde::#private::PhantomData + })? + }; + + // When allowing unknown fields, we want to transparently step through keys + // we don't care about until we find `tag`, `content`, or run out of keys. + let next_relevant_key = if deny_unknown_fields { + next_key + } else { + quote!({ + let mut __rk : _serde::#private::Option<_serde::#private::de::TagOrContentField> = _serde::#private::None; + while let _serde::#private::Some(__k) = #next_key { + match __k { + _serde::#private::de::TagContentOtherField::Other => { + let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; + continue; + }, + _serde::#private::de::TagContentOtherField::Tag => { + __rk = _serde::#private::Some(_serde::#private::de::TagOrContentField::Tag); + break; + } + _serde::#private::de::TagContentOtherField::Content => { + __rk = _serde::#private::Some(_serde::#private::de::TagOrContentField::Content); + break; + } + } + } + + __rk + }) + }; + + // Step through remaining keys, looking for duplicates of previously-seen + // keys. When unknown fields are denied, any key that isn't a duplicate will + // at this point immediately produce an error. + let visit_remaining_keys = quote! { + match #next_relevant_key { + _serde::#private::Some(_serde::#private::de::TagOrContentField::Tag) => { + _serde::#private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) + } + _serde::#private::Some(_serde::#private::de::TagOrContentField::Content) => { + _serde::#private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) + } + _serde::#private::None => _serde::#private::Ok(__ret), + } + }; + + let finish_content_then_tag = if variant_arms.is_empty() { + quote! { + match #variant_from_map {} + } + } else { + quote! { + let __seed = __Seed { + variant: #variant_from_map, + marker: _serde::#private::PhantomData, + lifetime: _serde::#private::PhantomData, + }; + let __deserializer = _serde::#private::de::ContentDeserializer::<__A::Error>::new(__content); + let __ret = _serde::de::DeserializeSeed::deserialize(__seed, __deserializer)?; + // Visit remaining keys, looking for duplicates. + #visit_remaining_keys + } + }; + + quote_block! { + #variant_visitor + + #variants_stmt + + #[doc(hidden)] + struct __Seed #de_impl_generics #where_clause { + variant: __Field, + marker: _serde::#private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } + + #[automatically_derived] + impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Seed #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn deserialize<__D>(self, __deserializer: __D) -> _serde::#private::Result + where + __D: _serde::Deserializer<#delife>, + { + match self.variant { + #(#variant_arms)* + } + } + } + + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::#private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } + + #[automatically_derived] + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::#private::Formatter) -> _serde::#private::fmt::Result { + _serde::#private::Formatter::write_str(__formatter, #expecting) + } + + fn visit_map<__A>(self, mut __map: __A) -> _serde::#private::Result + where + __A: _serde::de::MapAccess<#delife>, + { + // Visit the first relevant key. + match #next_relevant_key { + // First key is the tag. + _serde::#private::Some(_serde::#private::de::TagOrContentField::Tag) => { + // Parse the tag. + let __field = #variant_from_map; + // Visit the second key. + match #next_relevant_key { + // Second key is a duplicate of the tag. + _serde::#private::Some(_serde::#private::de::TagOrContentField::Tag) => { + _serde::#private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) + } + // Second key is the content. + _serde::#private::Some(_serde::#private::de::TagOrContentField::Content) => { + let __ret = _serde::de::MapAccess::next_value_seed(&mut __map, + __Seed { + variant: __field, + marker: _serde::#private::PhantomData, + lifetime: _serde::#private::PhantomData, + })?; + // Visit remaining keys, looking for duplicates. + #visit_remaining_keys + } + // There is no second key; might be okay if the we have a unit variant. + _serde::#private::None => #missing_content + } + } + // First key is the content. + _serde::#private::Some(_serde::#private::de::TagOrContentField::Content) => { + // Buffer up the content. + let __content = _serde::de::MapAccess::next_value_seed(&mut __map, _serde::#private::de::ContentVisitor::new())?; + // Visit the second key. + match #next_relevant_key { + // Second key is the tag. + _serde::#private::Some(_serde::#private::de::TagOrContentField::Tag) => { + #finish_content_then_tag + } + // Second key is a duplicate of the content. + _serde::#private::Some(_serde::#private::de::TagOrContentField::Content) => { + _serde::#private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) + } + // There is no second key. + _serde::#private::None => { + _serde::#private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) + } + } + } + // There is no first key. + _serde::#private::None => { + _serde::#private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) + } + } + } + + fn visit_seq<__A>(self, mut __seq: __A) -> _serde::#private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + // Visit the first element - the tag. + match _serde::de::SeqAccess::next_element(&mut __seq)? { + _serde::#private::Some(__variant) => { + // Visit the second element - the content. + match _serde::de::SeqAccess::next_element_seed( + &mut __seq, + __Seed { + variant: __variant, + marker: _serde::#private::PhantomData, + lifetime: _serde::#private::PhantomData, + }, + )? { + _serde::#private::Some(__ret) => _serde::#private::Ok(__ret), + // There is no second element. + _serde::#private::None => { + _serde::#private::Err(_serde::de::Error::invalid_length(1, &self)) + } + } + } + // There is no first element. + _serde::#private::None => { + _serde::#private::Err(_serde::de::Error::invalid_length(0, &self)) + } + } + } + } + + #[doc(hidden)] + const FIELDS: &'static [&'static str] = &[#tag, #content]; + _serde::Deserializer::deserialize_struct( + __deserializer, + #type_name, + FIELDS, + __Visitor { + marker: _serde::#private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData, + }, + ) + } +} diff --git a/pkg/installer/vendor/serde_derive/src/de/enum_externally.rs b/pkg/installer/vendor/serde_derive/src/de/enum_externally.rs new file mode 100644 index 00000000000..9e5bde3d8b6 --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/de/enum_externally.rs @@ -0,0 +1,212 @@ +//! Deserialization for externally tagged enums: +//! +//! ```ignore +//! enum Enum {} +//! ``` + +use crate::de::enum_; +use crate::de::struct_; +use crate::de::tuple; +use crate::de::{ + expr_is_missing, field_i, unwrap_to_variant_closure, wrap_deserialize_field_with, + wrap_deserialize_with, Parameters, StructForm, TupleForm, +}; +use crate::fragment::{Expr, Fragment, Match}; +use crate::internals::ast::{Field, Style, Variant}; +use crate::internals::attr; +use crate::private; +use proc_macro2::TokenStream; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; + +/// Generates `Deserialize::deserialize` body for an `enum Enum {...}` without additional attributes +pub(super) fn deserialize( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + let this_type = ¶ms.this_type; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + params.generics_with_de_lifetime(); + let delife = params.borrowed.de_lifetime(); + + let type_name = cattrs.name().deserialize_name(); + let expecting = format!("enum {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let (variants_stmt, variant_visitor) = enum_::prepare_enum_variant_enum(variants); + + // Match arms to extract a variant from a string + let variant_arms = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| { + let variant_name = field_i(i); + + let block = Match(deserialize_externally_tagged_variant( + params, variant, cattrs, + )); + + quote! { + (__Field::#variant_name, __variant) => #block + } + }); + + let all_skipped = variants + .iter() + .all(|variant| variant.attrs.skip_deserializing()); + let match_variant = if all_skipped { + // This is an empty enum like `enum Impossible {}` or an enum in which + // all variants have `#[serde(skip_deserializing)]`. + quote! { + // FIXME: Once feature(exhaustive_patterns) is stable: + // let _serde::#private::Err(__err) = _serde::de::EnumAccess::variant::<__Field>(__data); + // _serde::#private::Err(__err) + _serde::#private::Result::map( + _serde::de::EnumAccess::variant::<__Field>(__data), + |(__impossible, _)| match __impossible {}) + } + } else { + quote! { + match _serde::de::EnumAccess::variant(__data)? { + #(#variant_arms)* + } + } + }; + + quote_block! { + #variant_visitor + + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::#private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } + + #[automatically_derived] + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::#private::Formatter) -> _serde::#private::fmt::Result { + _serde::#private::Formatter::write_str(__formatter, #expecting) + } + + fn visit_enum<__A>(self, __data: __A) -> _serde::#private::Result + where + __A: _serde::de::EnumAccess<#delife>, + { + #match_variant + } + } + + #variants_stmt + + _serde::Deserializer::deserialize_enum( + __deserializer, + #type_name, + VARIANTS, + __Visitor { + marker: _serde::#private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData, + }, + ) + } +} + +fn deserialize_externally_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, +) -> Fragment { + if let Some(path) = variant.attrs.deserialize_with() { + let (wrapper, wrapper_ty, unwrap_fn) = wrap_deserialize_variant_with(params, variant, path); + return quote_block! { + #wrapper + _serde::#private::Result::map( + _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), #unwrap_fn) + }; + } + + let variant_ident = &variant.ident; + + match variant.style { + Style::Unit => { + let this_value = ¶ms.this_value; + quote_block! { + _serde::de::VariantAccess::unit_variant(__variant)?; + _serde::#private::Ok(#this_value::#variant_ident) + } + } + Style::Newtype => deserialize_externally_tagged_newtype_variant( + variant_ident, + params, + &variant.fields[0], + cattrs, + ), + Style::Tuple => tuple::deserialize( + params, + &variant.fields, + cattrs, + TupleForm::ExternallyTagged(variant_ident), + ), + Style::Struct => struct_::deserialize( + params, + &variant.fields, + cattrs, + StructForm::ExternallyTagged(variant_ident), + ), + } +} + +fn wrap_deserialize_variant_with( + params: &Parameters, + variant: &Variant, + deserialize_with: &syn::ExprPath, +) -> (TokenStream, TokenStream, TokenStream) { + let field_tys = variant.fields.iter().map(|field| field.ty); + let (wrapper, wrapper_ty) = + wrap_deserialize_with(params, "e!((#(#field_tys),*)), deserialize_with); + + let unwrap_fn = unwrap_to_variant_closure(params, variant, true); + + (wrapper, wrapper_ty, unwrap_fn) +} + +fn deserialize_externally_tagged_newtype_variant( + variant_ident: &syn::Ident, + params: &Parameters, + field: &Field, + cattrs: &attr::Container, +) -> Fragment { + let this_value = ¶ms.this_value; + + if field.attrs.skip_deserializing() { + let default = Expr(expr_is_missing(field, cattrs)); + return quote_block! { + _serde::de::VariantAccess::unit_variant(__variant)?; + _serde::#private::Ok(#this_value::#variant_ident(#default)) + }; + } + + match field.attrs.deserialize_with() { + None => { + let field_ty = field.ty; + let span = field.original.span(); + let func = + quote_spanned!(span=> _serde::de::VariantAccess::newtype_variant::<#field_ty>); + quote_expr! { + _serde::#private::Result::map(#func(__variant), #this_value::#variant_ident) + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote_block! { + #wrapper + _serde::#private::Result::map( + _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), + |__wrapper| #this_value::#variant_ident(__wrapper.value)) + } + } + } +} diff --git a/pkg/installer/vendor/serde_derive/src/de/enum_internally.rs b/pkg/installer/vendor/serde_derive/src/de/enum_internally.rs new file mode 100644 index 00000000000..b669eef7e81 --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/de/enum_internally.rs @@ -0,0 +1,106 @@ +//! Deserialization for internally tagged enums: +//! +//! ```ignore +//! #[serde(tag = "...")] +//! enum Enum {} +//! ``` + +use crate::de::enum_; +use crate::de::enum_untagged; +use crate::de::struct_; +use crate::de::{ + effective_style, expr_is_missing, field_i, unwrap_to_variant_closure, Parameters, StructForm, +}; +use crate::fragment::{Expr, Fragment, Match}; +use crate::internals::ast::{Style, Variant}; +use crate::internals::attr; +use crate::private; +use quote::quote; + +/// Generates `Deserialize::deserialize` body for an `enum Enum {...}` with `#[serde(tag)]` attribute +pub(super) fn deserialize( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, + tag: &str, +) -> Fragment { + let (variants_stmt, variant_visitor) = enum_::prepare_enum_variant_enum(variants); + + // Match arms to extract a variant from a string + let variant_arms = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| { + let variant_name = field_i(i); + + let block = Match(deserialize_internally_tagged_variant( + params, variant, cattrs, + )); + + quote! { + __Field::#variant_name => #block + } + }); + + let expecting = format!("internally tagged enum {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + quote_block! { + #variant_visitor + + #variants_stmt + + let (__tag, __content) = _serde::Deserializer::deserialize_any( + __deserializer, + _serde::#private::de::TaggedContentVisitor::<__Field>::new(#tag, #expecting))?; + let __deserializer = _serde::#private::de::ContentDeserializer::<__D::Error>::new(__content); + + match __tag { + #(#variant_arms)* + } + } +} + +// Generates significant part of the visit_seq and visit_map bodies of visitors +// for the variants of internally tagged enum. +fn deserialize_internally_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, +) -> Fragment { + if let Some(path) = variant.attrs.deserialize_with() { + let unwrap_fn = unwrap_to_variant_closure(params, variant, false); + return quote_block! { + _serde::#private::Result::map(#path(__deserializer), #unwrap_fn) + }; + } + + let variant_ident = &variant.ident; + + match effective_style(variant) { + Style::Unit => { + let this_value = ¶ms.this_value; + let type_name = params.type_name(); + let variant_name = variant.ident.to_string(); + let default = variant.fields.first().map(|field| { + let default = Expr(expr_is_missing(field, cattrs)); + quote!((#default)) + }); + quote_block! { + _serde::Deserializer::deserialize_any(__deserializer, _serde::#private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name))?; + _serde::#private::Ok(#this_value::#variant_ident #default) + } + } + Style::Newtype => { + enum_untagged::deserialize_newtype_variant(variant_ident, params, &variant.fields[0]) + } + Style::Struct => struct_::deserialize( + params, + &variant.fields, + cattrs, + StructForm::InternallyTagged(variant_ident), + ), + Style::Tuple => unreachable!("checked in serde_derive_internals"), + } +} diff --git a/pkg/installer/vendor/serde_derive/src/de/enum_untagged.rs b/pkg/installer/vendor/serde_derive/src/de/enum_untagged.rs new file mode 100644 index 00000000000..f66d98de1f8 --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/de/enum_untagged.rs @@ -0,0 +1,135 @@ +//! Deserialization for untagged enums: +//! +//! ```ignore +//! #[serde(untagged)] +//! enum Enum {} +//! ``` + +use crate::de::struct_; +use crate::de::tuple; +use crate::de::{ + effective_style, expr_is_missing, unwrap_to_variant_closure, Parameters, StructForm, TupleForm, +}; +use crate::fragment::{Expr, Fragment}; +use crate::internals::ast::{Field, Style, Variant}; +use crate::internals::attr; +use crate::private; +use proc_macro2::TokenStream; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; + +/// Generates `Deserialize::deserialize` body for an `enum Enum {...}` with `#[serde(untagged)]` attribute +pub(super) fn deserialize( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, + first_attempt: Option, +) -> Fragment { + let attempts = variants + .iter() + .filter(|variant| !variant.attrs.skip_deserializing()) + .map(|variant| Expr(deserialize_variant(params, variant, cattrs))); + // TODO this message could be better by saving the errors from the failed + // attempts. The heuristic used by TOML was to count the number of fields + // processed before an error, and use the error that happened after the + // largest number of fields. I'm not sure I like that. Maybe it would be + // better to save all the errors and combine them into one message that + // explains why none of the variants matched. + let fallthrough_msg = format!( + "data did not match any variant of untagged enum {}", + params.type_name() + ); + let fallthrough_msg = cattrs.expecting().unwrap_or(&fallthrough_msg); + + let private2 = private; + quote_block! { + let __content = _serde::de::DeserializeSeed::deserialize(_serde::#private::de::ContentVisitor::new(), __deserializer)?; + let __deserializer = _serde::#private::de::ContentRefDeserializer::<__D::Error>::new(&__content); + + #first_attempt + + #( + if let _serde::#private2::Ok(__ok) = #attempts { + return _serde::#private2::Ok(__ok); + } + )* + + _serde::#private::Err(_serde::de::Error::custom(#fallthrough_msg)) + } +} + +// Also used by adjacently tagged enums +pub(super) fn deserialize_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, +) -> Fragment { + if let Some(path) = variant.attrs.deserialize_with() { + let unwrap_fn = unwrap_to_variant_closure(params, variant, false); + return quote_block! { + _serde::#private::Result::map(#path(__deserializer), #unwrap_fn) + }; + } + + let variant_ident = &variant.ident; + + match effective_style(variant) { + Style::Unit => { + let this_value = ¶ms.this_value; + let type_name = params.type_name(); + let variant_name = variant.ident.to_string(); + let default = variant.fields.first().map(|field| { + let default = Expr(expr_is_missing(field, cattrs)); + quote!((#default)) + }); + quote_expr! { + match _serde::Deserializer::deserialize_any( + __deserializer, + _serde::#private::de::UntaggedUnitVisitor::new(#type_name, #variant_name) + ) { + _serde::#private::Ok(()) => _serde::#private::Ok(#this_value::#variant_ident #default), + _serde::#private::Err(__err) => _serde::#private::Err(__err), + } + } + } + Style::Newtype => deserialize_newtype_variant(variant_ident, params, &variant.fields[0]), + Style::Tuple => tuple::deserialize( + params, + &variant.fields, + cattrs, + TupleForm::Untagged(variant_ident), + ), + Style::Struct => struct_::deserialize( + params, + &variant.fields, + cattrs, + StructForm::Untagged(variant_ident), + ), + } +} + +// Also used by internally tagged enums +// Implicitly (via `generate_variant`) used by adjacently tagged enums +pub(super) fn deserialize_newtype_variant( + variant_ident: &syn::Ident, + params: &Parameters, + field: &Field, +) -> Fragment { + let this_value = ¶ms.this_value; + let field_ty = field.ty; + match field.attrs.deserialize_with() { + None => { + let span = field.original.span(); + let func = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize); + quote_expr! { + _serde::#private::Result::map(#func(__deserializer), #this_value::#variant_ident) + } + } + Some(path) => { + quote_block! { + let __value: _serde::#private::Result<#field_ty, _> = #path(__deserializer); + _serde::#private::Result::map(__value, #this_value::#variant_ident) + } + } + } +} diff --git a/pkg/installer/vendor/serde_derive/src/de/identifier.rs b/pkg/installer/vendor/serde_derive/src/de/identifier.rs new file mode 100644 index 00000000000..8e67b96310c --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/de/identifier.rs @@ -0,0 +1,477 @@ +//! Deserialization of struct field identifiers and enum variant identifiers by +//! way of a Rust enum. + +use crate::de::{FieldWithAliases, Parameters}; +use crate::fragment::{Fragment, Stmts}; +use crate::internals::ast::{Style, Variant}; +use crate::internals::attr; +use crate::private; +use proc_macro2::{Literal, TokenStream}; +use quote::{quote, ToTokens}; + +// Generates `Deserialize::deserialize` body for an enum with +// `serde(field_identifier)` or `serde(variant_identifier)` attribute. +pub(super) fn deserialize_custom( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + let is_variant = match cattrs.identifier() { + attr::Identifier::Variant => true, + attr::Identifier::Field => false, + attr::Identifier::No => unreachable!(), + }; + + let this_type = params.this_type.to_token_stream(); + let this_value = params.this_value.to_token_stream(); + + let (ordinary, fallthrough, fallthrough_borrowed) = if let Some(last) = variants.last() { + let last_ident = &last.ident; + if last.attrs.other() { + // Process `serde(other)` attribute. It would always be found on the + // last variant (checked in `check_identifier`), so all preceding + // are ordinary variants. + let ordinary = &variants[..variants.len() - 1]; + let fallthrough = quote!(_serde::#private::Ok(#this_value::#last_ident)); + (ordinary, Some(fallthrough), None) + } else if let Style::Newtype = last.style { + let ordinary = &variants[..variants.len() - 1]; + let fallthrough = |value| { + quote! { + _serde::#private::Result::map( + _serde::Deserialize::deserialize( + _serde::#private::de::IdentifierDeserializer::from(#value) + ), + #this_value::#last_ident) + } + }; + ( + ordinary, + Some(fallthrough(quote!(__value))), + Some(fallthrough(quote!(_serde::#private::de::Borrowed( + __value + )))), + ) + } else { + (variants, None, None) + } + } else { + (variants, None, None) + }; + + let idents_aliases: Vec<_> = ordinary + .iter() + .map(|variant| FieldWithAliases { + ident: variant.ident.clone(), + aliases: variant.attrs.aliases(), + }) + .collect(); + + let names = idents_aliases.iter().flat_map(|variant| variant.aliases); + + let names_const = if fallthrough.is_some() { + None + } else if is_variant { + let variants = quote! { + #[doc(hidden)] + const VARIANTS: &'static [&'static str] = &[ #(#names),* ]; + }; + Some(variants) + } else { + let fields = quote! { + #[doc(hidden)] + const FIELDS: &'static [&'static str] = &[ #(#names),* ]; + }; + Some(fields) + }; + + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + params.generics_with_de_lifetime(); + let delife = params.borrowed.de_lifetime(); + let visitor_impl = Stmts(deserialize_identifier( + &this_value, + &idents_aliases, + is_variant, + fallthrough, + fallthrough_borrowed, + false, + cattrs.expecting(), + )); + + quote_block! { + #names_const + + #[doc(hidden)] + struct __FieldVisitor #de_impl_generics #where_clause { + marker: _serde::#private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } + + #[automatically_derived] + impl #de_impl_generics _serde::de::Visitor<#delife> for __FieldVisitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + #visitor_impl + } + + let __visitor = __FieldVisitor { + marker: _serde::#private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData, + }; + _serde::Deserializer::deserialize_identifier(__deserializer, __visitor) + } +} + +pub(super) fn deserialize_generated( + deserialized_fields: &[FieldWithAliases], + has_flatten: bool, + is_variant: bool, + ignore_variant: Option, + fallthrough: Option, +) -> Fragment { + let this_value = quote!(__Field); + let field_idents: &Vec<_> = &deserialized_fields + .iter() + .map(|field| &field.ident) + .collect(); + + let visitor_impl = Stmts(deserialize_identifier( + &this_value, + deserialized_fields, + is_variant, + fallthrough, + None, + !is_variant && has_flatten, + None, + )); + + let lifetime = if !is_variant && has_flatten { + Some(quote!(<'de>)) + } else { + None + }; + + quote_block! { + #[allow(non_camel_case_types)] + #[doc(hidden)] + enum __Field #lifetime { + #(#field_idents,)* + #ignore_variant + } + + #[doc(hidden)] + struct __FieldVisitor; + + #[automatically_derived] + impl<'de> _serde::de::Visitor<'de> for __FieldVisitor { + type Value = __Field #lifetime; + + #visitor_impl + } + + #[automatically_derived] + impl<'de> _serde::Deserialize<'de> for __Field #lifetime { + #[inline] + fn deserialize<__D>(__deserializer: __D) -> _serde::#private::Result + where + __D: _serde::Deserializer<'de>, + { + _serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor) + } + } + } +} + +fn deserialize_identifier( + this_value: &TokenStream, + deserialized_fields: &[FieldWithAliases], + is_variant: bool, + fallthrough: Option, + fallthrough_borrowed: Option, + collect_other_fields: bool, + expecting: Option<&str>, +) -> Fragment { + let str_mapping = deserialized_fields.iter().map(|field| { + let ident = &field.ident; + let aliases = field.aliases; + let private2 = private; + // `aliases` also contains a main name + quote! { + #( + #aliases => _serde::#private2::Ok(#this_value::#ident), + )* + } + }); + let bytes_mapping = deserialized_fields.iter().map(|field| { + let ident = &field.ident; + // `aliases` also contains a main name + let aliases = field + .aliases + .iter() + .map(|alias| Literal::byte_string(alias.value.as_bytes())); + let private2 = private; + quote! { + #( + #aliases => _serde::#private2::Ok(#this_value::#ident), + )* + } + }); + + let expecting = expecting.unwrap_or(if is_variant { + "variant identifier" + } else { + "field identifier" + }); + + let bytes_to_str = if fallthrough.is_some() || collect_other_fields { + None + } else { + Some(quote! { + let __value = &_serde::#private::from_utf8_lossy(__value); + }) + }; + + let ( + value_as_str_content, + value_as_borrowed_str_content, + value_as_bytes_content, + value_as_borrowed_bytes_content, + ) = if collect_other_fields { + ( + Some(quote! { + let __value = _serde::#private::de::Content::String(_serde::#private::ToString::to_string(__value)); + }), + Some(quote! { + let __value = _serde::#private::de::Content::Str(__value); + }), + Some(quote! { + let __value = _serde::#private::de::Content::ByteBuf(__value.to_vec()); + }), + Some(quote! { + let __value = _serde::#private::de::Content::Bytes(__value); + }), + ) + } else { + (None, None, None, None) + }; + + let fallthrough_arm_tokens; + let fallthrough_arm = if let Some(fallthrough) = &fallthrough { + fallthrough + } else if is_variant { + fallthrough_arm_tokens = quote! { + _serde::#private::Err(_serde::de::Error::unknown_variant(__value, VARIANTS)) + }; + &fallthrough_arm_tokens + } else { + fallthrough_arm_tokens = quote! { + _serde::#private::Err(_serde::de::Error::unknown_field(__value, FIELDS)) + }; + &fallthrough_arm_tokens + }; + + let visit_other = if collect_other_fields { + quote! { + fn visit_bool<__E>(self, __value: bool) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::Bool(__value))) + } + + fn visit_i8<__E>(self, __value: i8) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::I8(__value))) + } + + fn visit_i16<__E>(self, __value: i16) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::I16(__value))) + } + + fn visit_i32<__E>(self, __value: i32) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::I32(__value))) + } + + fn visit_i64<__E>(self, __value: i64) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::I64(__value))) + } + + fn visit_u8<__E>(self, __value: u8) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::U8(__value))) + } + + fn visit_u16<__E>(self, __value: u16) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::U16(__value))) + } + + fn visit_u32<__E>(self, __value: u32) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::U32(__value))) + } + + fn visit_u64<__E>(self, __value: u64) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::U64(__value))) + } + + fn visit_f32<__E>(self, __value: f32) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::F32(__value))) + } + + fn visit_f64<__E>(self, __value: f64) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::F64(__value))) + } + + fn visit_char<__E>(self, __value: char) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::Char(__value))) + } + + fn visit_unit<__E>(self) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(__Field::__other(_serde::#private::de::Content::Unit)) + } + } + } else { + let u64_mapping = deserialized_fields.iter().enumerate().map(|(i, field)| { + let i = i as u64; + let ident = &field.ident; + quote!(#i => _serde::#private::Ok(#this_value::#ident)) + }); + + let u64_fallthrough_arm_tokens; + let u64_fallthrough_arm = if let Some(fallthrough) = &fallthrough { + fallthrough + } else { + let index_expecting = if is_variant { "variant" } else { "field" }; + let fallthrough_msg = format!( + "{} index 0 <= i < {}", + index_expecting, + deserialized_fields.len(), + ); + u64_fallthrough_arm_tokens = quote! { + _serde::#private::Err(_serde::de::Error::invalid_value( + _serde::de::Unexpected::Unsigned(__value), + &#fallthrough_msg, + )) + }; + &u64_fallthrough_arm_tokens + }; + + quote! { + fn visit_u64<__E>(self, __value: u64) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#u64_mapping,)* + _ => #u64_fallthrough_arm, + } + } + } + }; + + let visit_borrowed = if fallthrough_borrowed.is_some() || collect_other_fields { + let str_mapping = str_mapping.clone(); + let bytes_mapping = bytes_mapping.clone(); + let fallthrough_borrowed_arm = fallthrough_borrowed.as_ref().unwrap_or(fallthrough_arm); + Some(quote! { + fn visit_borrowed_str<__E>(self, __value: &'de str) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#str_mapping)* + _ => { + #value_as_borrowed_str_content + #fallthrough_borrowed_arm + } + } + } + + fn visit_borrowed_bytes<__E>(self, __value: &'de [u8]) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#bytes_mapping)* + _ => { + #bytes_to_str + #value_as_borrowed_bytes_content + #fallthrough_borrowed_arm + } + } + } + }) + } else { + None + }; + + quote_block! { + fn expecting(&self, __formatter: &mut _serde::#private::Formatter) -> _serde::#private::fmt::Result { + _serde::#private::Formatter::write_str(__formatter, #expecting) + } + + #visit_other + + fn visit_str<__E>(self, __value: &str) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#str_mapping)* + _ => { + #value_as_str_content + #fallthrough_arm + } + } + } + + fn visit_bytes<__E>(self, __value: &[u8]) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#bytes_mapping)* + _ => { + #bytes_to_str + #value_as_bytes_content + #fallthrough_arm + } + } + } + + #visit_borrowed + } +} diff --git a/pkg/installer/vendor/serde_derive/src/de/struct_.rs b/pkg/installer/vendor/serde_derive/src/de/struct_.rs new file mode 100644 index 00000000000..6a5da232acd --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/de/struct_.rs @@ -0,0 +1,697 @@ +use crate::de::identifier; +use crate::de::{ + deserialize_seq, expr_is_missing, field_i, has_flatten, wrap_deserialize_field_with, + FieldWithAliases, Parameters, StructForm, +}; +#[cfg(feature = "deserialize_in_place")] +use crate::de::{deserialize_seq_in_place, place_lifetime}; +use crate::fragment::{Expr, Fragment, Match, Stmts}; +use crate::internals::ast::Field; +use crate::internals::attr; +use crate::private; +use proc_macro2::TokenStream; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; + +/// Generates `Deserialize::deserialize` body for a `struct Struct {...}` +pub(super) fn deserialize( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + form: StructForm, +) -> Fragment { + let this_type = ¶ms.this_type; + let this_value = ¶ms.this_value; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + params.generics_with_de_lifetime(); + let delife = params.borrowed.de_lifetime(); + + // If there are getters (implying private fields), construct the local type + // and use an `Into` conversion to get the remote type. If there are no + // getters then construct the target type directly. + let construct = if params.has_getter { + let local = ¶ms.local; + quote!(#local) + } else { + quote!(#this_value) + }; + + let type_path = match form { + StructForm::Struct => construct, + StructForm::ExternallyTagged(variant_ident) + | StructForm::InternallyTagged(variant_ident) + | StructForm::Untagged(variant_ident) => quote!(#construct::#variant_ident), + }; + let expecting = match form { + StructForm::Struct => format!("struct {}", params.type_name()), + StructForm::ExternallyTagged(variant_ident) + | StructForm::InternallyTagged(variant_ident) + | StructForm::Untagged(variant_ident) => { + format!("struct variant {}::{}", params.type_name(), variant_ident) + } + }; + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let deserialized_fields: Vec<_> = fields + .iter() + .enumerate() + // Skip fields that shouldn't be deserialized or that were flattened, + // so they don't appear in the storage in their literal form + .filter(|&(_, field)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|(i, field)| FieldWithAliases { + ident: field_i(i), + aliases: field.attrs.aliases(), + }) + .collect(); + + let has_flatten = has_flatten(fields); + let field_visitor = deserialize_field_identifier(&deserialized_fields, cattrs, has_flatten); + + // untagged struct variants do not get a visit_seq method. The same applies to + // structs that only have a map representation. + let visit_seq = match form { + StructForm::Untagged(_) => None, + _ if has_flatten => None, + _ => { + let mut_seq = if deserialized_fields.is_empty() { + quote!(_) + } else { + quote!(mut __seq) + }; + + let visit_seq = Stmts(deserialize_seq( + &type_path, params, fields, true, cattrs, expecting, + )); + + Some(quote! { + #[inline] + fn visit_seq<__A>(self, #mut_seq: __A) -> _serde::#private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + #visit_seq + } + }) + } + }; + let visit_map = Stmts(deserialize_map( + &type_path, + params, + fields, + cattrs, + has_flatten, + )); + + let visitor_seed = match form { + StructForm::ExternallyTagged(..) if has_flatten => Some(quote! { + #[automatically_derived] + impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn deserialize<__D>(self, __deserializer: __D) -> _serde::#private::Result + where + __D: _serde::Deserializer<#delife>, + { + _serde::Deserializer::deserialize_map(__deserializer, self) + } + } + }), + _ => None, + }; + + let fields_stmt = if has_flatten { + None + } else { + let field_names = deserialized_fields.iter().flat_map(|field| field.aliases); + + Some(quote! { + #[doc(hidden)] + const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; + }) + }; + + let visitor_expr = quote! { + __Visitor { + marker: _serde::#private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData, + } + }; + let dispatch = match form { + StructForm::Struct if has_flatten => quote! { + _serde::Deserializer::deserialize_map(__deserializer, #visitor_expr) + }, + StructForm::Struct => { + let type_name = cattrs.name().deserialize_name(); + quote! { + _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, #visitor_expr) + } + } + StructForm::ExternallyTagged(_) if has_flatten => quote! { + _serde::de::VariantAccess::newtype_variant_seed(__variant, #visitor_expr) + }, + StructForm::ExternallyTagged(_) => quote! { + _serde::de::VariantAccess::struct_variant(__variant, FIELDS, #visitor_expr) + }, + StructForm::InternallyTagged(_) => quote! { + _serde::Deserializer::deserialize_any(__deserializer, #visitor_expr) + }, + StructForm::Untagged(_) => quote! { + _serde::Deserializer::deserialize_any(__deserializer, #visitor_expr) + }, + }; + + quote_block! { + #field_visitor + + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::#private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } + + #[automatically_derived] + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::#private::Formatter) -> _serde::#private::fmt::Result { + _serde::#private::Formatter::write_str(__formatter, #expecting) + } + + #visit_seq + + #[inline] + fn visit_map<__A>(self, mut __map: __A) -> _serde::#private::Result + where + __A: _serde::de::MapAccess<#delife>, + { + #visit_map + } + } + + #visitor_seed + + #fields_stmt + + #dispatch + } +} + +fn deserialize_map( + struct_path: &TokenStream, + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + has_flatten: bool, +) -> Fragment { + // Create the field names for the fields. + let fields_names: Vec<_> = fields + .iter() + .enumerate() + .map(|(i, field)| (field, field_i(i))) + .collect(); + + // Declare each field that will be deserialized. + let let_values = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|(field, name)| { + let field_ty = field.ty; + quote! { + let mut #name: _serde::#private::Option<#field_ty> = _serde::#private::None; + } + }); + + // Collect contents for flatten fields into a buffer + let let_collect = if has_flatten { + Some(quote! { + let mut __collect = _serde::#private::Vec::<_serde::#private::Option<( + _serde::#private::de::Content, + _serde::#private::de::Content + )>>::new(); + }) + } else { + None + }; + + // Match arms to extract a value for a field. + let value_arms = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|(field, name)| { + let deser_name = field.attrs.name().deserialize_name(); + + let visit = match field.attrs.deserialize_with() { + None => { + let field_ty = field.ty; + let span = field.original.span(); + let func = + quote_spanned!(span=> _serde::de::MapAccess::next_value::<#field_ty>); + quote! { + #func(&mut __map)? + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + match _serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map) { + _serde::#private::Ok(__wrapper) => __wrapper.value, + _serde::#private::Err(__err) => { + return _serde::#private::Err(__err); + } + } + }) + } + }; + quote! { + __Field::#name => { + if _serde::#private::Option::is_some(&#name) { + return _serde::#private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); + } + #name = _serde::#private::Some(#visit); + } + } + }); + + // Visit ignored values to consume them + let ignored_arm = if has_flatten { + Some(quote! { + __Field::__other(__name) => { + __collect.push(_serde::#private::Some(( + __name, + _serde::de::MapAccess::next_value_seed(&mut __map, _serde::#private::de::ContentVisitor::new())?))); + } + }) + } else if cattrs.deny_unknown_fields() { + None + } else { + Some(quote! { + _ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; } + }) + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + let match_keys = if cattrs.deny_unknown_fields() && all_skipped { + quote! { + // FIXME: Once feature(exhaustive_patterns) is stable: + // let _serde::#private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?; + _serde::#private::Option::map( + _serde::de::MapAccess::next_key::<__Field>(&mut __map)?, + |__impossible| match __impossible {}); + } + } else { + quote! { + while let _serde::#private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&mut __map)? { + match __key { + #(#value_arms)* + #ignored_arm + } + } + } + }; + + let extract_values = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|(field, name)| { + let missing_expr = Match(expr_is_missing(field, cattrs)); + + quote! { + let #name = match #name { + _serde::#private::Some(#name) => #name, + _serde::#private::None => #missing_expr + }; + } + }); + + let extract_collected = fields_names + .iter() + .filter(|&&(field, _)| field.attrs.flatten() && !field.attrs.skip_deserializing()) + .map(|(field, name)| { + let field_ty = field.ty; + let func = match field.attrs.deserialize_with() { + None => { + let span = field.original.span(); + quote_spanned!(span=> _serde::de::Deserialize::deserialize) + } + Some(path) => quote!(#path), + }; + quote! { + let #name: #field_ty = #func( + _serde::#private::de::FlatMapDeserializer( + &mut __collect, + _serde::#private::PhantomData))?; + } + }); + + let collected_deny_unknown_fields = if has_flatten && cattrs.deny_unknown_fields() { + Some(quote! { + if let _serde::#private::Some(_serde::#private::Some((__key, _))) = + __collect.into_iter().filter(_serde::#private::Option::is_some).next() + { + if let _serde::#private::Some(__key) = _serde::#private::de::content_as_str(&__key) { + return _serde::#private::Err( + _serde::de::Error::custom(format_args!("unknown field `{}`", &__key))); + } else { + return _serde::#private::Err( + _serde::de::Error::custom(format_args!("unexpected map key"))); + } + } + }) + } else { + None + }; + + let result = fields_names.iter().map(|(field, name)| { + let member = &field.member; + if field.attrs.skip_deserializing() { + let value = Expr(expr_is_missing(field, cattrs)); + quote!(#member: #value) + } else { + quote!(#member: #name) + } + }); + + let let_default = match cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: Self::Value = _serde::#private::Default::default(); + )), + // If #path returns wrong type, error will be reported here (^^^^^). + // We attach span of the path to the function so it will be reported + // on the #[serde(default = "...")] + // ^^^^^ + attr::Default::Path(path) => Some(quote_spanned!(path.span()=> + let __default: Self::Value = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + let mut result = quote!(#struct_path { #(#result),* }); + if params.has_getter { + let this_type = ¶ms.this_type; + let (_, ty_generics, _) = params.generics.split_for_impl(); + result = quote! { + _serde::#private::Into::<#this_type #ty_generics>::into(#result) + }; + } + + quote_block! { + #(#let_values)* + + #let_collect + + #match_keys + + #let_default + + #(#extract_values)* + + #(#extract_collected)* + + #collected_deny_unknown_fields + + _serde::#private::Ok(#result) + } +} + +/// Generates `Deserialize::deserialize_in_place` body for a `struct Struct {...}` +#[cfg(feature = "deserialize_in_place")] +pub(super) fn deserialize_in_place( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Option { + // for now we do not support in_place deserialization for structs that + // are represented as map. + if has_flatten(fields) { + return None; + } + + let this_type = ¶ms.this_type; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + params.generics_with_de_lifetime(); + let delife = params.borrowed.de_lifetime(); + + let expecting = format!("struct {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let deserialized_fields: Vec<_> = fields + .iter() + .enumerate() + .filter(|&(_, field)| !field.attrs.skip_deserializing()) + .map(|(i, field)| FieldWithAliases { + ident: field_i(i), + aliases: field.attrs.aliases(), + }) + .collect(); + + let field_visitor = deserialize_field_identifier(&deserialized_fields, cattrs, false); + + let mut_seq = if deserialized_fields.is_empty() { + quote!(_) + } else { + quote!(mut __seq) + }; + let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs, expecting)); + let visit_map = Stmts(deserialize_map_in_place(params, fields, cattrs)); + let field_names = deserialized_fields.iter().flat_map(|field| field.aliases); + let type_name = cattrs.name().deserialize_name(); + + let in_place_impl_generics = de_impl_generics.in_place(); + let in_place_ty_generics = de_ty_generics.in_place(); + let place_life = place_lifetime(); + + Some(quote_block! { + #field_visitor + + #[doc(hidden)] + struct __Visitor #in_place_impl_generics #where_clause { + place: &#place_life mut #this_type #ty_generics, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } + + #[automatically_derived] + impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { + type Value = (); + + fn expecting(&self, __formatter: &mut _serde::#private::Formatter) -> _serde::#private::fmt::Result { + _serde::#private::Formatter::write_str(__formatter, #expecting) + } + + #[inline] + fn visit_seq<__A>(self, #mut_seq: __A) -> _serde::#private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + #visit_seq + } + + #[inline] + fn visit_map<__A>(self, mut __map: __A) -> _serde::#private::Result + where + __A: _serde::de::MapAccess<#delife>, + { + #visit_map + } + } + + #[doc(hidden)] + const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; + + _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, __Visitor { + place: __place, + lifetime: _serde::#private::PhantomData, + }) + }) +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_map_in_place( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + assert!( + !has_flatten(fields), + "inplace deserialization of maps does not support flatten fields" + ); + + // Create the field names for the fields. + let fields_names: Vec<_> = fields + .iter() + .enumerate() + .map(|(i, field)| (field, field_i(i))) + .collect(); + + // For deserialize_in_place, declare booleans for each field that will be + // deserialized. + let let_flags = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing()) + .map(|(_, name)| { + quote! { + let mut #name: bool = false; + } + }); + + // Match arms to extract a value for a field. + let value_arms_from = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing()) + .map(|(field, name)| { + let deser_name = field.attrs.name().deserialize_name(); + let member = &field.member; + + let visit = match field.attrs.deserialize_with() { + None => { + quote! { + _serde::de::MapAccess::next_value_seed(&mut __map, _serde::#private::de::InPlaceSeed(&mut self.place.#member))? + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + self.place.#member = match _serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map) { + _serde::#private::Ok(__wrapper) => __wrapper.value, + _serde::#private::Err(__err) => { + return _serde::#private::Err(__err); + } + }; + }) + } + }; + quote! { + __Field::#name => { + if #name { + return _serde::#private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); + } + #visit; + #name = true; + } + } + }); + + // Visit ignored values to consume them + let ignored_arm = if cattrs.deny_unknown_fields() { + None + } else { + Some(quote! { + _ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; } + }) + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + + let match_keys = if cattrs.deny_unknown_fields() && all_skipped { + quote! { + // FIXME: Once feature(exhaustive_patterns) is stable: + // let _serde::#private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?; + _serde::#private::Option::map( + _serde::de::MapAccess::next_key::<__Field>(&mut __map)?, + |__impossible| match __impossible {}); + } + } else { + quote! { + while let _serde::#private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&mut __map)? { + match __key { + #(#value_arms_from)* + #ignored_arm + } + } + } + }; + + let check_flags = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing()) + .map(|(field, name)| { + let missing_expr = expr_is_missing(field, cattrs); + // If missing_expr unconditionally returns an error, don't try + // to assign its value to self.place. + if field.attrs.default().is_none() + && cattrs.default().is_none() + && field.attrs.deserialize_with().is_some() + { + let missing_expr = Stmts(missing_expr); + quote! { + if !#name { + #missing_expr; + } + } + } else { + let member = &field.member; + let missing_expr = Expr(missing_expr); + quote! { + if !#name { + self.place.#member = #missing_expr; + }; + } + } + }); + + let this_type = ¶ms.this_type; + let (_, ty_generics, _) = params.generics.split_for_impl(); + + let let_default = match cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: #this_type #ty_generics = _serde::#private::Default::default(); + )), + // If #path returns wrong type, error will be reported here (^^^^^). + // We attach span of the path to the function so it will be reported + // on the #[serde(default = "...")] + // ^^^^^ + attr::Default::Path(path) => Some(quote_spanned!(path.span()=> + let __default: #this_type #ty_generics = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + quote_block! { + #(#let_flags)* + + #match_keys + + #let_default + + #(#check_flags)* + + _serde::#private::Ok(()) + } +} + +/// Generates enum and its `Deserialize` implementation that represents each +/// non-skipped field of the struct +fn deserialize_field_identifier( + deserialized_fields: &[FieldWithAliases], + cattrs: &attr::Container, + has_flatten: bool, +) -> Stmts { + let (ignore_variant, fallthrough) = if has_flatten { + let ignore_variant = quote!(__other(_serde::#private::de::Content<'de>),); + let fallthrough = quote!(_serde::#private::Ok(__Field::__other(__value))); + (Some(ignore_variant), Some(fallthrough)) + } else if cattrs.deny_unknown_fields() { + (None, None) + } else { + let ignore_variant = quote!(__ignore,); + let fallthrough = quote!(_serde::#private::Ok(__Field::__ignore)); + (Some(ignore_variant), Some(fallthrough)) + }; + + Stmts(identifier::deserialize_generated( + deserialized_fields, + has_flatten, + false, + ignore_variant, + fallthrough, + )) +} diff --git a/pkg/installer/vendor/serde_derive/src/de/tuple.rs b/pkg/installer/vendor/serde_derive/src/de/tuple.rs new file mode 100644 index 00000000000..a76089fe658 --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/de/tuple.rs @@ -0,0 +1,283 @@ +use crate::de::{deserialize_seq, has_flatten, Parameters, TupleForm}; +#[cfg(feature = "deserialize_in_place")] +use crate::de::{deserialize_seq_in_place, place_lifetime}; +use crate::fragment::{Fragment, Stmts}; +use crate::internals::ast::Field; +use crate::internals::attr; +use crate::private; +use proc_macro2::TokenStream; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; + +/// Generates `Deserialize::deserialize` body for a `struct Tuple(...);` including `struct Newtype(T);` +pub(super) fn deserialize( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + form: TupleForm, +) -> Fragment { + assert!( + !has_flatten(fields), + "tuples and tuple variants cannot have flatten fields" + ); + + let field_count = fields + .iter() + .filter(|field| !field.attrs.skip_deserializing()) + .count(); + + let this_type = ¶ms.this_type; + let this_value = ¶ms.this_value; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + params.generics_with_de_lifetime(); + let delife = params.borrowed.de_lifetime(); + + // If there are getters (implying private fields), construct the local type + // and use an `Into` conversion to get the remote type. If there are no + // getters then construct the target type directly. + let construct = if params.has_getter { + let local = ¶ms.local; + quote!(#local) + } else { + quote!(#this_value) + }; + + let type_path = match form { + TupleForm::Tuple => construct, + TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident) => { + quote!(#construct::#variant_ident) + } + }; + let expecting = match form { + TupleForm::Tuple => format!("tuple struct {}", params.type_name()), + TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident) => { + format!("tuple variant {}::{}", params.type_name(), variant_ident) + } + }; + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let nfields = fields.len(); + + let visit_newtype_struct = match form { + TupleForm::Tuple if nfields == 1 => { + Some(deserialize_newtype_struct(&type_path, params, &fields[0])) + } + _ => None, + }; + + let visit_seq = Stmts(deserialize_seq( + &type_path, params, fields, false, cattrs, expecting, + )); + + let visitor_expr = quote! { + __Visitor { + marker: _serde::#private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData, + } + }; + let dispatch = match form { + TupleForm::Tuple if nfields == 1 => { + let type_name = cattrs.name().deserialize_name(); + quote! { + _serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr) + } + } + TupleForm::Tuple => { + let type_name = cattrs.name().deserialize_name(); + quote! { + _serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #field_count, #visitor_expr) + } + } + TupleForm::ExternallyTagged(_) => quote! { + _serde::de::VariantAccess::tuple_variant(__variant, #field_count, #visitor_expr) + }, + TupleForm::Untagged(_) => quote! { + _serde::Deserializer::deserialize_tuple(__deserializer, #field_count, #visitor_expr) + }, + }; + + let visitor_var = if field_count == 0 { + quote!(_) + } else { + quote!(mut __seq) + }; + + quote_block! { + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::#private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } + + #[automatically_derived] + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::#private::Formatter) -> _serde::#private::fmt::Result { + _serde::#private::Formatter::write_str(__formatter, #expecting) + } + + #visit_newtype_struct + + #[inline] + fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::#private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + #visit_seq + } + } + + #dispatch + } +} + +fn deserialize_newtype_struct( + type_path: &TokenStream, + params: &Parameters, + field: &Field, +) -> TokenStream { + let delife = params.borrowed.de_lifetime(); + let field_ty = field.ty; + let deserializer_var = quote!(__e); + + let value = match field.attrs.deserialize_with() { + None => { + let span = field.original.span(); + let func = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize); + quote! { + #func(#deserializer_var)? + } + } + Some(path) => { + // If #path returns wrong type, error will be reported here (^^^^^). + // We attach span of the path to the function so it will be reported + // on the #[serde(with = "...")] + // ^^^^^ + quote_spanned! {path.span()=> + #path(#deserializer_var)? + } + } + }; + + let mut result = quote!(#type_path(__field0)); + if params.has_getter { + let this_type = ¶ms.this_type; + let (_, ty_generics, _) = params.generics.split_for_impl(); + result = quote! { + _serde::#private::Into::<#this_type #ty_generics>::into(#result) + }; + } + + quote! { + #[inline] + fn visit_newtype_struct<__E>(self, #deserializer_var: __E) -> _serde::#private::Result + where + __E: _serde::Deserializer<#delife>, + { + let __field0: #field_ty = #value; + _serde::#private::Ok(#result) + } + } +} + +/// Generates `Deserialize::deserialize_in_place` body for a `struct Tuple(...);` including `struct Newtype(T);` +#[cfg(feature = "deserialize_in_place")] +pub(super) fn deserialize_in_place( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + assert!( + !has_flatten(fields), + "tuples and tuple variants cannot have flatten fields" + ); + + let field_count = fields + .iter() + .filter(|field| !field.attrs.skip_deserializing()) + .count(); + + let this_type = ¶ms.this_type; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + params.generics_with_de_lifetime(); + let delife = params.borrowed.de_lifetime(); + + let expecting = format!("tuple struct {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let nfields = fields.len(); + + let visit_newtype_struct = if nfields == 1 { + // We do not generate deserialize_in_place if every field has a + // deserialize_with. + assert!(fields[0].attrs.deserialize_with().is_none()); + + Some(quote! { + #[inline] + fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::#private::Result + where + __E: _serde::Deserializer<#delife>, + { + _serde::Deserialize::deserialize_in_place(__e, &mut self.place.0) + } + }) + } else { + None + }; + + let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs, expecting)); + + let visitor_expr = quote! { + __Visitor { + place: __place, + lifetime: _serde::#private::PhantomData, + } + }; + + let type_name = cattrs.name().deserialize_name(); + let dispatch = if nfields == 1 { + quote!(_serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr)) + } else { + quote!(_serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #field_count, #visitor_expr)) + }; + + let visitor_var = if field_count == 0 { + quote!(_) + } else { + quote!(mut __seq) + }; + + let in_place_impl_generics = de_impl_generics.in_place(); + let in_place_ty_generics = de_ty_generics.in_place(); + let place_life = place_lifetime(); + + quote_block! { + #[doc(hidden)] + struct __Visitor #in_place_impl_generics #where_clause { + place: &#place_life mut #this_type #ty_generics, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } + + #[automatically_derived] + impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { + type Value = (); + + fn expecting(&self, __formatter: &mut _serde::#private::Formatter) -> _serde::#private::fmt::Result { + _serde::#private::Formatter::write_str(__formatter, #expecting) + } + + #visit_newtype_struct + + #[inline] + fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::#private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + #visit_seq + } + } + + #dispatch + } +} diff --git a/pkg/installer/vendor/serde_derive/src/de/unit.rs b/pkg/installer/vendor/serde_derive/src/de/unit.rs new file mode 100644 index 00000000000..0d15ef4db5c --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/de/unit.rs @@ -0,0 +1,52 @@ +use crate::de::Parameters; +use crate::fragment::Fragment; +use crate::internals::attr; +use crate::private; +use quote::quote; + +/// Generates `Deserialize::deserialize` body for a `struct Unit;` +pub(super) fn deserialize(params: &Parameters, cattrs: &attr::Container) -> Fragment { + let this_type = ¶ms.this_type; + let this_value = ¶ms.this_value; + let type_name = cattrs.name().deserialize_name(); + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + params.generics_with_de_lifetime(); + let delife = params.borrowed.de_lifetime(); + + let expecting = format!("unit struct {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + quote_block! { + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::#private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData<&#delife ()>, + } + + #[automatically_derived] + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::#private::Formatter) -> _serde::#private::fmt::Result { + _serde::#private::Formatter::write_str(__formatter, #expecting) + } + + #[inline] + fn visit_unit<__E>(self) -> _serde::#private::Result + where + __E: _serde::de::Error, + { + _serde::#private::Ok(#this_value) + } + } + + _serde::Deserializer::deserialize_unit_struct( + __deserializer, + #type_name, + __Visitor { + marker: _serde::#private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::#private::PhantomData, + }, + ) + } +} diff --git a/pkg/installer/vendor/serde_derive/src/deprecated.rs b/pkg/installer/vendor/serde_derive/src/deprecated.rs new file mode 100644 index 00000000000..3abdc1b25e2 --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/deprecated.rs @@ -0,0 +1,56 @@ +use proc_macro2::TokenStream; +use quote::quote; + +pub fn allow_deprecated(input: &syn::DeriveInput) -> Option { + if should_allow_deprecated(input) { + Some(quote! { #[allow(deprecated)] }) + } else { + None + } +} + +/// Determine if an `#[allow(deprecated)]` should be added to the derived impl. +/// +/// This should happen if the derive input or an enum variant it contains has +/// one of: +/// - `#[deprecated]` +/// - `#[allow(deprecated)]` +fn should_allow_deprecated(input: &syn::DeriveInput) -> bool { + if contains_deprecated(&input.attrs) { + return true; + } + if let syn::Data::Enum(data_enum) = &input.data { + for variant in &data_enum.variants { + if contains_deprecated(&variant.attrs) { + return true; + } + } + } + false +} + +/// Check whether the given attributes contains one of: +/// - `#[deprecated]` +/// - `#[allow(deprecated)]` +fn contains_deprecated(attrs: &[syn::Attribute]) -> bool { + for attr in attrs { + if attr.path().is_ident("deprecated") { + return true; + } + if let syn::Meta::List(meta_list) = &attr.meta { + if meta_list.path.is_ident("allow") { + let mut allow_deprecated = false; + let _ = meta_list.parse_nested_meta(|meta| { + if meta.path.is_ident("deprecated") { + allow_deprecated = true; + } + Ok(()) + }); + if allow_deprecated { + return true; + } + } + } + } + false +} diff --git a/pkg/installer/vendor/serde_derive/src/dummy.rs b/pkg/installer/vendor/serde_derive/src/dummy.rs index 095f950f3ef..e0bca647aca 100644 --- a/pkg/installer/vendor/serde_derive/src/dummy.rs +++ b/pkg/installer/vendor/serde_derive/src/dummy.rs @@ -14,9 +14,17 @@ pub fn wrap_in_const(serde_path: Option<&syn::Path>, code: TokenStream) -> Token quote! { #[doc(hidden)] - #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + #[allow( + non_upper_case_globals, + unused_attributes, + unused_qualifications, + clippy::absolute_paths, + )] const _: () = { #use_serde + + _serde::__require_serde_not_serde_core!(); + #code }; } diff --git a/pkg/installer/vendor/serde_derive/src/internals/ast.rs b/pkg/installer/vendor/serde_derive/src/internals/ast.rs index 3293823a7ef..5a760c65735 100644 --- a/pkg/installer/vendor/serde_derive/src/internals/ast.rs +++ b/pkg/installer/vendor/serde_derive/src/internals/ast.rs @@ -1,6 +1,7 @@ //! A Serde ast, parsed from the Syn ast and ready to generate Rust code. use crate::internals::{attr, check, Ctxt, Derive}; +use proc_macro2::Ident; use syn::punctuated::Punctuated; use syn::Token; @@ -62,13 +63,17 @@ impl<'a> Container<'a> { cx: &Ctxt, item: &'a syn::DeriveInput, derive: Derive, + private: &Ident, ) -> Option> { let attrs = attr::Container::from_ast(cx, item); let mut data = match &item.data { - syn::Data::Enum(data) => Data::Enum(enum_from_ast(cx, &data.variants, attrs.default())), + syn::Data::Enum(data) => { + Data::Enum(enum_from_ast(cx, &data.variants, attrs.default(), private)) + } syn::Data::Struct(data) => { - let (style, fields) = struct_from_ast(cx, &data.fields, None, attrs.default()); + let (style, fields) = + struct_from_ast(cx, &data.fields, None, attrs.default(), private); Data::Struct(style, fields) } syn::Data::Union(_) => { @@ -129,13 +134,19 @@ fn enum_from_ast<'a>( cx: &Ctxt, variants: &'a Punctuated, container_default: &attr::Default, + private: &Ident, ) -> Vec> { let variants: Vec = variants .iter() .map(|variant| { let attrs = attr::Variant::from_ast(cx, variant); - let (style, fields) = - struct_from_ast(cx, &variant.fields, Some(&attrs), container_default); + let (style, fields) = struct_from_ast( + cx, + &variant.fields, + Some(&attrs), + container_default, + private, + ); Variant { ident: variant.ident.clone(), attrs, @@ -165,19 +176,20 @@ fn struct_from_ast<'a>( fields: &'a syn::Fields, attrs: Option<&attr::Variant>, container_default: &attr::Default, + private: &Ident, ) -> (Style, Vec>) { match fields { syn::Fields::Named(fields) => ( Style::Struct, - fields_from_ast(cx, &fields.named, attrs, container_default), + fields_from_ast(cx, &fields.named, attrs, container_default, private), ), syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => ( Style::Newtype, - fields_from_ast(cx, &fields.unnamed, attrs, container_default), + fields_from_ast(cx, &fields.unnamed, attrs, container_default, private), ), syn::Fields::Unnamed(fields) => ( Style::Tuple, - fields_from_ast(cx, &fields.unnamed, attrs, container_default), + fields_from_ast(cx, &fields.unnamed, attrs, container_default, private), ), syn::Fields::Unit => (Style::Unit, Vec::new()), } @@ -188,6 +200,7 @@ fn fields_from_ast<'a>( fields: &'a Punctuated, attrs: Option<&attr::Variant>, container_default: &attr::Default, + private: &Ident, ) -> Vec> { fields .iter() @@ -197,7 +210,7 @@ fn fields_from_ast<'a>( Some(ident) => syn::Member::Named(ident.clone()), None => syn::Member::Unnamed(i.into()), }, - attrs: attr::Field::from_ast(cx, i, field, attrs, container_default), + attrs: attr::Field::from_ast(cx, i, field, attrs, container_default, private), ty: &field.ty, original: field, }) diff --git a/pkg/installer/vendor/serde_derive/src/internals/attr.rs b/pkg/installer/vendor/serde_derive/src/internals/attr.rs index ac5f5d9a52e..f982f03a39f 100644 --- a/pkg/installer/vendor/serde_derive/src/internals/attr.rs +++ b/pkg/installer/vendor/serde_derive/src/internals/attr.rs @@ -1,14 +1,15 @@ +use crate::internals::name::{MultiName, Name}; use crate::internals::symbol::*; use crate::internals::{ungroup, Ctxt}; use proc_macro2::{Spacing, Span, TokenStream, TokenTree}; use quote::ToTokens; -use std::borrow::Cow; use std::collections::BTreeSet; use std::iter::FromIterator; use syn::meta::ParseNestedMeta; use syn::parse::ParseStream; use syn::punctuated::Punctuated; -use syn::{parse_quote, token, Ident, Lifetime, Token}; +use syn::spanned::Spanned; +use syn::{token, Ident, Lifetime, Token}; // This module handles parsing of `#[serde(...)]` attributes. The entrypoints // are `attr::Container::from_ast`, `attr::Variant::from_ast`, and @@ -20,7 +21,7 @@ use syn::{parse_quote, token, Ident, Lifetime, Token}; pub use crate::internals::case::RenameRule; -struct Attr<'c, T> { +pub(crate) struct Attr<'c, T> { cx: &'c Ctxt, name: Symbol, tokens: TokenStream, @@ -61,7 +62,7 @@ impl<'c, T> Attr<'c, T> { } } - fn get(self) -> Option { + pub(crate) fn get(self) -> Option { self.value } @@ -89,7 +90,7 @@ impl<'c> BoolAttr<'c> { } } -struct VecAttr<'c, T> { +pub(crate) struct VecAttr<'c, T> { cx: &'c Ctxt, name: Symbol, first_dup_tokens: TokenStream, @@ -124,63 +125,13 @@ impl<'c, T> VecAttr<'c, T> { } } - fn get(self) -> Vec { + pub(crate) fn get(self) -> Vec { self.values } } -pub struct Name { - serialize: String, - serialize_renamed: bool, - deserialize: String, - deserialize_renamed: bool, - deserialize_aliases: BTreeSet, -} - -fn unraw(ident: &Ident) -> String { - ident.to_string().trim_start_matches("r#").to_owned() -} - -impl Name { - fn from_attrs( - source_name: String, - ser_name: Attr, - de_name: Attr, - de_aliases: Option>, - ) -> Name { - let mut alias_set = BTreeSet::new(); - if let Some(de_aliases) = de_aliases { - for alias_name in de_aliases.get() { - alias_set.insert(alias_name); - } - } - - let ser_name = ser_name.get(); - let ser_renamed = ser_name.is_some(); - let de_name = de_name.get(); - let de_renamed = de_name.is_some(); - Name { - serialize: ser_name.unwrap_or_else(|| source_name.clone()), - serialize_renamed: ser_renamed, - deserialize: de_name.unwrap_or(source_name), - deserialize_renamed: de_renamed, - deserialize_aliases: alias_set, - } - } - - /// Return the container name for the container when serializing. - pub fn serialize_name(&self) -> &str { - &self.serialize - } - - /// Return the container name for the container when deserializing. - pub fn deserialize_name(&self) -> &str { - &self.deserialize - } - - fn deserialize_aliases(&self) -> &BTreeSet { - &self.deserialize_aliases - } +fn unraw(ident: &Ident) -> Ident { + Ident::new(ident.to_string().trim_start_matches("r#"), ident.span()) } #[derive(Copy, Clone)] @@ -202,7 +153,7 @@ impl RenameAllRules { /// Represents struct or enum attribute information. pub struct Container { - name: Name, + name: MultiName, transparent: bool, deny_unknown_fields: bool, default: Default, @@ -326,8 +277,8 @@ impl Container { // #[serde(rename = "foo")] // #[serde(rename(serialize = "foo", deserialize = "bar"))] let (ser, de) = get_renames(cx, RENAME, &meta)?; - ser_name.set_opt(&meta.path, ser.as_ref().map(syn::LitStr::value)); - de_name.set_opt(&meta.path, de.as_ref().map(syn::LitStr::value)); + ser_name.set_opt(&meta.path, ser.as_ref().map(Name::from)); + de_name.set_opt(&meta.path, de.as_ref().map(Name::from)); } else if meta.path == RENAME_ALL { // #[serde(rename_all = "foo")] // #[serde(rename_all(serialize = "foo", deserialize = "bar"))] @@ -566,7 +517,7 @@ impl Container { } Container { - name: Name::from_attrs(unraw(&item.ident), ser_name, de_name, None), + name: MultiName::from_attrs(Name::from(&unraw(&item.ident)), ser_name, de_name, None), transparent: transparent.get(), deny_unknown_fields: deny_unknown_fields.get(), default: default.get().unwrap_or(Default::None), @@ -593,7 +544,7 @@ impl Container { } } - pub fn name(&self) -> &Name { + pub fn name(&self) -> &MultiName { &self.name } @@ -657,11 +608,6 @@ impl Container { self.serde_path.as_ref() } - pub fn serde_path(&self) -> Cow { - self.custom_serde_path() - .map_or_else(|| Cow::Owned(parse_quote!(_serde)), Cow::Borrowed) - } - /// Error message generated when type can't be deserialized. /// If `None`, default message will be used pub fn expecting(&self) -> Option<&str> { @@ -780,7 +726,7 @@ fn decide_identifier( /// Represents variant attribute information pub struct Variant { - name: Name, + name: MultiName, rename_all_rules: RenameAllRules, ser_bound: Option>, de_bound: Option>, @@ -831,15 +777,15 @@ impl Variant { // #[serde(rename = "foo")] // #[serde(rename(serialize = "foo", deserialize = "bar"))] let (ser, de) = get_multiple_renames(cx, &meta)?; - ser_name.set_opt(&meta.path, ser.as_ref().map(syn::LitStr::value)); + ser_name.set_opt(&meta.path, ser.as_ref().map(Name::from)); for de_value in de { - de_name.set_if_none(de_value.value()); - de_aliases.insert(&meta.path, de_value.value()); + de_name.set_if_none(Name::from(&de_value)); + de_aliases.insert(&meta.path, Name::from(&de_value)); } } else if meta.path == ALIAS { // #[serde(alias = "foo")] if let Some(s) = get_lit_str(cx, ALIAS, &meta)? { - de_aliases.insert(&meta.path, s.value()); + de_aliases.insert(&meta.path, Name::from(&s)); } } else if meta.path == RENAME_ALL { // #[serde(rename_all = "foo")] @@ -888,13 +834,13 @@ impl Variant { ser_path .path .segments - .push(Ident::new("serialize", Span::call_site()).into()); + .push(Ident::new("serialize", ser_path.span()).into()); serialize_with.set(&meta.path, ser_path); let mut de_path = path; de_path .path .segments - .push(Ident::new("deserialize", Span::call_site()).into()); + .push(Ident::new("deserialize", de_path.span()).into()); deserialize_with.set(&meta.path, de_path); } } else if meta.path == SERIALIZE_WITH { @@ -946,7 +892,12 @@ impl Variant { } Variant { - name: Name::from_attrs(unraw(&variant.ident), ser_name, de_name, Some(de_aliases)), + name: MultiName::from_attrs( + Name::from(&unraw(&variant.ident)), + ser_name, + de_name, + Some(de_aliases), + ), rename_all_rules: RenameAllRules { serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None), deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None), @@ -963,20 +914,23 @@ impl Variant { } } - pub fn name(&self) -> &Name { + pub fn name(&self) -> &MultiName { &self.name } - pub fn aliases(&self) -> &BTreeSet { + pub fn aliases(&self) -> &BTreeSet { self.name.deserialize_aliases() } pub fn rename_by_rules(&mut self, rules: RenameAllRules) { if !self.name.serialize_renamed { - self.name.serialize = rules.serialize.apply_to_variant(&self.name.serialize); + self.name.serialize.value = + rules.serialize.apply_to_variant(&self.name.serialize.value); } if !self.name.deserialize_renamed { - self.name.deserialize = rules.deserialize.apply_to_variant(&self.name.deserialize); + self.name.deserialize.value = rules + .deserialize + .apply_to_variant(&self.name.deserialize.value); } self.name .deserialize_aliases @@ -1022,7 +976,7 @@ impl Variant { /// Represents field attribute information pub struct Field { - name: Name, + name: MultiName, skip_serializing: bool, skip_deserializing: bool, skip_serializing_if: Option, @@ -1064,6 +1018,7 @@ impl Field { field: &syn::Field, attrs: Option<&Variant>, container_default: &Default, + private: &Ident, ) -> Self { let mut ser_name = Attr::none(cx, RENAME); let mut de_name = Attr::none(cx, RENAME); @@ -1081,8 +1036,11 @@ impl Field { let mut flatten = BoolAttr::none(cx, FLATTEN); let ident = match &field.ident { - Some(ident) => unraw(ident), - None => index.to_string(), + Some(ident) => Name::from(&unraw(ident)), + None => Name { + value: index.to_string(), + span: Span::call_site(), + }, }; if let Some(borrow_attribute) = attrs.and_then(|variant| variant.borrow.as_ref()) { @@ -1118,15 +1076,15 @@ impl Field { // #[serde(rename = "foo")] // #[serde(rename(serialize = "foo", deserialize = "bar"))] let (ser, de) = get_multiple_renames(cx, &meta)?; - ser_name.set_opt(&meta.path, ser.as_ref().map(syn::LitStr::value)); + ser_name.set_opt(&meta.path, ser.as_ref().map(Name::from)); for de_value in de { - de_name.set_if_none(de_value.value()); - de_aliases.insert(&meta.path, de_value.value()); + de_name.set_if_none(Name::from(&de_value)); + de_aliases.insert(&meta.path, Name::from(&de_value)); } } else if meta.path == ALIAS { // #[serde(alias = "foo")] if let Some(s) = get_lit_str(cx, ALIAS, &meta)? { - de_aliases.insert(&meta.path, s.value()); + de_aliases.insert(&meta.path, Name::from(&s)); } } else if meta.path == DEFAULT { if meta.input.peek(Token![=]) { @@ -1170,13 +1128,13 @@ impl Field { ser_path .path .segments - .push(Ident::new("serialize", Span::call_site()).into()); + .push(Ident::new("serialize", ser_path.span()).into()); serialize_with.set(&meta.path, ser_path); let mut de_path = path; de_path .path .segments - .push(Ident::new("deserialize", Span::call_site()).into()); + .push(Ident::new("deserialize", de_path.span()).into()); deserialize_with.set(&meta.path, de_path); } } else if meta.path == BOUND { @@ -1254,7 +1212,7 @@ impl Field { }; let span = Span::call_site(); path.segments.push(Ident::new("_serde", span).into()); - path.segments.push(Ident::new("__private", span).into()); + path.segments.push(private.clone().into()); path.segments.push(Ident::new("de", span).into()); path.segments .push(Ident::new("borrow_cow_str", span).into()); @@ -1271,7 +1229,7 @@ impl Field { }; let span = Span::call_site(); path.segments.push(Ident::new("_serde", span).into()); - path.segments.push(Ident::new("__private", span).into()); + path.segments.push(private.clone().into()); path.segments.push(Ident::new("de", span).into()); path.segments .push(Ident::new("borrow_cow_bytes", span).into()); @@ -1289,7 +1247,7 @@ impl Field { } Field { - name: Name::from_attrs(ident, ser_name, de_name, Some(de_aliases)), + name: MultiName::from_attrs(ident, ser_name, de_name, Some(de_aliases)), skip_serializing: skip_serializing.get(), skip_deserializing: skip_deserializing.get(), skip_serializing_if: skip_serializing_if.get(), @@ -1305,20 +1263,22 @@ impl Field { } } - pub fn name(&self) -> &Name { + pub fn name(&self) -> &MultiName { &self.name } - pub fn aliases(&self) -> &BTreeSet { + pub fn aliases(&self) -> &BTreeSet { self.name.deserialize_aliases() } pub fn rename_by_rules(&mut self, rules: RenameAllRules) { if !self.name.serialize_renamed { - self.name.serialize = rules.serialize.apply_to_field(&self.name.serialize); + self.name.serialize.value = rules.serialize.apply_to_field(&self.name.serialize.value); } if !self.name.deserialize_renamed { - self.name.deserialize = rules.deserialize.apply_to_field(&self.name.deserialize); + self.name.deserialize.value = rules + .deserialize + .apply_to_field(&self.name.deserialize.value); } self.name .deserialize_aliases @@ -1768,7 +1728,7 @@ fn is_primitive_path(path: &syn::Path, primitive: &str) -> bool { // attribute on the field so there must be at least one borrowable lifetime. fn borrowable_lifetimes( cx: &Ctxt, - name: &str, + name: &Name, field: &syn::Field, ) -> Result, ()> { let mut lifetimes = BTreeSet::new(); diff --git a/pkg/installer/vendor/serde_derive/src/internals/check.rs b/pkg/installer/vendor/serde_derive/src/internals/check.rs index 52b0f379fd3..da2a0fbdc8c 100644 --- a/pkg/installer/vendor/serde_derive/src/internals/check.rs +++ b/pkg/installer/vendor/serde_derive/src/internals/check.rs @@ -329,13 +329,13 @@ fn check_internal_tag_field_name_conflict(cx: &Ctxt, cont: &Container) { let name = field.attrs.name(); let ser_name = name.serialize_name(); - if check_ser && ser_name == tag { + if check_ser && ser_name.value == tag { diagnose_conflict(); return; } for de_name in field.attrs.aliases() { - if check_de && de_name == tag { + if check_de && de_name.value == tag { diagnose_conflict(); return; } diff --git a/pkg/installer/vendor/serde_derive/src/internals/mod.rs b/pkg/installer/vendor/serde_derive/src/internals/mod.rs index f98ef08e8cb..cd1e8105283 100644 --- a/pkg/installer/vendor/serde_derive/src/internals/mod.rs +++ b/pkg/installer/vendor/serde_derive/src/internals/mod.rs @@ -1,5 +1,6 @@ pub mod ast; pub mod attr; +pub mod name; mod case; mod check; diff --git a/pkg/installer/vendor/serde_derive/src/internals/name.rs b/pkg/installer/vendor/serde_derive/src/internals/name.rs new file mode 100644 index 00000000000..4c59f9636d3 --- /dev/null +++ b/pkg/installer/vendor/serde_derive/src/internals/name.rs @@ -0,0 +1,113 @@ +use crate::internals::attr::{Attr, VecAttr}; +use proc_macro2::{Ident, Span, TokenStream}; +use quote::ToTokens; +use std::cmp::Ordering; +use std::collections::BTreeSet; +use std::fmt::{self, Display}; +use syn::LitStr; + +pub struct MultiName { + pub(crate) serialize: Name, + pub(crate) serialize_renamed: bool, + pub(crate) deserialize: Name, + pub(crate) deserialize_renamed: bool, + pub(crate) deserialize_aliases: BTreeSet, +} + +impl MultiName { + pub(crate) fn from_attrs( + source_name: Name, + ser_name: Attr, + de_name: Attr, + de_aliases: Option>, + ) -> Self { + let mut alias_set = BTreeSet::new(); + if let Some(de_aliases) = de_aliases { + for alias_name in de_aliases.get() { + alias_set.insert(alias_name); + } + } + + let ser_name = ser_name.get(); + let ser_renamed = ser_name.is_some(); + let de_name = de_name.get(); + let de_renamed = de_name.is_some(); + MultiName { + serialize: ser_name.unwrap_or_else(|| source_name.clone()), + serialize_renamed: ser_renamed, + deserialize: de_name.unwrap_or(source_name), + deserialize_renamed: de_renamed, + deserialize_aliases: alias_set, + } + } + + /// Return the container name for the container when serializing. + pub fn serialize_name(&self) -> &Name { + &self.serialize + } + + /// Return the container name for the container when deserializing. + pub fn deserialize_name(&self) -> &Name { + &self.deserialize + } + + pub(crate) fn deserialize_aliases(&self) -> &BTreeSet { + &self.deserialize_aliases + } +} + +#[derive(Clone)] +pub struct Name { + pub value: String, + pub span: Span, +} + +impl ToTokens for Name { + fn to_tokens(&self, tokens: &mut TokenStream) { + LitStr::new(&self.value, self.span).to_tokens(tokens); + } +} + +impl Ord for Name { + fn cmp(&self, other: &Self) -> Ordering { + Ord::cmp(&self.value, &other.value) + } +} + +impl PartialOrd for Name { + fn partial_cmp(&self, other: &Self) -> Option { + Some(Ord::cmp(self, other)) + } +} + +impl Eq for Name {} + +impl PartialEq for Name { + fn eq(&self, other: &Self) -> bool { + self.value == other.value + } +} + +impl From<&Ident> for Name { + fn from(ident: &Ident) -> Self { + Name { + value: ident.to_string(), + span: ident.span(), + } + } +} + +impl From<&LitStr> for Name { + fn from(lit: &LitStr) -> Self { + Name { + value: lit.value(), + span: lit.span(), + } + } +} + +impl Display for Name { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.value, formatter) + } +} diff --git a/pkg/installer/vendor/serde_derive/src/internals/receiver.rs b/pkg/installer/vendor/serde_derive/src/internals/receiver.rs index 852e857b8a2..a326f667c1e 100644 --- a/pkg/installer/vendor/serde_derive/src/internals/receiver.rs +++ b/pkg/installer/vendor/serde_derive/src/internals/receiver.rs @@ -2,7 +2,6 @@ use crate::internals::respan::respan; use proc_macro2::Span; use quote::ToTokens; use std::mem; -use syn::punctuated::Punctuated; use syn::{ parse_quote, Data, DeriveInput, Expr, ExprPath, GenericArgument, GenericParam, Generics, Macro, Path, PathArguments, QSelf, ReturnType, Token, Type, TypeParamBound, TypePath, WherePredicate, @@ -49,7 +48,7 @@ impl ReplaceReceiver<'_> { path.leading_colon = Some(**path.segments.pairs().next().unwrap().punct().unwrap()); - let segments = mem::replace(&mut path.segments, Punctuated::new()); + let segments = mem::take(&mut path.segments); path.segments = segments.into_pairs().skip(1).collect(); } @@ -209,7 +208,9 @@ impl ReplaceReceiver<'_> { match bound { #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] TypeParamBound::Trait(bound) => self.visit_path_mut(&mut bound.path), - TypeParamBound::Lifetime(_) | TypeParamBound::Verbatim(_) => {} + TypeParamBound::Lifetime(_) + | TypeParamBound::PreciseCapture(_) + | TypeParamBound::Verbatim(_) => {} _ => {} } } diff --git a/pkg/installer/vendor/serde_derive/src/internals/symbol.rs b/pkg/installer/vendor/serde_derive/src/internals/symbol.rs index 572391a8076..59ef8de7c48 100644 --- a/pkg/installer/vendor/serde_derive/src/internals/symbol.rs +++ b/pkg/installer/vendor/serde_derive/src/internals/symbol.rs @@ -46,7 +46,7 @@ impl PartialEq for Ident { } } -impl<'a> PartialEq for &'a Ident { +impl PartialEq for &Ident { fn eq(&self, word: &Symbol) -> bool { *self == word.0 } @@ -58,7 +58,7 @@ impl PartialEq for Path { } } -impl<'a> PartialEq for &'a Path { +impl PartialEq for &Path { fn eq(&self, word: &Symbol) -> bool { self.is_ident(word.0) } diff --git a/pkg/installer/vendor/serde_derive/src/lib.rs b/pkg/installer/vendor/serde_derive/src/lib.rs index 372b424c222..8577b308eaa 100644 --- a/pkg/installer/vendor/serde_derive/src/lib.rs +++ b/pkg/installer/vendor/serde_derive/src/lib.rs @@ -13,7 +13,7 @@ //! //! [https://serde.rs/derive.html]: https://serde.rs/derive.html -#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.207")] +#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.228")] #![cfg_attr(not(check_cfg), allow(unexpected_cfgs))] // Ignored clippy lints #![allow( @@ -27,6 +27,7 @@ // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6797 clippy::manual_map, clippy::match_like_matches_macro, + clippy::needless_lifetimes, clippy::needless_pass_by_value, clippy::too_many_arguments, clippy::trivially_copy_pass_by_ref, @@ -40,6 +41,7 @@ clippy::cast_possible_truncation, clippy::checked_conversions, clippy::doc_markdown, + clippy::elidable_lifetime_names, clippy::enum_glob_use, clippy::indexing_slicing, clippy::items_after_statements, @@ -55,12 +57,14 @@ clippy::single_match_else, clippy::struct_excessive_bools, clippy::too_many_lines, + clippy::uninlined_format_args, clippy::unseparated_literal_suffix, clippy::unused_self, clippy::use_self, clippy::wildcard_imports )] #![cfg_attr(all(test, exhaustive), feature(non_exhaustive_omitted_patterns_lint))] +#![allow(unknown_lints, mismatched_lifetime_syntaxes)] extern crate proc_macro2; extern crate quote; @@ -71,6 +75,8 @@ extern crate proc_macro; mod internals; use proc_macro::TokenStream; +use proc_macro2::{Ident, Span}; +use quote::{ToTokens, TokenStreamExt as _}; use syn::parse_macro_input; use syn::DeriveInput; @@ -80,11 +86,30 @@ mod bound; mod fragment; mod de; +mod deprecated; mod dummy; mod pretend; mod ser; mod this; +#[allow(non_camel_case_types)] +struct private; + +impl private { + fn ident(&self) -> Ident { + Ident::new( + concat!("__private", env!("CARGO_PKG_VERSION_PATCH")), + Span::call_site(), + ) + } +} + +impl ToTokens for private { + fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { + tokens.append(self.ident()); + } +} + #[proc_macro_derive(Serialize, attributes(serde))] pub fn derive_serialize(input: TokenStream) -> TokenStream { let mut input = parse_macro_input!(input as DeriveInput); diff --git a/pkg/installer/vendor/serde_derive/src/pretend.rs b/pkg/installer/vendor/serde_derive/src/pretend.rs index 2c9e7793683..cfa1a87d1a0 100644 --- a/pkg/installer/vendor/serde_derive/src/pretend.rs +++ b/pkg/installer/vendor/serde_derive/src/pretend.rs @@ -1,4 +1,5 @@ use crate::internals::ast::{Container, Data, Field, Style, Variant}; +use crate::private; use proc_macro2::TokenStream; use quote::{format_ident, quote}; @@ -83,8 +84,8 @@ fn pretend_fields_used_struct(cont: &Container, fields: &[Field]) -> TokenStream let placeholders = (0usize..).map(|i| format_ident!("__v{}", i)); quote! { - match _serde::__private::None::<&#type_ident #ty_generics> { - _serde::__private::Some(#type_ident { #(#members: #placeholders),* }) => {} + match _serde::#private::None::<&#type_ident #ty_generics> { + _serde::#private::Some(#type_ident { #(#members: #placeholders),* }) => {} _ => {} } } @@ -96,11 +97,12 @@ fn pretend_fields_used_struct_packed(cont: &Container, fields: &[Field]) -> Toke let members = fields.iter().map(|field| &field.member).collect::>(); + let private2 = private; quote! { - match _serde::__private::None::<&#type_ident #ty_generics> { - _serde::__private::Some(__v @ #type_ident { #(#members: _),* }) => { + match _serde::#private::None::<&#type_ident #ty_generics> { + _serde::#private::Some(__v @ #type_ident { #(#members: _),* }) => { #( - let _ = _serde::__private::ptr::addr_of!(__v.#members); + let _ = _serde::#private2::ptr::addr_of!(__v.#members); )* } _ => {} @@ -125,10 +127,11 @@ fn pretend_fields_used_enum(cont: &Container, variants: &[Variant]) -> TokenStre }) .collect::>(); + let private2 = private; quote! { - match _serde::__private::None::<&#type_ident #ty_generics> { + match _serde::#private::None::<&#type_ident #ty_generics> { #( - _serde::__private::Some(#patterns) => {} + _serde::#private2::Some(#patterns) => {} )* _ => {} } @@ -172,8 +175,8 @@ fn pretend_variants_used(cont: &Container) -> TokenStream { }; quote! { - match _serde::__private::None { - _serde::__private::Some((#(#placeholders,)*)) => { + match _serde::#private::None { + _serde::#private::Some((#(#placeholders,)*)) => { let _ = #type_ident::#variant_ident #turbofish #pat; } _ => {} diff --git a/pkg/installer/vendor/serde_derive/src/ser.rs b/pkg/installer/vendor/serde_derive/src/ser.rs index 35f8ca4bd4c..ad1fb174e81 100644 --- a/pkg/installer/vendor/serde_derive/src/ser.rs +++ b/pkg/installer/vendor/serde_derive/src/ser.rs @@ -1,7 +1,9 @@ +use crate::deprecated::allow_deprecated; use crate::fragment::{Fragment, Match, Stmts}; use crate::internals::ast::{Container, Data, Field, Style, Variant}; +use crate::internals::name::Name; use crate::internals::{attr, replace_receiver, Ctxt, Derive}; -use crate::{bound, dummy, pretend, this}; +use crate::{bound, dummy, pretend, private, this}; use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned}; use syn::spanned::Spanned; @@ -11,7 +13,7 @@ pub fn expand_derive_serialize(input: &mut syn::DeriveInput) -> syn::Result cont, None => return Err(ctxt.check().unwrap_err()), }; @@ -22,16 +24,18 @@ pub fn expand_derive_serialize(input: &mut syn::DeriveInput) -> syn::Result(__self: &#remote #ty_generics, __serializer: __S) -> #serde::__private::Result<__S::Ok, __S::Error> + #vis fn serialize<__S>(__self: &#remote #ty_generics, __serializer: __S) -> _serde::#private::Result<__S::Ok, __S::Error> where - __S: #serde::Serializer, + __S: _serde::Serializer, { #used #body @@ -41,10 +45,11 @@ pub fn expand_derive_serialize(input: &mut syn::DeriveInput) -> syn::Result(&self, __serializer: __S) -> #serde::__private::Result<__S::Ok, __S::Error> + #allow_deprecated + impl #impl_generics _serde::Serialize for #ident #ty_generics #where_clause { + fn serialize<__S>(&self, __serializer: __S) -> _serde::#private::Result<__S::Ok, __S::Error> where - __S: #serde::Serializer, + __S: _serde::Serializer, { #body } @@ -148,7 +153,7 @@ fn build_generics(cont: &Container) -> syn::Generics { } // Fields with a `skip_serializing` or `serialize_with` attribute, or which -// belong to a variant with a 'skip_serializing` or `serialize_with` attribute, +// belong to a variant with a `skip_serializing` or `serialize_with` attribute, // are not serialized by us so we do not generate a bound. Fields with a `bound` // attribute specify their own bound so we do not generate one. All other fields // may need a `T: Serialize` bound where T is the type of the field. @@ -210,7 +215,7 @@ fn serialize_into(params: &Parameters, type_into: &syn::Type) -> Fragment { let self_var = ¶ms.self_var; quote_block! { _serde::Serialize::serialize( - &_serde::__private::Into::<#type_into>::into(_serde::__private::Clone::clone(#self_var)), + &_serde::#private::Into::<#type_into>::into(_serde::#private::Clone::clone(#self_var)), __serializer) } } @@ -380,7 +385,7 @@ fn serialize_struct_as_map( let let_mut = mut_if(serialized_fields.peek().is_some() || tag_field_exists); quote_block! { - let #let_mut __serde_state = _serde::Serializer::serialize_map(__serializer, _serde::__private::None)?; + let #let_mut __serde_state = _serde::Serializer::serialize_map(__serializer, _serde::#private::None)?; #tag_field #(#serialize_fields)* _serde::ser::SerializeMap::end(__serde_state) @@ -402,7 +407,7 @@ fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Cont if cattrs.remote().is_some() && cattrs.non_exhaustive() { arms.push(quote! { - ref unrecognized => _serde::__private::Err(_serde::ser::Error::custom(_serde::__private::ser::CannotSerializeVariant(unrecognized))), + ref unrecognized => _serde::#private::Err(_serde::ser::Error::custom(_serde::#private::ser::CannotSerializeVariant(unrecognized))), }); } @@ -429,7 +434,7 @@ fn serialize_variant( variant_ident ); let skipped_err = quote! { - _serde::__private::Err(_serde::ser::Error::custom(#skipped_msg)) + _serde::#private::Err(_serde::ser::Error::custom(#skipped_msg)) }; let fields_pat = match variant.style { Style::Unit => quote!(), @@ -583,7 +588,7 @@ fn serialize_internally_tagged_variant( if let Some(path) = variant.attrs.serialize_with() { let ser = wrap_serialize_variant_with(params, path, variant); return quote_expr! { - _serde::__private::ser::serialize_tagged_newtype( + _serde::#private::ser::serialize_tagged_newtype( __serializer, #enum_ident_str, #variant_ident_str, @@ -612,7 +617,7 @@ fn serialize_internally_tagged_variant( } let span = field.original.span(); - let func = quote_spanned!(span=> _serde::__private::ser::serialize_tagged_newtype); + let func = quote_spanned!(span=> _serde::#private::ser::serialize_tagged_newtype); quote_expr! { #func( __serializer, @@ -646,7 +651,7 @@ fn serialize_adjacently_tagged_variant( let type_name = cattrs.name().serialize_name(); let variant_name = variant.attrs.name().serialize_name(); let serialize_variant = quote! { - &_serde::__private::ser::AdjacentlyTaggedEnumVariant { + &_serde::#private::ser::AdjacentlyTaggedEnumVariant { enum_name: #type_name, variant_index: #variant_index, variant_name: #variant_name, @@ -729,11 +734,12 @@ fn serialize_adjacently_tagged_variant( #[doc(hidden)] struct __AdjacentlyTagged #wrapper_generics #where_clause { data: (#(&'__a #fields_ty,)*), - phantom: _serde::__private::PhantomData<#this_type #ty_generics>, + phantom: _serde::#private::PhantomData<#this_type #ty_generics>, } + #[automatically_derived] impl #wrapper_impl_generics _serde::Serialize for __AdjacentlyTagged #wrapper_ty_generics #where_clause { - fn serialize<__S>(&self, __serializer: __S) -> _serde::__private::Result<__S::Ok, __S::Error> + fn serialize<__S>(&self, __serializer: __S) -> _serde::#private::Result<__S::Ok, __S::Error> where __S: _serde::Serializer, { @@ -751,7 +757,7 @@ fn serialize_adjacently_tagged_variant( _serde::ser::SerializeStruct::serialize_field( &mut __struct, #content, &__AdjacentlyTagged { data: (#(#fields_ident,)*), - phantom: _serde::__private::PhantomData::<#this_type #ty_generics>, + phantom: _serde::#private::PhantomData::<#this_type #ty_generics>, })?; _serde::ser::SerializeStruct::end(__struct) } @@ -798,9 +804,9 @@ fn serialize_untagged_variant( enum TupleVariant<'a> { ExternallyTagged { - type_name: &'a str, + type_name: &'a Name, variant_index: u32, - variant_name: &'a str, + variant_name: &'a Name, }, Untagged, } @@ -867,11 +873,11 @@ fn serialize_tuple_variant( enum StructVariant<'a> { ExternallyTagged { variant_index: u32, - variant_name: &'a str, + variant_name: &'a Name, }, InternallyTagged { tag: &'a str, - variant_name: &'a str, + variant_name: &'a Name, }, Untagged, } @@ -880,7 +886,7 @@ fn serialize_struct_variant( context: StructVariant, params: &Parameters, fields: &[Field], - name: &str, + name: &Name, ) -> Fragment { if fields.iter().any(|field| field.attrs.flatten()) { return serialize_struct_variant_with_flatten(context, params, fields, name); @@ -964,7 +970,7 @@ fn serialize_struct_variant_with_flatten( context: StructVariant, params: &Parameters, fields: &[Field], - name: &str, + name: &Name, ) -> Fragment { let struct_trait = StructTrait::SerializeMap; let serialize_fields = serialize_struct_visitor(fields, params, true, &struct_trait); @@ -993,18 +999,19 @@ fn serialize_struct_variant_with_flatten( #[doc(hidden)] struct __EnumFlatten #wrapper_generics #where_clause { data: (#(&'__a #fields_ty,)*), - phantom: _serde::__private::PhantomData<#this_type #ty_generics>, + phantom: _serde::#private::PhantomData<#this_type #ty_generics>, } + #[automatically_derived] impl #wrapper_impl_generics _serde::Serialize for __EnumFlatten #wrapper_ty_generics #where_clause { - fn serialize<__S>(&self, __serializer: __S) -> _serde::__private::Result<__S::Ok, __S::Error> + fn serialize<__S>(&self, __serializer: __S) -> _serde::#private::Result<__S::Ok, __S::Error> where __S: _serde::Serializer, { let (#(#members,)*) = self.data; let #let_mut __serde_state = _serde::Serializer::serialize_map( __serializer, - _serde::__private::None)?; + _serde::#private::None)?; #(#serialize_fields)* _serde::ser::SerializeMap::end(__serde_state) } @@ -1017,7 +1024,7 @@ fn serialize_struct_variant_with_flatten( #variant_name, &__EnumFlatten { data: (#(#members,)*), - phantom: _serde::__private::PhantomData::<#this_type #ty_generics>, + phantom: _serde::#private::PhantomData::<#this_type #ty_generics>, }) } } @@ -1025,7 +1032,7 @@ fn serialize_struct_variant_with_flatten( quote_block! { let #let_mut __serde_state = _serde::Serializer::serialize_map( __serializer, - _serde::__private::None)?; + _serde::#private::None)?; _serde::ser::SerializeMap::serialize_entry( &mut __serde_state, #tag, @@ -1039,7 +1046,7 @@ fn serialize_struct_variant_with_flatten( quote_block! { let #let_mut __serde_state = _serde::Serializer::serialize_map( __serializer, - _serde::__private::None)?; + _serde::#private::None)?; #(#serialize_fields)* _serde::ser::SerializeMap::end(__serde_state) } @@ -1128,7 +1135,7 @@ fn serialize_struct_visitor( let ser = if field.attrs.flatten() { let func = quote_spanned!(span=> _serde::Serialize::serialize); quote! { - #func(&#field_expr, _serde::__private::ser::FlatMapSerializer(&mut __serde_state))?; + #func(&#field_expr, _serde::#private::ser::FlatMapSerializer(&mut __serde_state))?; } } else { let func = struct_trait.serialize_field(span); @@ -1220,25 +1227,37 @@ fn wrap_serialize_with( }) }); - quote!({ + let self_var = quote!(self); + let serializer_var = quote!(__s); + + // If #serialize_with returns wrong type, error will be reported on here. + // We attach span of the path to this piece so error will be reported + // on the #[serde(with = "...")] + // ^^^^^ + let wrapper_serialize = quote_spanned! {serialize_with.span()=> + #serialize_with(#(#self_var.values.#field_access, )* #serializer_var) + }; + + quote!(&{ #[doc(hidden)] struct __SerializeWith #wrapper_impl_generics #where_clause { values: (#(&'__a #field_tys, )*), - phantom: _serde::__private::PhantomData<#this_type #ty_generics>, + phantom: _serde::#private::PhantomData<#this_type #ty_generics>, } + #[automatically_derived] impl #wrapper_impl_generics _serde::Serialize for __SerializeWith #wrapper_ty_generics #where_clause { - fn serialize<__S>(&self, __s: __S) -> _serde::__private::Result<__S::Ok, __S::Error> + fn serialize<__S>(&#self_var, #serializer_var: __S) -> _serde::#private::Result<__S::Ok, __S::Error> where __S: _serde::Serializer, { - #serialize_with(#(self.values.#field_access, )* __s) + #wrapper_serialize } } - &__SerializeWith { + __SerializeWith { values: (#(#field_exprs, )*), - phantom: _serde::__private::PhantomData::<#this_type #ty_generics>, + phantom: _serde::#private::PhantomData::<#this_type #ty_generics>, } }) } @@ -1274,11 +1293,11 @@ fn get_member(params: &Parameters, field: &Field, member: &Member) -> TokenStrea quote!(&#self_var.#member) }; let ty = field.ty; - quote!(_serde::__private::ser::constrain::<#ty>(#inner)) + quote!(_serde::#private::ser::constrain::<#ty>(#inner)) } (true, Some(getter)) => { let ty = field.ty; - quote!(_serde::__private::ser::constrain::<#ty>(&#getter(#self_var))) + quote!(_serde::#private::ser::constrain::<#ty>(&#getter(#self_var))) } (false, Some(_)) => { unreachable!("getter is only allowed for remote impls"); diff --git a/pkg/installer/vendor/syn/.cargo-checksum.json b/pkg/installer/vendor/syn/.cargo-checksum.json index c8e7adf664e..058d2c2b17e 100644 --- a/pkg/installer/vendor/syn/.cargo-checksum.json +++ b/pkg/installer/vendor/syn/.cargo-checksum.json @@ -1 +1 @@ -{"files":{".cargo_vcs_info.json":"420153162f9d1f76f3aa9d261c6bdecf922810b0c668c8dc72e97dee22da9db2","Cargo.toml":"1c5edd74d38f48af9424890e81075ae96e08ea77e40f9173cf0398bf1beccf3f","Cargo.toml.orig":"c1eb55265ae1470f49524d819603e6adadef2448f4ba30681abf4ea595332b30","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"ae6deb98ea51df4829c0327139a555cc115c6bcf6fb459db0ef0d6a96c4566ec","benches/file.rs":"0a0527c78d849148cbb6118b4d36f72da7d4add865ba1a410e0a1be9e8dbfe0e","benches/rust.rs":"a4b2ac626d36df1e344b1389384a559fb47da291b8ad3aa964d59d93279eebb1","src/attr.rs":"bd959c93f997d5d77ec08a5f580d1d38a391978b916b5bbe82bad4c03e694563","src/bigint.rs":"0299829b2f7a1a798fe2f7bc1680e4a10f9b6f4a852d09af4da2deab466c4242","src/buffer.rs":"00f28570908d311f3f568f3b116dc4f6aa3da556eb0bd5af8d6771f3301ab060","src/classify.rs":"00312dc6d51f634530f06b44365365a2588a3f6f40740224f64d0cde94839b5b","src/custom_keyword.rs":"322114e36ae43a2f8605506fb4568efdbc2986853e2fee74bd10a4ca0fb60c69","src/custom_punctuation.rs":"2ae2339c29b1aff3ab16157d51a3a07bfca594aa38586981534fe07a62cdd9d1","src/data.rs":"6f20b5ebbac7c3e9389cb0b5b0637f34d3ab721b6d6707b0eed274024ac78675","src/derive.rs":"f54f8cf9386a2d45186ff3c86ade5dae59e0e337b0198532449190ae8520cff8","src/discouraged.rs":"88b38a75d074d3f0b4186f2b4988844e8284a0c9d279d784327c6b595b9e33ea","src/drops.rs":"013385f1dd95663f1afab41abc1e2eea04181998644828935ca564c74d6462ae","src/error.rs":"3b03fd75eee8b0bb646eaf20f7e287345bdc7515ad5286024a2dd1e53c1e7bf2","src/export.rs":"b260cc49da1da3489e7755832bc8015cfad79e84f6c74e237f65ae25a2385e56","src/expr.rs":"50916a31a8fe40774c07a735661e97198997aedd7fa0aa8436ba5d6c57e6a9da","src/ext.rs":"ed143b029af286e62ceb4310286a4ce894792dd588465face042b4199b39d329","src/file.rs":"39d4ed9c56a7dc0d83259843732c434cd187248a4cde3dba4a98c3b92df6d08f","src/fixup.rs":"b312a6a527f81df17a94cb9f08def820584ca76cbef07893bbed492f2f0506af","src/gen/clone.rs":"36491f5f9e9cad6c4eb354b3331ec2b672607bb26429eba6379d1e9a4919170f","src/gen/debug.rs":"c9b2547663ed9025ba614fb1a70810df1b25f471ebb57abb01de5ab8e4fa8bf0","src/gen/eq.rs":"b5fffca0c3b6c31b3fcc80a7bd8fec65baed982a4e2fb4c8862db6059ab7dea1","src/gen/fold.rs":"345e6a6d9a7d2d09e09cd5857fc903af4202df42f0759a3da118556e98829fd2","src/gen/hash.rs":"447e840245178d0777b4e143b54c356b88962456e80282dcaad1763093709c13","src/gen/visit.rs":"178a6841d7d1974bff8c8c2f9a18e9b77384956841861a50828252bcaef67c18","src/gen/visit_mut.rs":"2a8f9a1c0259060f3fa1d6cab8a1924c1b07d713561aa9562cde8e79a39e66d5","src/generics.rs":"f532d7e4516c250e3eeda92e98ab2d1af19c9a368850abc8f56c230f1bbe534a","src/group.rs":"ddbff97e41315bdf9dfce215a8c00bb4d532827cf794246afde7308b39dc09ca","src/ident.rs":"d6061030fadae9c7dc847e1ee46178d9657d782aad108c7197e8cafe765b3eaa","src/item.rs":"81e2f57843cf2f8df82e314da940a6dda9bfa54e0641dbabe3ca2a7a68c9c5a8","src/lib.rs":"ee0a7e68948e1b8f7df6e8e31b76fe31c9ddbc7d31d46b17e4c54ed417fc5747","src/lifetime.rs":"5787d5a5dc7e5332b03283a25ae0a9e826464242ca2d149b1a19e7cae9cee34d","src/lit.rs":"8fa6fa2d752bd1bf5a94cd5cbf9becbcba37d491876614ce62dba0f8fc745a3d","src/lookahead.rs":"eae3c1855dfd1f9bca5dd4afba07d41b15f8c108017f9eda3dc515567160a2af","src/mac.rs":"cd85132ab4d302333f771be7a9b40f9281781ae9bcaee0607e0a25547352baaa","src/macros.rs":"2a6e895dfe1c3a9a7237b5e23358ca5d8967e2beae6d094dda68d3659f9a5c84","src/meta.rs":"969d8ccbdbc6ea2e4928a21831b791c57447b231e1373149e4c63b46f3951801","src/op.rs":"a61757370f802e44efa3c4a1057ae2cd26e64e273f7d76c06d5ffb49602319e2","src/parse.rs":"fc010e04b49c36813ee50f37d974289ae7081b3f96c37051340040f460b375aa","src/parse_macro_input.rs":"e4e22b63d0496d06a4ca17742a22467ed93f08a739081324773828bad63175ee","src/parse_quote.rs":"6f4e5e28622205651bdb23fcf0f0526aef81a7921aaeac2e7a1a1e3b67916fe9","src/pat.rs":"e552911a1712508c672eca35abdf9f81bad3a960f21522eddbc411a6a7070445","src/path.rs":"d77045e5dad382056d67fe31a42bc45b6a02ce044c43287bd38a95e32fd6aead","src/precedence.rs":"a0c3cd0d873e7c40b609ce3279838deb42cec4004bd4bf53276325428d7584fb","src/print.rs":"22910bf0521ab868ebd7c62601c55912d12cfb400c65723e08e5cfa3a2d111c0","src/punctuated.rs":"6e4a63b736f371bbb4cba83bb674e29aa25f9f214bc10e9acf785673a39d3fc5","src/restriction.rs":"eabb012634ef67aa3c3849c905ab549189461df7fefde2a4b90161c8685f31b2","src/sealed.rs":"6ece3b3dcb30f6bb98b93d83759ca7712ee8592bef9c0511141039c38765db0e","src/span.rs":"0a48e375e5c9768f6f64174a91ba6a255f4b021e2fb3548d8494e617f142601b","src/spanned.rs":"4b9bd65f60ab81922adfd0be8f03b6d50e98da3a5f525f242f9639aec4beac79","src/stmt.rs":"bb4cd196ce23c3fc07fefa47e67a0cd815db4f02ce1192625379d60bd657ffd2","src/thread.rs":"1f1deb1272525ab2af9a36aac4bce8f65b0e315adb1656641fd7075662f49222","src/token.rs":"3625e05bfaaf48adf7685669a59186386862572fa4550c5e94bf9a1febdb069e","src/tt.rs":"a58303a95d08d6bf3f3e09715b9b70a57b91b54774cfc1f00f2848034d2ff5c7","src/ty.rs":"c6efe6dd4fcdae77a20e9826d864f185546dffb15331c09e09feed8efabc284b","src/verbatim.rs":"87cbe82a90f48efb57ffd09141042698b3e011a21d0d5412154d80324b0a5ef0","src/whitespace.rs":"9cdcbfe9045b259046329a795bc1105ab5a871471a6d3f7318d275ee53f7a825","tests/common/eq.rs":"c4503ecbb7014eb816f6e6768c8e7853aa3d389419db5cd9ef122707cc168de2","tests/common/mod.rs":"1f43ce65b273172c87640e87ee0775ecb6f19280fbf8f792570d019b61f9a32d","tests/common/parse.rs":"c173bd515ba1d53b3b676161849fa8df0ae3d5592445843cee65b6628b71ac32","tests/debug/gen.rs":"3ca161a049fe72ff73ead99fbfe78335fdb2ac7c41085fe8cd0c9a0b29995151","tests/debug/mod.rs":"b56136586267ae1812a937b69215dd053ada2c21717771d89dcd3ce52bcb27f5","tests/macros/mod.rs":"64b0da858096e7cf0f772e66bc1787a867e45897d7677de580c0a1f35c0f6852","tests/regression.rs":"e9565ea0efecb4136f099164ffcfa26e1996b0a27fb9c6659e90ad9bdd42e7b6","tests/regression/issue1108.rs":"f32db35244a674e22ff824ca9e5bbec2184e287b59f022db68c418b5878a2edc","tests/regression/issue1235.rs":"a2266b10c3f7c7af5734817ab0a3e8b309b51e7d177b63f26e67e6b744d280b0","tests/repo/mod.rs":"7d2c93eecb65204c8417db8ebe3e6875a56f1cd6975263ccca9440cf43832266","tests/repo/progress.rs":"c08d0314a7f3ecf760d471f27da3cd2a500aeb9f1c8331bffb2aa648f9fabf3f","tests/test_asyncness.rs":"8982f6bc4e36510f924e288247473403e72697389ce9dda4e4b5ab0a8e49259f","tests/test_attribute.rs":"b35550a43bbd187bb330997ba36f90c65d8fc489135b1d32ef4547f145cb7612","tests/test_derive_input.rs":"99c4e6e45e3322ea9e269b309059c8a00fda1dcc03aed41f6e7d8c7e0a72fa2b","tests/test_expr.rs":"08129117bd4f6b8c2faea8e241e62ec8428c5286b20b5bb1583422f2b661d2f4","tests/test_generics.rs":"2fcc8575d695b568f3724b3b33d853b8fa6d9864eb816b5e3ca82420682e6155","tests/test_grouping.rs":"1bd63c8ca0b90bd493fb3f927079ab9ddf74d2a78da82db2f638e652d22305d5","tests/test_ident.rs":"d5850e817720e774cd397a46dbc5298c57933823c18e20805e84503fc9387e8f","tests/test_item.rs":"1b8412a5581adf93eaa215785a592f139af8511c954dee283d52dff2718a6cc2","tests/test_iterators.rs":"e7bd4e0743b852b9e0286489aee24fb08d48559bfa20ae55f3c7552ab69a5ba1","tests/test_lit.rs":"01b0acfe03cff16e7c1a45ceb7f4b637e5cbc6145840886ba981b7ed8e83691c","tests/test_meta.rs":"4ae570333f849ed8edec5dd957111a2deb721ede360f1e1ffeeab75380578ad4","tests/test_parse_buffer.rs":"0de6af13ba0345986b18d495063f9b75a1018e8569c34b277f9522c63a6c0941","tests/test_parse_quote.rs":"928176da6ebb449ef01a798f3352c9b181d3077c1266eb008df73876f4013c47","tests/test_parse_stream.rs":"b6b533432173123d6d01d8d2cb33714bc50b30b16ffbb6116f93937221ad4594","tests/test_pat.rs":"f6954a50e62a97ac2bc1ba0cb7a5a1fc53b7b01fb55ffe0176bee3fe1955d460","tests/test_path.rs":"d54350aa91508f8d301f5be3e3a34e03b0615b1a04e8fbbab9840da20161838b","tests/test_precedence.rs":"7e825e3845a96a274d99484f720db7ddf06205ba96cfcbef191749bcbce89620","tests/test_receiver.rs":"af64117acd66fbf42edc476f731ecd20c88009d9cb641dbd7a1d6384ae99ae73","tests/test_round_trip.rs":"48559ad63116f31fbbfd0d8501c5ace77d47f60a26b70359244bb0988fe65084","tests/test_shebang.rs":"98e8a6690c04e0aad2893b747593620b51836fe704f50f5c6fe352609837138a","tests/test_size.rs":"03efaf829b80b7db1f831474c1d3ce268914fc499d0e2a7eea03cad04a482974","tests/test_stmt.rs":"bbc305ea888254798b6faf285187d8bc7a955e4402d9a497d4b9d361e0436691","tests/test_token_trees.rs":"d012da9c3c861073711b006bf6ffdc073821fb9fb0a08733628cdae57124d1f5","tests/test_ty.rs":"aa14822fe99f3ac22eb056f5488a8110dfdb922e0008ea82b73bca8e1a613cd5","tests/test_unparenthesize.rs":"6c723cd6332b7d8be703fab20f085cef7716692eb07b1d75f2e590935656641d","tests/test_visibility.rs":"7bd239aef6f6d8173462dbd869064f3fdb9ba71644ac1f62c5d2fbb2568fb986","tests/zzz_stable.rs":"2a862e59cb446235ed99aec0e6ada8e16d3ecc30229b29d825b7c0bbc2602989"},"package":"1fceb41e3d546d0bd83421d3409b1460cc7444cd389341a4c880fe7a042cb3d7"} \ No newline at end of file +{"files":{".cargo_vcs_info.json":"ebcd037dc793c5f347b334359f52334b584d8e1f3f3e1b7f0b4223aded9075ae","Cargo.toml":"efa510558fc95d6629092691db4752f63049127862359f0617f675c2c31dea70","Cargo.toml.orig":"9024ae7025fa523cd8a48b738ff138ed95f7cdc352aa9475abd57ee907992534","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"ae6deb98ea51df4829c0327139a555cc115c6bcf6fb459db0ef0d6a96c4566ec","benches/file.rs":"e3593aa456d7ad50a118150e262ce2beb2092ed5c9391e93a055700d228cafb2","benches/rust.rs":"f40e33d0affc2d2081dc4522419382bf9a7b767eada7ac0063a1e6128929359f","src/attr.rs":"d890e2f0866758aec4a21729e2ea76b51485e43170f78b5a130499edad8a069d","src/bigint.rs":"0299829b2f7a1a798fe2f7bc1680e4a10f9b6f4a852d09af4da2deab466c4242","src/buffer.rs":"c2b99c6b4268205050fa93e6695f0f6d5990c4b2a7b24e234fd8d81c265f309a","src/classify.rs":"fa71d85602981cabf8f283d58748116a0d614a6af07d9e0025f459d71004fd14","src/custom_keyword.rs":"322114e36ae43a2f8605506fb4568efdbc2986853e2fee74bd10a4ca0fb60c69","src/custom_punctuation.rs":"2ae2339c29b1aff3ab16157d51a3a07bfca594aa38586981534fe07a62cdd9d1","src/data.rs":"5bb05d41eb93f5c895f05f31a2aa468f3332265a6d5e7a89968c5daa273937dc","src/derive.rs":"f54f8cf9386a2d45186ff3c86ade5dae59e0e337b0198532449190ae8520cff8","src/discouraged.rs":"88b38a75d074d3f0b4186f2b4988844e8284a0c9d279d784327c6b595b9e33ea","src/drops.rs":"e98da4aaafb5afc75919f9e2914326ad09bf16094a9407c60a05515a2e01dd00","src/error.rs":"3b03fd75eee8b0bb646eaf20f7e287345bdc7515ad5286024a2dd1e53c1e7bf2","src/export.rs":"b260cc49da1da3489e7755832bc8015cfad79e84f6c74e237f65ae25a2385e56","src/expr.rs":"1d33206bc7ef18bc280f1e79101cad01b24f1796c8d9701cb12f6908f63aa973","src/ext.rs":"ed143b029af286e62ceb4310286a4ce894792dd588465face042b4199b39d329","src/file.rs":"378839f4e6a9f30d524a6a9213cc513711ddeb14e04d98b0c67644d81788919d","src/fixup.rs":"b312a6a527f81df17a94cb9f08def820584ca76cbef07893bbed492f2f0506af","src/gen/clone.rs":"7af00b0a240453d7aac178be1b6cdf9df3b33f1281da35e02f66ba7ba55d060c","src/gen/debug.rs":"59bc259fa9dc0c7ffe094df7ad8afc9c4e79b6d73a8f0fae8a2e435905866e7a","src/gen/eq.rs":"d7428672d82c1931fdefb8bda0425a25ebbe20e5e2736b18cfd1752b64e99f78","src/gen/fold.rs":"99e8d2a7a7ca3e57c9358e6ea364f68145351f0c81677930e6c3597d15fab527","src/gen/hash.rs":"6808bb0e47e7346a14fbec5f55430906efa172f46417c83c2f7c76ce8c9ceab6","src/gen/token.css":"3a5882d0b3aefbf56ca5d08c28c117e25ac2327eadf7242202d906b2ddb2232e","src/gen/visit.rs":"10ce13d77cec3b3babc8f332902b0bddd712bb5fd5de1f4b3d7761e67cc13947","src/gen/visit_mut.rs":"53672f7c2568b1a9ad0ab33009c61ca19a3ebf18f5d1da57910e4e92fd6075e3","src/generics.rs":"972d7f6c7d33183b5c5338fdbc9e3e67681fd193d945c433b145e348836cbc1c","src/group.rs":"ddbff97e41315bdf9dfce215a8c00bb4d532827cf794246afde7308b39dc09ca","src/ident.rs":"d6061030fadae9c7dc847e1ee46178d9657d782aad108c7197e8cafe765b3eaa","src/item.rs":"2c1547f87927aee8443bebfcc7c924d128f2c78cebd4e23afd81bdd1b0298ee8","src/lib.rs":"1e4fbde852722294acff9f47056ffde222d6f3f3029e5a1fadb6090e5f2e68fe","src/lifetime.rs":"5787d5a5dc7e5332b03283a25ae0a9e826464242ca2d149b1a19e7cae9cee34d","src/lit.rs":"8fa6fa2d752bd1bf5a94cd5cbf9becbcba37d491876614ce62dba0f8fc745a3d","src/lookahead.rs":"6c8071c172620969b4b708981c7424d672985038be7dfde95ddc433604111773","src/mac.rs":"fdce8291f71adef3f69975f229156dca2309ca232ed943061afaf96220908ab8","src/macros.rs":"2a6e895dfe1c3a9a7237b5e23358ca5d8967e2beae6d094dda68d3659f9a5c84","src/meta.rs":"969d8ccbdbc6ea2e4928a21831b791c57447b231e1373149e4c63b46f3951801","src/op.rs":"a61757370f802e44efa3c4a1057ae2cd26e64e273f7d76c06d5ffb49602319e2","src/parse.rs":"2fa82a15f12a3ff0b7fdd36dd8c215f99120ec316769187bea5c0a6cc730289f","src/parse_macro_input.rs":"e4e22b63d0496d06a4ca17742a22467ed93f08a739081324773828bad63175ee","src/parse_quote.rs":"1679f4621b2702f6ad8ede2fd2a50d4c6f2c07fc5b18e6a389076f37d1e7cc19","src/pat.rs":"1455a882df5defbf6b774a80f37fe24cf96d5ad1e5584c5204c0c9723883566b","src/path.rs":"0e1f132bcb8586b0e93d377da96d48a6c8e63b2c3ea2b83c23698da5ec8039d5","src/precedence.rs":"b745555d0b743bf0d72b56c46ae722b768194ecf9bfbe0fe6c97edcec8c7fd50","src/print.rs":"22910bf0521ab868ebd7c62601c55912d12cfb400c65723e08e5cfa3a2d111c0","src/punctuated.rs":"6e4a63b736f371bbb4cba83bb674e29aa25f9f214bc10e9acf785673a39d3fc5","src/restriction.rs":"a7152ec5a4ee4f55446019aa2b4d84f2238776f0e6ffc0c22adf3374b517fe56","src/scan_expr.rs":"d46ae7a3eaaa6476553db3164676ec71aa82bcd8a2e4cad59deb07893c79f1c8","src/sealed.rs":"6ece3b3dcb30f6bb98b93d83759ca7712ee8592bef9c0511141039c38765db0e","src/span.rs":"0a48e375e5c9768f6f64174a91ba6a255f4b021e2fb3548d8494e617f142601b","src/spanned.rs":"4b9bd65f60ab81922adfd0be8f03b6d50e98da3a5f525f242f9639aec4beac79","src/stmt.rs":"9d68b914eac9569de71b3b76fdec2a729796c7350b6eb03d2255662233b12195","src/thread.rs":"1f1deb1272525ab2af9a36aac4bce8f65b0e315adb1656641fd7075662f49222","src/token.rs":"aa7f0e20c3f84e88810ef3ff30f71722973fdeed5cf31ce617f18a5459c758f0","src/tt.rs":"a58303a95d08d6bf3f3e09715b9b70a57b91b54774cfc1f00f2848034d2ff5c7","src/ty.rs":"b0e29da2f6d11e7766ef76d54a5af65eb7eaa00f3cf2db95276528057f77a37c","src/verbatim.rs":"87cbe82a90f48efb57ffd09141042698b3e011a21d0d5412154d80324b0a5ef0","src/whitespace.rs":"9cdcbfe9045b259046329a795bc1105ab5a871471a6d3f7318d275ee53f7a825","tests/common/eq.rs":"fd76c9ee5324d0b36efe9d5bb649ea545015f6402965b5dabaf109ce19f55155","tests/common/mod.rs":"1f43ce65b273172c87640e87ee0775ecb6f19280fbf8f792570d019b61f9a32d","tests/common/parse.rs":"c173bd515ba1d53b3b676161849fa8df0ae3d5592445843cee65b6628b71ac32","tests/debug/gen.rs":"3843ce1b6ea5a8e72bd24dfd52760d9326c30e05a3cfe5b28f8f0ac6d76318cf","tests/debug/mod.rs":"1259df940bbcaa968a837e402d6853f2efa38d2260e306d42f17f9e8ef74fae5","tests/macros/mod.rs":"c246b05fcca55d3880278754f36c802a8a006bb0a17d0c787989dd6716e76f37","tests/regression.rs":"e9565ea0efecb4136f099164ffcfa26e1996b0a27fb9c6659e90ad9bdd42e7b6","tests/regression/issue1108.rs":"f32db35244a674e22ff824ca9e5bbec2184e287b59f022db68c418b5878a2edc","tests/regression/issue1235.rs":"a2266b10c3f7c7af5734817ab0a3e8b309b51e7d177b63f26e67e6b744d280b0","tests/repo/mod.rs":"3ff3657c5201809456307dd4f3f3a2eef5170e29f4c3df3a7d43ae0415124471","tests/repo/progress.rs":"c08d0314a7f3ecf760d471f27da3cd2a500aeb9f1c8331bffb2aa648f9fabf3f","tests/test_asyncness.rs":"aca499c3c120f35f56033493aa732079af9a85463cc39297ed46ad2397be1c6d","tests/test_attribute.rs":"48078187c20a257422e02042c47acea8bb9b3644696e5d6a1eb0962864b81691","tests/test_derive_input.rs":"e062007ef389c0b8490d9145f9cc5dec59acbf34927c92355a43f2a847070ac2","tests/test_expr.rs":"f33918ab66c64605890d835fd72d96ea7c9e8ec645518030b4c2f8c8fd569d85","tests/test_generics.rs":"73ed0bb52b75720911fb03977b8ec33b873c2eaab735114d7a5fb45531b0b3c4","tests/test_grouping.rs":"28084b1b922884b54dfa6dc573ffc19a58138e5b08e0b6e0a82120572983c81d","tests/test_ident.rs":"d5850e817720e774cd397a46dbc5298c57933823c18e20805e84503fc9387e8f","tests/test_item.rs":"7191698ea9ed6e94ac57dbcfc4b484623d0c31cf89b005d5935083431be725f3","tests/test_iterators.rs":"f1ab7d5504dc06dc79cc3ba09c0364b045d2da86deb06e60412e6b80208b7439","tests/test_lit.rs":"8ec75a817036f0ff918b350370e90b2fb3fdef0ed32587b0015ebc09f9456c10","tests/test_meta.rs":"fee43f1219dd23523766feded7609d7c7fc3a156ecd55e309b2c5b40f11e045a","tests/test_parse_buffer.rs":"0de6af13ba0345986b18d495063f9b75a1018e8569c34b277f9522c63a6c0941","tests/test_parse_quote.rs":"28c11ab23b374327f56b29cc5f424f4a22a5974b92f9077a8dd0b8dca08c8d5c","tests/test_parse_stream.rs":"b6b533432173123d6d01d8d2cb33714bc50b30b16ffbb6116f93937221ad4594","tests/test_pat.rs":"d70d701ab2b9bd4f632e926af44c829ac273cf6fdacbdc52df4ec7cefcc9e09c","tests/test_path.rs":"9529c461c38ac1ecca1c6b798392aba791e7d371228b7670cde4c9b34c8e9d68","tests/test_precedence.rs":"a9cc731e65e5491c3e7d77e0f66ec875583cded36391b2fe02beac58fd95ce9e","tests/test_receiver.rs":"d34a1c5cac8f78ff0ff41df3bd9631b02edacab4d50059e8a2ed3d13fe6ba4c5","tests/test_round_trip.rs":"9c00a071a98cad7ce730d9e78e75ac63852924d6c1eaa6b6e29d06f02d276560","tests/test_shebang.rs":"98f7ec66e2240391c8f48fe9a330737930740b6275fef22486555ebef113acad","tests/test_size.rs":"03efaf829b80b7db1f831474c1d3ce268914fc499d0e2a7eea03cad04a482974","tests/test_stmt.rs":"3cf4463864039483c1ee329e3796d690b47c18bc8255c407451d31b239440ffe","tests/test_token_trees.rs":"f0a57f4d46b5dd4dbdf601450f6eb4db5fb5622dce3e9d17d2f021021b37fd9d","tests/test_ty.rs":"57622225e442427b79a68ff86a3fb2ebf2b81cc2ae1d2d00be601e8402bb1197","tests/test_unparenthesize.rs":"3e1eaf1025849db95d086a06735c6c564b30db87ee7abb3e4bb82f533e58c638","tests/test_visibility.rs":"f0ef86f7a89b8b78b841cad25d98420e96f59309d3d42f6930c6defad183edc7","tests/zzz_stable.rs":"2a862e59cb446235ed99aec0e6ada8e16d3ecc30229b29d825b7c0bbc2602989"},"package":"25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d"} \ No newline at end of file diff --git a/pkg/installer/vendor/syn/.cargo_vcs_info.json b/pkg/installer/vendor/syn/.cargo_vcs_info.json index cfee76db5ed..8147bb07237 100644 --- a/pkg/installer/vendor/syn/.cargo_vcs_info.json +++ b/pkg/installer/vendor/syn/.cargo_vcs_info.json @@ -1,6 +1,6 @@ { "git": { - "sha1": "b15ae2840910cb6102d4d23d8b1e7bcb91304b23" + "sha1": "a777cff00528f270b43f40b0a58c5c26fc85a2bd" }, "path_in_vcs": "" } \ No newline at end of file diff --git a/pkg/installer/vendor/syn/Cargo.toml b/pkg/installer/vendor/syn/Cargo.toml index 96e6833ca98..9e91ac2f120 100644 --- a/pkg/installer/vendor/syn/Cargo.toml +++ b/pkg/installer/vendor/syn/Cargo.toml @@ -13,7 +13,7 @@ edition = "2021" rust-version = "1.61" name = "syn" -version = "2.0.74" +version = "2.0.87" authors = ["David Tolnay "] build = false include = [ @@ -25,6 +25,7 @@ include = [ "/src/**", "/tests/**", ] +autolib = false autobins = false autoexamples = false autotests = false @@ -45,7 +46,10 @@ repository = "https://github.com/dtolnay/syn" [package.metadata.docs.rs] all-features = true -rustdoc-args = ["--generate-link-to-definition"] +rustdoc-args = [ + "--generate-link-to-definition", + "--extend-css=src/gen/token.css", +] targets = ["x86_64-unknown-linux-gnu"] [package.metadata.playground] diff --git a/pkg/installer/vendor/syn/Cargo.toml.orig b/pkg/installer/vendor/syn/Cargo.toml.orig index bf90f6009dc..e3af17d4912 100644 --- a/pkg/installer/vendor/syn/Cargo.toml.orig +++ b/pkg/installer/vendor/syn/Cargo.toml.orig @@ -1,6 +1,6 @@ [package] name = "syn" -version = "2.0.74" +version = "2.0.87" authors = ["David Tolnay "] categories = ["development-tools::procedural-macro-helpers", "parser-implementations"] description = "Parser for Rust source code" @@ -70,7 +70,7 @@ required-features = ["full", "parsing"] [package.metadata.docs.rs] all-features = true targets = ["x86_64-unknown-linux-gnu"] -rustdoc-args = ["--generate-link-to-definition"] +rustdoc-args = ["--generate-link-to-definition", "--extend-css=src/gen/token.css"] [package.metadata.playground] features = ["full", "visit", "visit-mut", "fold", "extra-traits"] diff --git a/pkg/installer/vendor/syn/benches/file.rs b/pkg/installer/vendor/syn/benches/file.rs index b4247239669..5754d20a67d 100644 --- a/pkg/installer/vendor/syn/benches/file.rs +++ b/pkg/installer/vendor/syn/benches/file.rs @@ -8,6 +8,7 @@ clippy::match_like_matches_macro, clippy::missing_panics_doc, clippy::must_use_candidate, + clippy::needless_lifetimes, clippy::uninlined_format_args )] diff --git a/pkg/installer/vendor/syn/benches/rust.rs b/pkg/installer/vendor/syn/benches/rust.rs index 09917e7cbe8..75a9f910105 100644 --- a/pkg/installer/vendor/syn/benches/rust.rs +++ b/pkg/installer/vendor/syn/benches/rust.rs @@ -11,6 +11,7 @@ clippy::let_underscore_untyped, clippy::manual_let_else, clippy::match_like_matches_macro, + clippy::needless_lifetimes, clippy::uninlined_format_args, clippy::unnecessary_wraps )] @@ -70,13 +71,13 @@ mod librustc_parse { impl Emitter for SilentEmitter { fn emit_diagnostic(&mut self, _diag: DiagInner) {} - fn source_map(&self) -> Option<&Lrc> { + fn source_map(&self) -> Option<&SourceMap> { None } } impl Translate for SilentEmitter { - fn fluent_bundle(&self) -> Option<&Lrc> { + fn fluent_bundle(&self) -> Option<&FluentBundle> { None } fn fallback_fluent_bundle(&self) -> &FluentBundle { diff --git a/pkg/installer/vendor/syn/src/attr.rs b/pkg/installer/vendor/syn/src/attr.rs index c19715cb3ba..2bdf96ee7fa 100644 --- a/pkg/installer/vendor/syn/src/attr.rs +++ b/pkg/installer/vendor/syn/src/attr.rs @@ -448,7 +448,7 @@ ast_enum! { } } -ast_enum_of_structs! { +ast_enum! { /// Content of a compile-time structured attribute. /// /// ## Path @@ -625,6 +625,24 @@ impl<'a> FilterAttrs<'a> for &'a [Attribute] { } } +impl From for Meta { + fn from(meta: Path) -> Meta { + Meta::Path(meta) + } +} + +impl From for Meta { + fn from(meta: MetaList) -> Meta { + Meta::List(meta) + } +} + +impl From for Meta { + fn from(meta: MetaNameValue) -> Meta { + Meta::NameValue(meta) + } +} + #[cfg(feature = "parsing")] pub(crate) mod parsing { use crate::attr::{AttrStyle, Attribute, Meta, MetaList, MetaNameValue}; @@ -635,6 +653,7 @@ pub(crate) mod parsing { use crate::parse::{Parse, ParseStream}; use crate::path::Path; use crate::{mac, token}; + use proc_macro2::Ident; use std::fmt::{self, Display}; pub(crate) fn parse_inner(input: ParseStream, attrs: &mut Vec) -> Result<()> { @@ -667,7 +686,7 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for Meta { fn parse(input: ParseStream) -> Result { - let path = input.call(Path::parse_mod_style)?; + let path = parse_outermost_meta_path(input)?; parse_meta_after_path(path, input) } } @@ -675,7 +694,7 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for MetaList { fn parse(input: ParseStream) -> Result { - let path = input.call(Path::parse_mod_style)?; + let path = parse_outermost_meta_path(input)?; parse_meta_list_after_path(path, input) } } @@ -683,11 +702,22 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for MetaNameValue { fn parse(input: ParseStream) -> Result { - let path = input.call(Path::parse_mod_style)?; + let path = parse_outermost_meta_path(input)?; parse_meta_name_value_after_path(path, input) } } + // Unlike meta::parse_meta_path which accepts arbitrary keywords in the path, + // only the `unsafe` keyword is accepted as an attribute's outermost path. + fn parse_outermost_meta_path(input: ParseStream) -> Result { + if input.peek(Token![unsafe]) { + let unsafe_token: Token![unsafe] = input.parse()?; + Ok(Path::from(Ident::new("unsafe", unsafe_token.span))) + } else { + Path::parse_mod_style(input) + } + } + pub(crate) fn parse_meta_after_path(path: Path, input: ParseStream) -> Result { if input.peek(token::Paren) || input.peek(token::Bracket) || input.peek(token::Brace) { parse_meta_list_after_path(path, input).map(Meta::List) @@ -757,7 +787,9 @@ pub(crate) mod parsing { #[cfg(feature = "printing")] mod printing { - use crate::attr::{AttrStyle, Attribute, MetaList, MetaNameValue}; + use crate::attr::{AttrStyle, Attribute, Meta, MetaList, MetaNameValue}; + use crate::path; + use crate::path::printing::PathStyle; use proc_macro2::TokenStream; use quote::ToTokens; @@ -774,10 +806,21 @@ mod printing { } } + #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] + impl ToTokens for Meta { + fn to_tokens(&self, tokens: &mut TokenStream) { + match self { + Meta::Path(path) => path::printing::print_path(tokens, path, PathStyle::Mod), + Meta::List(meta_list) => meta_list.to_tokens(tokens), + Meta::NameValue(meta_name_value) => meta_name_value.to_tokens(tokens), + } + } + } + #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for MetaList { fn to_tokens(&self, tokens: &mut TokenStream) { - self.path.to_tokens(tokens); + path::printing::print_path(tokens, &self.path, PathStyle::Mod); self.delimiter.surround(tokens, self.tokens.clone()); } } @@ -785,7 +828,7 @@ mod printing { #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for MetaNameValue { fn to_tokens(&self, tokens: &mut TokenStream) { - self.path.to_tokens(tokens); + path::printing::print_path(tokens, &self.path, PathStyle::Mod); self.eq_token.to_tokens(tokens); self.value.to_tokens(tokens); } diff --git a/pkg/installer/vendor/syn/src/buffer.rs b/pkg/installer/vendor/syn/src/buffer.rs index c28440a29b8..b4d19807255 100644 --- a/pkg/installer/vendor/syn/src/buffer.rs +++ b/pkg/installer/vendor/syn/src/buffer.rs @@ -183,52 +183,6 @@ impl<'a> Cursor<'a> { self.ptr == self.scope } - /// If the cursor is pointing at a `Group` with the given delimiter, returns - /// a cursor into that group and one pointing to the next `TokenTree`. - pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, DelimSpan, Cursor<'a>)> { - // If we're not trying to enter a none-delimited group, we want to - // ignore them. We have to make sure to _not_ ignore them when we want - // to enter them, of course. For obvious reasons. - if delim != Delimiter::None { - self.ignore_none(); - } - - if let Entry::Group(group, end_offset) = self.entry() { - if group.delimiter() == delim { - let span = group.delim_span(); - let end_of_group = unsafe { self.ptr.add(*end_offset) }; - let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) }; - let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; - return Some((inside_of_group, span, after_group)); - } - } - - None - } - - pub(crate) fn any_group(self) -> Option<(Cursor<'a>, Delimiter, DelimSpan, Cursor<'a>)> { - if let Entry::Group(group, end_offset) = self.entry() { - let delimiter = group.delimiter(); - let span = group.delim_span(); - let end_of_group = unsafe { self.ptr.add(*end_offset) }; - let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) }; - let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; - return Some((inside_of_group, delimiter, span, after_group)); - } - - None - } - - pub(crate) fn any_group_token(self) -> Option<(Group, Cursor<'a>)> { - if let Entry::Group(group, end_offset) = self.entry() { - let end_of_group = unsafe { self.ptr.add(*end_offset) }; - let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; - return Some((group.clone(), after_group)); - } - - None - } - /// If the cursor is pointing at a `Ident`, returns it along with a cursor /// pointing at the next `TokenTree`. pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> { @@ -279,6 +233,54 @@ impl<'a> Cursor<'a> { } } + /// If the cursor is pointing at a `Group` with the given delimiter, returns + /// a cursor into that group and one pointing to the next `TokenTree`. + pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, DelimSpan, Cursor<'a>)> { + // If we're not trying to enter a none-delimited group, we want to + // ignore them. We have to make sure to _not_ ignore them when we want + // to enter them, of course. For obvious reasons. + if delim != Delimiter::None { + self.ignore_none(); + } + + if let Entry::Group(group, end_offset) = self.entry() { + if group.delimiter() == delim { + let span = group.delim_span(); + let end_of_group = unsafe { self.ptr.add(*end_offset) }; + let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) }; + let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; + return Some((inside_of_group, span, after_group)); + } + } + + None + } + + /// If the cursor is pointing at a `Group`, returns a cursor into the group + /// and one pointing to the next `TokenTree`. + pub fn any_group(self) -> Option<(Cursor<'a>, Delimiter, DelimSpan, Cursor<'a>)> { + if let Entry::Group(group, end_offset) = self.entry() { + let delimiter = group.delimiter(); + let span = group.delim_span(); + let end_of_group = unsafe { self.ptr.add(*end_offset) }; + let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) }; + let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; + return Some((inside_of_group, delimiter, span, after_group)); + } + + None + } + + pub(crate) fn any_group_token(self) -> Option<(Group, Cursor<'a>)> { + if let Entry::Group(group, end_offset) = self.entry() { + let end_of_group = unsafe { self.ptr.add(*end_offset) }; + let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; + return Some((group.clone(), after_group)); + } + + None + } + /// Copies all remaining tokens visible from this cursor into a /// `TokenStream`. pub fn token_stream(self) -> TokenStream { diff --git a/pkg/installer/vendor/syn/src/classify.rs b/pkg/installer/vendor/syn/src/classify.rs index 42732e6d8d3..b3a6ae960ea 100644 --- a/pkg/installer/vendor/syn/src/classify.rs +++ b/pkg/installer/vendor/syn/src/classify.rs @@ -54,6 +54,7 @@ pub(crate) fn requires_comma_to_be_match_arm(expr: &Expr) -> bool { | Expr::Paren(_) | Expr::Path(_) | Expr::Range(_) + | Expr::RawAddr(_) | Expr::Reference(_) | Expr::Repeat(_) | Expr::Return(_) @@ -105,6 +106,7 @@ pub(crate) fn confusable_with_adjacent_block(mut expr: &Expr) -> bool { (None, None) => stack.pop(), } } + Expr::RawAddr(e) => Some(&e.expr), Expr::Reference(e) => Some(&e.expr), Expr::Return(e) => { if e.expr.is_none() && stack.is_empty() { @@ -202,7 +204,9 @@ pub(crate) fn trailing_unparameterized_path(mut ty: &Type) -> bool { ) -> ControlFlow { match bounds.last().unwrap() { TypeParamBound::Trait(t) => last_type_in_path(&t.path), - TypeParamBound::Lifetime(_) | TypeParamBound::Verbatim(_) => ControlFlow::Break(false), + TypeParamBound::Lifetime(_) + | TypeParamBound::PreciseCapture(_) + | TypeParamBound::Verbatim(_) => ControlFlow::Break(false), } } } @@ -246,6 +250,7 @@ pub(crate) fn expr_leading_label(mut expr: &Expr) -> bool { | Expr::Match(_) | Expr::Paren(_) | Expr::Path(_) + | Expr::RawAddr(_) | Expr::Reference(_) | Expr::Repeat(_) | Expr::Return(_) @@ -291,6 +296,7 @@ pub(crate) fn expr_trailing_brace(mut expr: &Expr) -> bool { Some(end) => expr = end, None => return false, }, + Expr::RawAddr(e) => expr = &e.expr, Expr::Reference(e) => expr = &e.expr, Expr::Return(e) => match &e.expr { Some(e) => expr = e, @@ -374,7 +380,9 @@ pub(crate) fn expr_trailing_brace(mut expr: &Expr) -> bool { Some(t) => ControlFlow::Continue(t), None => ControlFlow::Break(false), }, - TypeParamBound::Lifetime(_) => ControlFlow::Break(false), + TypeParamBound::Lifetime(_) | TypeParamBound::PreciseCapture(_) => { + ControlFlow::Break(false) + } TypeParamBound::Verbatim(t) => ControlFlow::Break(tokens_trailing_brace(t)), } } diff --git a/pkg/installer/vendor/syn/src/data.rs b/pkg/installer/vendor/syn/src/data.rs index 9e73f02d3cb..96db2a0b7c6 100644 --- a/pkg/installer/vendor/syn/src/data.rs +++ b/pkg/installer/vendor/syn/src/data.rs @@ -248,6 +248,8 @@ pub(crate) mod parsing { use crate::parse::discouraged::Speculative as _; use crate::parse::{Parse, ParseStream}; use crate::restriction::{FieldMutability, Visibility}; + #[cfg(not(feature = "full"))] + use crate::scan_expr::scan_expr; use crate::token; use crate::ty::Type; use crate::verbatim; @@ -276,7 +278,7 @@ pub(crate) mod parsing { let mut discriminant: Result = ahead.parse(); if discriminant.is_ok() { input.advance_to(&ahead); - } else if scan_lenient_discriminant(input).is_ok() { + } else if scan_expr(input).is_ok() { discriminant = Ok(Expr::Verbatim(verbatim::between(&begin, input))); } discriminant? @@ -294,85 +296,6 @@ pub(crate) mod parsing { } } - #[cfg(not(feature = "full"))] - pub(crate) fn scan_lenient_discriminant(input: ParseStream) -> Result<()> { - use crate::expr::Member; - use crate::lifetime::Lifetime; - use crate::lit::Lit; - use crate::lit::LitFloat; - use crate::op::{BinOp, UnOp}; - use crate::path::{self, AngleBracketedGenericArguments}; - use proc_macro2::Delimiter::{self, Brace, Bracket, Parenthesis}; - - let consume = |delimiter: Delimiter| { - Result::unwrap(input.step(|cursor| match cursor.group(delimiter) { - Some((_inside, _span, rest)) => Ok((true, rest)), - None => Ok((false, *cursor)), - })) - }; - - macro_rules! consume { - [$token:tt] => { - input.parse::>().unwrap().is_some() - }; - } - - let mut initial = true; - let mut depth = 0usize; - loop { - if initial { - if consume![&] { - input.parse::>()?; - } else if consume![if] || consume![match] || consume![while] { - depth += 1; - } else if input.parse::>()?.is_some() - || (consume(Brace) || consume(Bracket) || consume(Parenthesis)) - || (consume![async] || consume![const] || consume![loop] || consume![unsafe]) - && (consume(Brace) || break) - { - initial = false; - } else if consume![let] { - while !consume![=] { - if !((consume![|] || consume![ref] || consume![mut] || consume![@]) - || (consume![!] || input.parse::>()?.is_some()) - || (consume![..=] || consume![..] || consume![&] || consume![_]) - || (consume(Brace) || consume(Bracket) || consume(Parenthesis))) - { - path::parsing::qpath(input, true)?; - } - } - } else if input.parse::>()?.is_some() && !consume![:] { - break; - } else if input.parse::().is_err() { - path::parsing::qpath(input, true)?; - initial = consume![!] || depth == 0 && input.peek(token::Brace); - } - } else if input.is_empty() || input.peek(Token![,]) { - return Ok(()); - } else if depth > 0 && consume(Brace) { - if consume![else] && !consume(Brace) { - initial = consume![if] || break; - } else { - depth -= 1; - } - } else if input.parse::().is_ok() || (consume![..] | consume![=]) { - initial = true; - } else if consume![.] { - if input.parse::>()?.is_none() - && (input.parse::()?.is_named() && consume![::]) - { - AngleBracketedGenericArguments::do_parse(None, input)?; - } - } else if consume![as] { - input.parse::()?; - } else if !(consume(Brace) || consume(Bracket) || consume(Parenthesis)) { - break; - } - } - - Err(input.error("unsupported expression")) - } - #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for FieldsNamed { fn parse(input: ParseStream) -> Result { diff --git a/pkg/installer/vendor/syn/src/drops.rs b/pkg/installer/vendor/syn/src/drops.rs index 89b42d82ef1..c54308f02c1 100644 --- a/pkg/installer/vendor/syn/src/drops.rs +++ b/pkg/installer/vendor/syn/src/drops.rs @@ -32,10 +32,10 @@ impl DerefMut for NoDrop { pub(crate) trait TrivialDrop {} impl TrivialDrop for iter::Empty {} -impl<'a, T> TrivialDrop for slice::Iter<'a, T> {} -impl<'a, T> TrivialDrop for slice::IterMut<'a, T> {} -impl<'a, T> TrivialDrop for option::IntoIter<&'a T> {} -impl<'a, T> TrivialDrop for option::IntoIter<&'a mut T> {} +impl TrivialDrop for slice::Iter<'_, T> {} +impl TrivialDrop for slice::IterMut<'_, T> {} +impl TrivialDrop for option::IntoIter<&T> {} +impl TrivialDrop for option::IntoIter<&mut T> {} #[test] fn test_needs_drop() { diff --git a/pkg/installer/vendor/syn/src/expr.rs b/pkg/installer/vendor/syn/src/expr.rs index 8e1e461d8ec..f68f6322fec 100644 --- a/pkg/installer/vendor/syn/src/expr.rs +++ b/pkg/installer/vendor/syn/src/expr.rs @@ -1,15 +1,17 @@ use crate::attr::Attribute; #[cfg(all(feature = "parsing", feature = "full"))] use crate::error::Result; +#[cfg(feature = "parsing")] +use crate::ext::IdentExt as _; #[cfg(feature = "full")] use crate::generics::BoundLifetimes; use crate::ident::Ident; -#[cfg(feature = "full")] +#[cfg(any(feature = "parsing", feature = "full"))] use crate::lifetime::Lifetime; use crate::lit::Lit; use crate::mac::Macro; use crate::op::{BinOp, UnOp}; -#[cfg(all(feature = "parsing", feature = "full"))] +#[cfg(feature = "parsing")] use crate::parse::ParseStream; #[cfg(feature = "full")] use crate::pat::Pat; @@ -202,6 +204,9 @@ ast_enum_of_structs! { /// A range expression: `1..2`, `1..`, `..2`, `1..=2`, `..=2`. Range(ExprRange), + /// Address-of operation: `&raw const place` or `&raw mut place`. + RawAddr(ExprRawAddr), + /// A referencing operation: `&a` or `&mut a`. Reference(ExprReference), @@ -574,6 +579,18 @@ ast_struct! { } } +ast_struct! { + /// Address-of operation: `&raw const place` or `&raw mut place`. + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + pub struct ExprRawAddr #full { + pub attrs: Vec, + pub and_token: Token![&], + pub raw: Token![raw], + pub mutability: PointerMutability, + pub expr: Box, + } +} + ast_struct! { /// A referencing operation: `&a` or `&mut a`. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] @@ -647,7 +664,7 @@ ast_struct! { ast_struct! { /// A tuple expression: `(a, b, c, d)`. #[cfg_attr(docsrs, doc(cfg(feature = "full")))] - pub struct ExprTuple #full { + pub struct ExprTuple { pub attrs: Vec, pub paren_token: token::Paren, pub elems: Punctuated, @@ -874,6 +891,36 @@ impl Expr { parsing::parse_with_earlier_boundary_rule(input) } + /// Returns whether the next token in the parse stream is one that might + /// possibly form the beginning of an expr. + /// + /// This classification is a load-bearing part of the grammar of some Rust + /// expressions, notably `return` and `break`. For example `return < …` will + /// never parse `<` as a binary operator regardless of what comes after, + /// because `<` is a legal starting token for an expression and so it's + /// required to be continued as a return value, such as `return ::CONST`. Meanwhile `return > …` treats the `>` as a binary + /// operator because it cannot be a starting token for any Rust expression. + #[cfg(feature = "parsing")] + #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] + pub fn peek(input: ParseStream) -> bool { + input.peek(Ident::peek_any) // value name or keyword + || input.peek(token::Paren) // tuple + || input.peek(token::Bracket) // array + || input.peek(token::Brace) // block + || input.peek(Lit) // literal + || input.peek(Token![!]) && !input.peek(Token![!=]) // operator not + || input.peek(Token![-]) && !input.peek(Token![-=]) && !input.peek(Token![->]) // unary minus + || input.peek(Token![*]) && !input.peek(Token![*=]) // dereference + || input.peek(Token![|]) && !input.peek(Token![|=]) // closure + || input.peek(Token![&]) && !input.peek(Token![&=]) // reference + || input.peek(Token![..]) // range + || input.peek(Token![<]) && !input.peek(Token![<=]) && !input.peek(Token![<<=]) // associated path + || input.peek(Token![::]) // absolute path + || input.peek(Lifetime) // labeled loop + || input.peek(Token![#]) // expression attributes + } + #[cfg(all(feature = "parsing", feature = "full"))] pub(crate) fn replace_attrs(&mut self, new: Vec) -> Vec { match self { @@ -904,6 +951,7 @@ impl Expr { | Expr::Paren(ExprParen { attrs, .. }) | Expr::Path(ExprPath { attrs, .. }) | Expr::Range(ExprRange { attrs, .. }) + | Expr::RawAddr(ExprRawAddr { attrs, .. }) | Expr::Reference(ExprReference { attrs, .. }) | Expr::Repeat(ExprRepeat { attrs, .. }) | Expr::Return(ExprReturn { attrs, .. }) @@ -1099,6 +1147,17 @@ ast_enum! { } } +#[cfg(feature = "full")] +ast_enum! { + /// Mutability of a raw pointer (`*const T`, `*mut T`), in which non-mutable + /// isn't the implicit default. + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + pub enum PointerMutability { + Const(Token![const]), + Mut(Token![mut]), + } +} + #[cfg(feature = "parsing")] pub(crate) mod parsing { #[cfg(feature = "full")] @@ -1111,17 +1170,15 @@ pub(crate) mod parsing { use crate::expr::{ Arm, ExprArray, ExprAssign, ExprAsync, ExprAwait, ExprBlock, ExprBreak, ExprClosure, ExprConst, ExprContinue, ExprForLoop, ExprIf, ExprInfer, ExprLet, ExprLoop, ExprMatch, - ExprRange, ExprRepeat, ExprReturn, ExprTry, ExprTryBlock, ExprTuple, ExprUnsafe, ExprWhile, - ExprYield, Label, RangeLimits, + ExprRange, ExprRawAddr, ExprRepeat, ExprReturn, ExprTry, ExprTryBlock, ExprUnsafe, + ExprWhile, ExprYield, Label, PointerMutability, RangeLimits, }; use crate::expr::{ Expr, ExprBinary, ExprCall, ExprCast, ExprField, ExprGroup, ExprIndex, ExprLit, ExprMacro, - ExprMethodCall, ExprParen, ExprPath, ExprReference, ExprStruct, ExprUnary, FieldValue, - Index, Member, + ExprMethodCall, ExprParen, ExprPath, ExprReference, ExprStruct, ExprTuple, ExprUnary, + FieldValue, Index, Member, }; #[cfg(feature = "full")] - use crate::ext::IdentExt as _; - #[cfg(feature = "full")] use crate::generics::BoundLifetimes; use crate::ident::Ident; #[cfg(feature = "full")] @@ -1149,11 +1206,6 @@ pub(crate) mod parsing { use proc_macro2::TokenStream; use std::mem; - mod kw { - crate::custom_keyword!(builtin); - crate::custom_keyword!(raw); - } - // When we're parsing expressions which occur before blocks, like in an if // statement's condition, we cannot parse a struct literal. // @@ -1244,25 +1296,6 @@ pub(crate) mod parsing { } } - #[cfg(feature = "full")] - fn can_begin_expr(input: ParseStream) -> bool { - input.peek(Ident::peek_any) // value name or keyword - || input.peek(token::Paren) // tuple - || input.peek(token::Bracket) // array - || input.peek(token::Brace) // block - || input.peek(Lit) // literal - || input.peek(Token![!]) && !input.peek(Token![!=]) // operator not - || input.peek(Token![-]) && !input.peek(Token![-=]) && !input.peek(Token![->]) // unary minus - || input.peek(Token![*]) && !input.peek(Token![*=]) // dereference - || input.peek(Token![|]) && !input.peek(Token![|=]) // closure - || input.peek(Token![&]) && !input.peek(Token![&=]) // reference - || input.peek(Token![..]) // range notation - || input.peek(Token![<]) && !input.peek(Token![<=]) && !input.peek(Token![<<=]) // associated path - || input.peek(Token![::]) // global path - || input.peek(Lifetime) // labeled loop - || input.peek(Token![#]) // expression attributes - } - #[cfg(feature = "full")] fn parse_expr( input: ParseStream, @@ -1284,7 +1317,7 @@ pub(crate) mod parsing { if precedence == Precedence::Compare { if let Expr::Binary(lhs) = &lhs { if Precedence::of_binop(&lhs.op) == Precedence::Compare { - break; + return Err(input.error("comparison operators cannot be chained")); } } } @@ -1346,7 +1379,7 @@ pub(crate) mod parsing { if precedence == Precedence::Compare { if let Expr::Binary(lhs) = &lhs { if Precedence::of_binop(&lhs.op) == Precedence::Compare { - break; + return Err(input.error("comparison operators cannot be chained")); } } } @@ -1390,6 +1423,7 @@ pub(crate) mod parsing { loop { let next = peek_precedence(input); if next > precedence || next == precedence && precedence == Precedence::Assign { + let cursor = input.cursor(); rhs = parse_expr( input, rhs, @@ -1397,10 +1431,18 @@ pub(crate) mod parsing { allow_struct, next, )?; + if cursor == input.cursor() { + // Bespoke grammar restrictions separate from precedence can + // cause parsing to not advance, such as `..a` being + // disallowed in the left-hand side of binary operators, + // even ones that have lower precedence than `..`. + break; + } } else { - return Ok(Box::new(rhs)); + break; } } + Ok(Box::new(rhs)) } fn peek_precedence(input: ParseStream) -> Precedence { @@ -1459,7 +1501,7 @@ pub(crate) mod parsing { if input.peek(Token![&]) { let and_token: Token![&] = input.parse()?; - let raw: Option = if input.peek(kw::raw) + let raw: Option = if input.peek(Token![raw]) && (input.peek2(Token![mut]) || input.peek2(Token![const])) { Some(input.parse()?) @@ -1467,12 +1509,23 @@ pub(crate) mod parsing { None }; let mutability: Option = input.parse()?; - if raw.is_some() && mutability.is_none() { - input.parse::()?; - } + let const_token: Option = if raw.is_some() && mutability.is_none() { + Some(input.parse()?) + } else { + None + }; let expr = Box::new(unary_expr(input, allow_struct)?); - if raw.is_some() { - Ok(Expr::Verbatim(verbatim::between(&begin, input))) + if let Some(raw) = raw { + Ok(Expr::RawAddr(ExprRawAddr { + attrs, + and_token, + raw, + mutability: match mutability { + Some(mut_token) => PointerMutability::Mut(mut_token), + None => PointerMutability::Const(const_token.unwrap()), + }, + expr, + })) } else { Ok(Expr::Reference(ExprReference { attrs, @@ -1721,7 +1774,8 @@ pub(crate) mod parsing { || input.peek(Token![async]) && (input.peek2(Token![|]) || input.peek2(Token![move])) { expr_closure(input, allow_struct).map(Expr::Closure) - } else if input.peek(kw::builtin) && input.peek2(Token![#]) { + } else if token::parsing::peek_keyword(input.cursor(), "builtin") && input.peek2(Token![#]) + { expr_builtin(input) } else if input.peek(Ident) || input.peek(Token![::]) @@ -1807,7 +1861,7 @@ pub(crate) mod parsing { } else if input.peek(Lit) { input.parse().map(Expr::Lit) } else if input.peek(token::Paren) { - input.call(expr_paren).map(Expr::Paren) + paren_or_tuple(input) } else if input.peek(Ident) || input.peek(Token![::]) || input.peek(Token![<]) @@ -1838,7 +1892,7 @@ pub(crate) mod parsing { fn expr_builtin(input: ParseStream) -> Result { let begin = input.fork(); - input.parse::()?; + token::parsing::keyword(input, "builtin")?; input.parse::()?; input.parse::()?; @@ -1853,7 +1907,8 @@ pub(crate) mod parsing { input: ParseStream, #[cfg(feature = "full")] allow_struct: AllowStruct, ) -> Result { - let (qself, path) = path::parsing::qpath(input, true)?; + let expr_style = true; + let (qself, path) = path::parsing::qpath(input, expr_style)?; rest_of_path_or_macro_or_struct( qself, path, @@ -1910,7 +1965,6 @@ pub(crate) mod parsing { } } - #[cfg(feature = "full")] fn paren_or_tuple(input: ParseStream) -> Result { let content; let paren_token = parenthesized!(content in input); @@ -2102,19 +2156,15 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for ExprParen { fn parse(input: ParseStream) -> Result { - expr_paren(input) + let content; + Ok(ExprParen { + attrs: Vec::new(), + paren_token: parenthesized!(content in input), + expr: content.parse()?, + }) } } - fn expr_paren(input: ParseStream) -> Result { - let content; - Ok(ExprParen { - attrs: Vec::new(), - paren_token: parenthesized!(content in input), - expr: content.parse()?, - }) - } - #[cfg(feature = "full")] #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for ExprLet { @@ -2354,6 +2404,21 @@ pub(crate) mod parsing { } } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] + impl Parse for ExprRawAddr { + fn parse(input: ParseStream) -> Result { + let allow_struct = AllowStruct(true); + Ok(ExprRawAddr { + attrs: Vec::new(), + and_token: input.parse()?, + raw: input.parse()?, + mutability: input.parse()?, + expr: Box::new(unary_expr(input, allow_struct)?), + }) + } + } + #[cfg(feature = "full")] #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for ExprReference { @@ -2385,7 +2450,7 @@ pub(crate) mod parsing { attrs: Vec::new(), return_token: input.parse()?, expr: { - if can_begin_expr(input) { + if Expr::peek(input) { Some(input.parse()?) } else { None @@ -2399,9 +2464,7 @@ pub(crate) mod parsing { fn expr_become(input: ParseStream) -> Result { let begin = input.fork(); input.parse::()?; - if can_begin_expr(input) { - input.parse::()?; - } + input.parse::()?; Ok(Expr::Verbatim(verbatim::between(&begin, input))) } @@ -2425,7 +2488,7 @@ pub(crate) mod parsing { attrs: Vec::new(), yield_token: input.parse()?, expr: { - if can_begin_expr(input) { + if Expr::peek(input) { Some(input.parse()?) } else { None @@ -2638,7 +2701,7 @@ pub(crate) mod parsing { } input.advance_to(&ahead); - let expr = if can_begin_expr(input) && (allow_struct.0 || !input.peek(token::Brace)) { + let expr = if Expr::peek(input) && (allow_struct.0 || !input.peek(token::Brace)) { Some(input.parse()?) } else { None @@ -2684,7 +2747,8 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for ExprStruct { fn parse(input: ParseStream) -> Result { - let (qself, path) = path::parsing::qpath(input, true)?; + let expr_style = true; + let (qself, path) = path::parsing::qpath(input, expr_style)?; expr_struct_helper(input, qself, path) } } @@ -2851,7 +2915,8 @@ pub(crate) mod parsing { #[cfg(feature = "full")] let attrs = input.call(Attribute::parse_outer)?; - let (qself, path) = path::parsing::qpath(input, true)?; + let expr_style = true; + let (qself, path) = path::parsing::qpath(input, expr_style)?; Ok(ExprPath { attrs, qself, path }) } @@ -2965,6 +3030,21 @@ pub(crate) mod parsing { } } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] + impl Parse for PointerMutability { + fn parse(input: ParseStream) -> Result { + let lookahead = input.lookahead1(); + if lookahead.peek(Token![const]) { + Ok(PointerMutability::Const(input.parse()?)) + } else if lookahead.peek(Token![mut]) { + Ok(PointerMutability::Mut(input.parse()?)) + } else { + Err(lookahead.error()) + } + } + } + fn check_cast(input: ParseStream) -> Result<()> { let kind = if input.peek(Token![.]) && !input.peek(Token![..]) { if input.peek2(Token![await]) { @@ -2999,17 +3079,18 @@ pub(crate) mod printing { use crate::expr::{ Arm, ExprArray, ExprAssign, ExprAsync, ExprAwait, ExprBlock, ExprBreak, ExprClosure, ExprConst, ExprContinue, ExprForLoop, ExprIf, ExprInfer, ExprLet, ExprLoop, ExprMatch, - ExprRange, ExprRepeat, ExprReturn, ExprTry, ExprTryBlock, ExprTuple, ExprUnsafe, ExprWhile, - ExprYield, Label, RangeLimits, + ExprRange, ExprRawAddr, ExprRepeat, ExprReturn, ExprTry, ExprTryBlock, ExprUnsafe, + ExprWhile, ExprYield, Label, PointerMutability, RangeLimits, }; use crate::expr::{ Expr, ExprBinary, ExprCall, ExprCast, ExprField, ExprGroup, ExprIndex, ExprLit, ExprMacro, - ExprMethodCall, ExprParen, ExprPath, ExprReference, ExprStruct, ExprUnary, FieldValue, - Index, Member, + ExprMethodCall, ExprParen, ExprPath, ExprReference, ExprStruct, ExprTuple, ExprUnary, + FieldValue, Index, Member, }; use crate::fixup::FixupContext; use crate::op::BinOp; use crate::path; + use crate::path::printing::PathStyle; use crate::precedence::Precedence; use crate::token; #[cfg(feature = "full")] @@ -3125,6 +3206,8 @@ pub(crate) mod printing { Expr::Path(e) => e.to_tokens(tokens), #[cfg(feature = "full")] Expr::Range(e) => print_expr_range(e, tokens, fixup), + #[cfg(feature = "full")] + Expr::RawAddr(e) => print_expr_raw_addr(e, tokens, fixup), Expr::Reference(e) => print_expr_reference(e, tokens, fixup), #[cfg(feature = "full")] Expr::Repeat(e) => e.to_tokens(tokens), @@ -3623,7 +3706,13 @@ pub(crate) mod printing { ); e.dot_token.to_tokens(tokens); e.method.to_tokens(tokens); - e.turbofish.to_tokens(tokens); + if let Some(turbofish) = &e.turbofish { + path::printing::print_angle_bracketed_generic_arguments( + tokens, + turbofish, + PathStyle::Expr, + ); + } e.paren_token.surround(tokens, |tokens| { e.args.to_tokens(tokens); }); @@ -3643,7 +3732,7 @@ pub(crate) mod printing { impl ToTokens for ExprPath { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); - path::printing::print_path(tokens, &self.qself, &self.path); + path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::Expr); } } @@ -3677,6 +3766,28 @@ pub(crate) mod printing { } } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] + impl ToTokens for ExprRawAddr { + fn to_tokens(&self, tokens: &mut TokenStream) { + print_expr_raw_addr(self, tokens, FixupContext::NONE); + } + } + + #[cfg(feature = "full")] + fn print_expr_raw_addr(e: &ExprRawAddr, tokens: &mut TokenStream, fixup: FixupContext) { + outer_attrs_to_tokens(&e.attrs, tokens); + e.and_token.to_tokens(tokens); + e.raw.to_tokens(tokens); + e.mutability.to_tokens(tokens); + print_subexpression( + &e.expr, + fixup.trailing_precedence(&e.expr) < Precedence::Prefix, + tokens, + fixup.subsequent_subexpression(), + ); + } + #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for ExprReference { fn to_tokens(&self, tokens: &mut TokenStream) { @@ -3730,7 +3841,7 @@ pub(crate) mod printing { impl ToTokens for ExprStruct { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); - path::printing::print_path(tokens, &self.qself, &self.path); + path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::Expr); self.brace_token.surround(tokens, |tokens| { self.fields.to_tokens(tokens); if let Some(dot2_token) = &self.dot2_token { @@ -3773,7 +3884,6 @@ pub(crate) mod printing { } } - #[cfg(feature = "full")] #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for ExprTuple { fn to_tokens(&self, tokens: &mut TokenStream) { @@ -3918,4 +4028,15 @@ pub(crate) mod printing { } } } + + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] + impl ToTokens for PointerMutability { + fn to_tokens(&self, tokens: &mut TokenStream) { + match self { + PointerMutability::Const(const_token) => const_token.to_tokens(tokens), + PointerMutability::Mut(mut_token) => mut_token.to_tokens(tokens), + } + } + } } diff --git a/pkg/installer/vendor/syn/src/file.rs b/pkg/installer/vendor/syn/src/file.rs index 681125e1379..8956d82eee9 100644 --- a/pkg/installer/vendor/syn/src/file.rs +++ b/pkg/installer/vendor/syn/src/file.rs @@ -15,8 +15,7 @@ ast_struct! { /// /// ``` /// use std::env; - /// use std::fs::File; - /// use std::io::Read; + /// use std::fs; /// use std::process; /// /// fn main() { @@ -34,11 +33,7 @@ ast_struct! { /// } /// }; /// - /// let mut file = File::open(&filename).expect("unable to open file"); - /// - /// let mut src = String::new(); - /// file.read_to_string(&mut src).expect("unable to read file"); - /// + /// let src = fs::read_to_string(&filename).expect("unable to read file"); /// let syntax = syn::parse_file(&src).expect("unable to parse file"); /// /// // Debug impl is available if Syn is built with "extra-traits" feature. diff --git a/pkg/installer/vendor/syn/src/gen/clone.rs b/pkg/installer/vendor/syn/src/gen/clone.rs index de8d5745166..be2b698422d 100644 --- a/pkg/installer/vendor/syn/src/gen/clone.rs +++ b/pkg/installer/vendor/syn/src/gen/clone.rs @@ -139,6 +139,18 @@ impl Clone for crate::BoundLifetimes { } } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))] +impl Clone for crate::CapturedParam { + fn clone(&self) -> Self { + match self { + crate::CapturedParam::Lifetime(v0) => { + crate::CapturedParam::Lifetime(v0.clone()) + } + crate::CapturedParam::Ident(v0) => crate::CapturedParam::Ident(v0.clone()), + } + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))] impl Clone for crate::ConstParam { @@ -270,6 +282,8 @@ impl Clone for crate::Expr { crate::Expr::Path(v0) => crate::Expr::Path(v0.clone()), #[cfg(feature = "full")] crate::Expr::Range(v0) => crate::Expr::Range(v0.clone()), + #[cfg(feature = "full")] + crate::Expr::RawAddr(v0) => crate::Expr::RawAddr(v0.clone()), crate::Expr::Reference(v0) => crate::Expr::Reference(v0.clone()), #[cfg(feature = "full")] crate::Expr::Repeat(v0) => crate::Expr::Repeat(v0.clone()), @@ -280,7 +294,6 @@ impl Clone for crate::Expr { crate::Expr::Try(v0) => crate::Expr::Try(v0.clone()), #[cfg(feature = "full")] crate::Expr::TryBlock(v0) => crate::Expr::TryBlock(v0.clone()), - #[cfg(feature = "full")] crate::Expr::Tuple(v0) => crate::Expr::Tuple(v0.clone()), crate::Expr::Unary(v0) => crate::Expr::Unary(v0.clone()), #[cfg(feature = "full")] @@ -622,6 +635,19 @@ impl Clone for crate::ExprRange { } } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))] +impl Clone for crate::ExprRawAddr { + fn clone(&self) -> Self { + crate::ExprRawAddr { + attrs: self.attrs.clone(), + and_token: self.and_token.clone(), + raw: self.raw.clone(), + mutability: self.mutability.clone(), + expr: self.expr.clone(), + } + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))] impl Clone for crate::ExprReference { @@ -695,7 +721,7 @@ impl Clone for crate::ExprTryBlock { } } } -#[cfg(feature = "full")] +#[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))] impl Clone for crate::ExprTuple { fn clone(&self) -> Self { @@ -1648,6 +1674,32 @@ impl Clone for crate::PathSegment { } } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))] +impl Clone for crate::PointerMutability { + fn clone(&self) -> Self { + match self { + crate::PointerMutability::Const(v0) => { + crate::PointerMutability::Const(v0.clone()) + } + crate::PointerMutability::Mut(v0) => { + crate::PointerMutability::Mut(v0.clone()) + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))] +impl Clone for crate::PreciseCapture { + fn clone(&self) -> Self { + crate::PreciseCapture { + use_token: self.use_token.clone(), + lt_token: self.lt_token.clone(), + params: self.params.clone(), + gt_token: self.gt_token.clone(), + } + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))] impl Clone for crate::PredicateLifetime { @@ -1983,9 +2035,15 @@ impl Clone for crate::TypeParamBound { crate::TypeParamBound::Lifetime(v0) => { crate::TypeParamBound::Lifetime(v0.clone()) } + #[cfg(feature = "full")] + crate::TypeParamBound::PreciseCapture(v0) => { + crate::TypeParamBound::PreciseCapture(v0.clone()) + } crate::TypeParamBound::Verbatim(v0) => { crate::TypeParamBound::Verbatim(v0.clone()) } + #[cfg(not(feature = "full"))] + _ => unreachable!(), } } } diff --git a/pkg/installer/vendor/syn/src/gen/debug.rs b/pkg/installer/vendor/syn/src/gen/debug.rs index 9232ece8ac1..aa42e32c60e 100644 --- a/pkg/installer/vendor/syn/src/gen/debug.rs +++ b/pkg/installer/vendor/syn/src/gen/debug.rs @@ -290,6 +290,25 @@ impl Debug for crate::BoundLifetimes { formatter.finish() } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Debug for crate::CapturedParam { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("CapturedParam::")?; + match self { + crate::CapturedParam::Lifetime(v0) => { + let mut formatter = formatter.debug_tuple("Lifetime"); + formatter.field(v0); + formatter.finish() + } + crate::CapturedParam::Ident(v0) => { + let mut formatter = formatter.debug_tuple("Ident"); + formatter.field(v0); + formatter.finish() + } + } + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Debug for crate::ConstParam { @@ -441,6 +460,8 @@ impl Debug for crate::Expr { crate::Expr::Path(v0) => v0.debug(formatter, "Path"), #[cfg(feature = "full")] crate::Expr::Range(v0) => v0.debug(formatter, "Range"), + #[cfg(feature = "full")] + crate::Expr::RawAddr(v0) => v0.debug(formatter, "RawAddr"), crate::Expr::Reference(v0) => v0.debug(formatter, "Reference"), #[cfg(feature = "full")] crate::Expr::Repeat(v0) => v0.debug(formatter, "Repeat"), @@ -451,7 +472,6 @@ impl Debug for crate::Expr { crate::Expr::Try(v0) => v0.debug(formatter, "Try"), #[cfg(feature = "full")] crate::Expr::TryBlock(v0) => v0.debug(formatter, "TryBlock"), - #[cfg(feature = "full")] crate::Expr::Tuple(v0) => v0.debug(formatter, "Tuple"), crate::Expr::Unary(v0) => v0.debug(formatter, "Unary"), #[cfg(feature = "full")] @@ -959,6 +979,25 @@ impl crate::ExprRange { formatter.finish() } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Debug for crate::ExprRawAddr { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.debug(formatter, "ExprRawAddr") + } +} +#[cfg(feature = "full")] +impl crate::ExprRawAddr { + fn debug(&self, formatter: &mut fmt::Formatter, name: &str) -> fmt::Result { + let mut formatter = formatter.debug_struct(name); + formatter.field("attrs", &self.attrs); + formatter.field("and_token", &self.and_token); + formatter.field("raw", &self.raw); + formatter.field("mutability", &self.mutability); + formatter.field("expr", &self.expr); + formatter.finish() + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Debug for crate::ExprReference { @@ -1068,14 +1107,14 @@ impl crate::ExprTryBlock { formatter.finish() } } -#[cfg(feature = "full")] +#[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Debug for crate::ExprTuple { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.debug(formatter, "ExprTuple") } } -#[cfg(feature = "full")] +#[cfg(any(feature = "derive", feature = "full"))] impl crate::ExprTuple { fn debug(&self, formatter: &mut fmt::Formatter, name: &str) -> fmt::Result { let mut formatter = formatter.debug_struct(name); @@ -2386,6 +2425,37 @@ impl Debug for crate::PathSegment { formatter.finish() } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Debug for crate::PointerMutability { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("PointerMutability::")?; + match self { + crate::PointerMutability::Const(v0) => { + let mut formatter = formatter.debug_tuple("Const"); + formatter.field(v0); + formatter.finish() + } + crate::PointerMutability::Mut(v0) => { + let mut formatter = formatter.debug_tuple("Mut"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Debug for crate::PreciseCapture { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PreciseCapture"); + formatter.field("use_token", &self.use_token); + formatter.field("lt_token", &self.lt_token); + formatter.field("params", &self.params); + formatter.field("gt_token", &self.gt_token); + formatter.finish() + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Debug for crate::PredicateLifetime { @@ -2839,11 +2909,19 @@ impl Debug for crate::TypeParamBound { formatter.finish() } crate::TypeParamBound::Lifetime(v0) => v0.debug(formatter, "Lifetime"), + #[cfg(feature = "full")] + crate::TypeParamBound::PreciseCapture(v0) => { + let mut formatter = formatter.debug_tuple("PreciseCapture"); + formatter.field(v0); + formatter.finish() + } crate::TypeParamBound::Verbatim(v0) => { let mut formatter = formatter.debug_tuple("Verbatim"); formatter.field(v0); formatter.finish() } + #[cfg(not(feature = "full"))] + _ => unreachable!(), } } } diff --git a/pkg/installer/vendor/syn/src/gen/eq.rs b/pkg/installer/vendor/syn/src/gen/eq.rs index bbcca472815..128e8991eec 100644 --- a/pkg/installer/vendor/syn/src/gen/eq.rs +++ b/pkg/installer/vendor/syn/src/gen/eq.rs @@ -160,6 +160,25 @@ impl PartialEq for crate::BoundLifetimes { self.lifetimes == other.lifetimes } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Eq for crate::CapturedParam {} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl PartialEq for crate::CapturedParam { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + ( + crate::CapturedParam::Lifetime(self0), + crate::CapturedParam::Lifetime(other0), + ) => self0 == other0, + (crate::CapturedParam::Ident(self0), crate::CapturedParam::Ident(other0)) => { + self0 == other0 + } + _ => false, + } + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Eq for crate::ConstParam {} @@ -297,6 +316,10 @@ impl PartialEq for crate::Expr { (crate::Expr::Path(self0), crate::Expr::Path(other0)) => self0 == other0, #[cfg(feature = "full")] (crate::Expr::Range(self0), crate::Expr::Range(other0)) => self0 == other0, + #[cfg(feature = "full")] + (crate::Expr::RawAddr(self0), crate::Expr::RawAddr(other0)) => { + self0 == other0 + } (crate::Expr::Reference(self0), crate::Expr::Reference(other0)) => { self0 == other0 } @@ -311,7 +334,6 @@ impl PartialEq for crate::Expr { (crate::Expr::TryBlock(self0), crate::Expr::TryBlock(other0)) => { self0 == other0 } - #[cfg(feature = "full")] (crate::Expr::Tuple(self0), crate::Expr::Tuple(other0)) => self0 == other0, (crate::Expr::Unary(self0), crate::Expr::Unary(other0)) => self0 == other0, #[cfg(feature = "full")] @@ -611,6 +633,17 @@ impl PartialEq for crate::ExprRange { && self.limits == other.limits && self.end == other.end } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Eq for crate::ExprRawAddr {} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl PartialEq for crate::ExprRawAddr { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.mutability == other.mutability + && self.expr == other.expr + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Eq for crate::ExprReference {} @@ -674,10 +707,10 @@ impl PartialEq for crate::ExprTryBlock { self.attrs == other.attrs && self.block == other.block } } -#[cfg(feature = "full")] +#[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Eq for crate::ExprTuple {} -#[cfg(feature = "full")] +#[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl PartialEq for crate::ExprTuple { fn eq(&self, other: &Self) -> bool { @@ -1623,6 +1656,32 @@ impl PartialEq for crate::PathSegment { self.ident == other.ident && self.arguments == other.arguments } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Eq for crate::PointerMutability {} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl PartialEq for crate::PointerMutability { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (crate::PointerMutability::Const(_), crate::PointerMutability::Const(_)) => { + true + } + (crate::PointerMutability::Mut(_), crate::PointerMutability::Mut(_)) => true, + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Eq for crate::PreciseCapture {} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl PartialEq for crate::PreciseCapture { + fn eq(&self, other: &Self) -> bool { + self.params == other.params + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Eq for crate::PredicateLifetime {} @@ -1990,6 +2049,11 @@ impl PartialEq for crate::TypeParamBound { crate::TypeParamBound::Lifetime(self0), crate::TypeParamBound::Lifetime(other0), ) => self0 == other0, + #[cfg(feature = "full")] + ( + crate::TypeParamBound::PreciseCapture(self0), + crate::TypeParamBound::PreciseCapture(other0), + ) => self0 == other0, ( crate::TypeParamBound::Verbatim(self0), crate::TypeParamBound::Verbatim(other0), diff --git a/pkg/installer/vendor/syn/src/gen/fold.rs b/pkg/installer/vendor/syn/src/gen/fold.rs index e5662f58349..6ad62945e92 100644 --- a/pkg/installer/vendor/syn/src/gen/fold.rs +++ b/pkg/installer/vendor/syn/src/gen/fold.rs @@ -65,6 +65,11 @@ pub trait Fold { } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] + fn fold_attributes(&mut self, i: Vec) -> Vec { + fold_vec(i, self, Self::fold_attribute) + } + #[cfg(any(feature = "derive", feature = "full"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn fold_bare_fn_arg(&mut self, i: crate::BareFnArg) -> crate::BareFnArg { fold_bare_fn_arg(self, i) } @@ -91,6 +96,11 @@ pub trait Fold { ) -> crate::BoundLifetimes { fold_bound_lifetimes(self, i) } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn fold_captured_param(&mut self, i: crate::CapturedParam) -> crate::CapturedParam { + fold_captured_param(self, i) + } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn fold_const_param(&mut self, i: crate::ConstParam) -> crate::ConstParam { @@ -269,6 +279,11 @@ pub trait Fold { fn fold_expr_range(&mut self, i: crate::ExprRange) -> crate::ExprRange { fold_expr_range(self, i) } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn fold_expr_raw_addr(&mut self, i: crate::ExprRawAddr) -> crate::ExprRawAddr { + fold_expr_raw_addr(self, i) + } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn fold_expr_reference(&mut self, i: crate::ExprReference) -> crate::ExprReference { @@ -299,8 +314,8 @@ pub trait Fold { fn fold_expr_try_block(&mut self, i: crate::ExprTryBlock) -> crate::ExprTryBlock { fold_expr_try_block(self, i) } - #[cfg(feature = "full")] - #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + #[cfg(any(feature = "derive", feature = "full"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn fold_expr_tuple(&mut self, i: crate::ExprTuple) -> crate::ExprTuple { fold_expr_tuple(self, i) } @@ -723,6 +738,22 @@ pub trait Fold { fn fold_path_segment(&mut self, i: crate::PathSegment) -> crate::PathSegment { fold_path_segment(self, i) } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn fold_pointer_mutability( + &mut self, + i: crate::PointerMutability, + ) -> crate::PointerMutability { + fold_pointer_mutability(self, i) + } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn fold_precise_capture( + &mut self, + i: crate::PreciseCapture, + ) -> crate::PreciseCapture { + fold_precise_capture(self, i) + } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn fold_predicate_lifetime( @@ -1020,7 +1051,7 @@ where F: Fold + ?Sized, { crate::Arm { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), pat: f.fold_pat(node.pat), guard: (node.guard).map(|it| ((it).0, Box::new(f.fold_expr(*(it).1)))), fat_arrow_token: node.fat_arrow_token, @@ -1085,7 +1116,7 @@ where F: Fold + ?Sized, { crate::BareFnArg { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), name: (node.name).map(|it| (f.fold_ident((it).0), (it).1)), ty: f.fold_type(node.ty), } @@ -1097,7 +1128,7 @@ where F: Fold + ?Sized, { crate::BareVariadic { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), name: (node.name).map(|it| (f.fold_ident((it).0), (it).1)), dots: node.dots, comma: node.comma, @@ -1167,6 +1198,24 @@ where gt_token: node.gt_token, } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn fold_captured_param( + f: &mut F, + node: crate::CapturedParam, +) -> crate::CapturedParam +where + F: Fold + ?Sized, +{ + match node { + crate::CapturedParam::Lifetime(_binding_0) => { + crate::CapturedParam::Lifetime(f.fold_lifetime(_binding_0)) + } + crate::CapturedParam::Ident(_binding_0) => { + crate::CapturedParam::Ident(f.fold_ident(_binding_0)) + } + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn fold_const_param(f: &mut F, node: crate::ConstParam) -> crate::ConstParam @@ -1174,7 +1223,7 @@ where F: Fold + ?Sized, { crate::ConstParam { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), const_token: node.const_token, ident: f.fold_ident(node.ident), colon_token: node.colon_token, @@ -1254,7 +1303,7 @@ where F: Fold + ?Sized, { crate::DeriveInput { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), ident: f.fold_ident(node.ident), generics: f.fold_generics(node.generics), @@ -1339,6 +1388,9 @@ where crate::Expr::Range(_binding_0) => { crate::Expr::Range(full!(f.fold_expr_range(_binding_0))) } + crate::Expr::RawAddr(_binding_0) => { + crate::Expr::RawAddr(full!(f.fold_expr_raw_addr(_binding_0))) + } crate::Expr::Reference(_binding_0) => { crate::Expr::Reference(f.fold_expr_reference(_binding_0)) } @@ -1358,7 +1410,7 @@ where crate::Expr::TryBlock(full!(f.fold_expr_try_block(_binding_0))) } crate::Expr::Tuple(_binding_0) => { - crate::Expr::Tuple(full!(f.fold_expr_tuple(_binding_0))) + crate::Expr::Tuple(f.fold_expr_tuple(_binding_0)) } crate::Expr::Unary(_binding_0) => { crate::Expr::Unary(f.fold_expr_unary(_binding_0)) @@ -1382,7 +1434,7 @@ where F: Fold + ?Sized, { crate::ExprArray { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), bracket_token: node.bracket_token, elems: crate::punctuated::fold(node.elems, f, F::fold_expr), } @@ -1394,7 +1446,7 @@ where F: Fold + ?Sized, { crate::ExprAssign { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), left: Box::new(f.fold_expr(*node.left)), eq_token: node.eq_token, right: Box::new(f.fold_expr(*node.right)), @@ -1407,7 +1459,7 @@ where F: Fold + ?Sized, { crate::ExprAsync { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), async_token: node.async_token, capture: node.capture, block: f.fold_block(node.block), @@ -1420,7 +1472,7 @@ where F: Fold + ?Sized, { crate::ExprAwait { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), base: Box::new(f.fold_expr(*node.base)), dot_token: node.dot_token, await_token: node.await_token, @@ -1433,7 +1485,7 @@ where F: Fold + ?Sized, { crate::ExprBinary { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), left: Box::new(f.fold_expr(*node.left)), op: f.fold_bin_op(node.op), right: Box::new(f.fold_expr(*node.right)), @@ -1446,7 +1498,7 @@ where F: Fold + ?Sized, { crate::ExprBlock { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), label: (node.label).map(|it| f.fold_label(it)), block: f.fold_block(node.block), } @@ -1458,7 +1510,7 @@ where F: Fold + ?Sized, { crate::ExprBreak { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), break_token: node.break_token, label: (node.label).map(|it| f.fold_lifetime(it)), expr: (node.expr).map(|it| Box::new(f.fold_expr(*it))), @@ -1471,7 +1523,7 @@ where F: Fold + ?Sized, { crate::ExprCall { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), func: Box::new(f.fold_expr(*node.func)), paren_token: node.paren_token, args: crate::punctuated::fold(node.args, f, F::fold_expr), @@ -1484,7 +1536,7 @@ where F: Fold + ?Sized, { crate::ExprCast { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), expr: Box::new(f.fold_expr(*node.expr)), as_token: node.as_token, ty: Box::new(f.fold_type(*node.ty)), @@ -1497,7 +1549,7 @@ where F: Fold + ?Sized, { crate::ExprClosure { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), lifetimes: (node.lifetimes).map(|it| f.fold_bound_lifetimes(it)), constness: node.constness, movability: node.movability, @@ -1517,7 +1569,7 @@ where F: Fold + ?Sized, { crate::ExprConst { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), const_token: node.const_token, block: f.fold_block(node.block), } @@ -1529,7 +1581,7 @@ where F: Fold + ?Sized, { crate::ExprContinue { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), continue_token: node.continue_token, label: (node.label).map(|it| f.fold_lifetime(it)), } @@ -1541,7 +1593,7 @@ where F: Fold + ?Sized, { crate::ExprField { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), base: Box::new(f.fold_expr(*node.base)), dot_token: node.dot_token, member: f.fold_member(node.member), @@ -1554,7 +1606,7 @@ where F: Fold + ?Sized, { crate::ExprForLoop { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), label: (node.label).map(|it| f.fold_label(it)), for_token: node.for_token, pat: Box::new(f.fold_pat(*node.pat)), @@ -1570,7 +1622,7 @@ where F: Fold + ?Sized, { crate::ExprGroup { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), group_token: node.group_token, expr: Box::new(f.fold_expr(*node.expr)), } @@ -1582,7 +1634,7 @@ where F: Fold + ?Sized, { crate::ExprIf { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), if_token: node.if_token, cond: Box::new(f.fold_expr(*node.cond)), then_branch: f.fold_block(node.then_branch), @@ -1597,7 +1649,7 @@ where F: Fold + ?Sized, { crate::ExprIndex { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), expr: Box::new(f.fold_expr(*node.expr)), bracket_token: node.bracket_token, index: Box::new(f.fold_expr(*node.index)), @@ -1610,7 +1662,7 @@ where F: Fold + ?Sized, { crate::ExprInfer { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), underscore_token: node.underscore_token, } } @@ -1621,7 +1673,7 @@ where F: Fold + ?Sized, { crate::ExprLet { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), let_token: node.let_token, pat: Box::new(f.fold_pat(*node.pat)), eq_token: node.eq_token, @@ -1635,7 +1687,7 @@ where F: Fold + ?Sized, { crate::ExprLit { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), lit: f.fold_lit(node.lit), } } @@ -1646,7 +1698,7 @@ where F: Fold + ?Sized, { crate::ExprLoop { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), label: (node.label).map(|it| f.fold_label(it)), loop_token: node.loop_token, body: f.fold_block(node.body), @@ -1659,7 +1711,7 @@ where F: Fold + ?Sized, { crate::ExprMacro { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), mac: f.fold_macro(node.mac), } } @@ -1670,7 +1722,7 @@ where F: Fold + ?Sized, { crate::ExprMatch { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), match_token: node.match_token, expr: Box::new(f.fold_expr(*node.expr)), brace_token: node.brace_token, @@ -1687,7 +1739,7 @@ where F: Fold + ?Sized, { crate::ExprMethodCall { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), receiver: Box::new(f.fold_expr(*node.receiver)), dot_token: node.dot_token, method: f.fold_ident(node.method), @@ -1704,7 +1756,7 @@ where F: Fold + ?Sized, { crate::ExprParen { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), paren_token: node.paren_token, expr: Box::new(f.fold_expr(*node.expr)), } @@ -1716,7 +1768,7 @@ where F: Fold + ?Sized, { crate::ExprPath { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), qself: (node.qself).map(|it| f.fold_qself(it)), path: f.fold_path(node.path), } @@ -1728,12 +1780,26 @@ where F: Fold + ?Sized, { crate::ExprRange { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), start: (node.start).map(|it| Box::new(f.fold_expr(*it))), limits: f.fold_range_limits(node.limits), end: (node.end).map(|it| Box::new(f.fold_expr(*it))), } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn fold_expr_raw_addr(f: &mut F, node: crate::ExprRawAddr) -> crate::ExprRawAddr +where + F: Fold + ?Sized, +{ + crate::ExprRawAddr { + attrs: f.fold_attributes(node.attrs), + and_token: node.and_token, + raw: node.raw, + mutability: f.fold_pointer_mutability(node.mutability), + expr: Box::new(f.fold_expr(*node.expr)), + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn fold_expr_reference( @@ -1744,7 +1810,7 @@ where F: Fold + ?Sized, { crate::ExprReference { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), and_token: node.and_token, mutability: node.mutability, expr: Box::new(f.fold_expr(*node.expr)), @@ -1757,7 +1823,7 @@ where F: Fold + ?Sized, { crate::ExprRepeat { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), bracket_token: node.bracket_token, expr: Box::new(f.fold_expr(*node.expr)), semi_token: node.semi_token, @@ -1771,7 +1837,7 @@ where F: Fold + ?Sized, { crate::ExprReturn { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), return_token: node.return_token, expr: (node.expr).map(|it| Box::new(f.fold_expr(*it))), } @@ -1783,7 +1849,7 @@ where F: Fold + ?Sized, { crate::ExprStruct { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), qself: (node.qself).map(|it| f.fold_qself(it)), path: f.fold_path(node.path), brace_token: node.brace_token, @@ -1799,7 +1865,7 @@ where F: Fold + ?Sized, { crate::ExprTry { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), expr: Box::new(f.fold_expr(*node.expr)), question_token: node.question_token, } @@ -1814,19 +1880,19 @@ where F: Fold + ?Sized, { crate::ExprTryBlock { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), try_token: node.try_token, block: f.fold_block(node.block), } } -#[cfg(feature = "full")] -#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn fold_expr_tuple(f: &mut F, node: crate::ExprTuple) -> crate::ExprTuple where F: Fold + ?Sized, { crate::ExprTuple { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), paren_token: node.paren_token, elems: crate::punctuated::fold(node.elems, f, F::fold_expr), } @@ -1838,7 +1904,7 @@ where F: Fold + ?Sized, { crate::ExprUnary { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), op: f.fold_un_op(node.op), expr: Box::new(f.fold_expr(*node.expr)), } @@ -1850,7 +1916,7 @@ where F: Fold + ?Sized, { crate::ExprUnsafe { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), unsafe_token: node.unsafe_token, block: f.fold_block(node.block), } @@ -1862,7 +1928,7 @@ where F: Fold + ?Sized, { crate::ExprWhile { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), label: (node.label).map(|it| f.fold_label(it)), while_token: node.while_token, cond: Box::new(f.fold_expr(*node.cond)), @@ -1876,7 +1942,7 @@ where F: Fold + ?Sized, { crate::ExprYield { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), yield_token: node.yield_token, expr: (node.expr).map(|it| Box::new(f.fold_expr(*it))), } @@ -1888,7 +1954,7 @@ where F: Fold + ?Sized, { crate::Field { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), mutability: f.fold_field_mutability(node.mutability), ident: (node.ident).map(|it| f.fold_ident(it)), @@ -1916,7 +1982,7 @@ where F: Fold + ?Sized, { crate::FieldPat { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), member: f.fold_member(node.member), colon_token: node.colon_token, pat: Box::new(f.fold_pat(*node.pat)), @@ -1929,7 +1995,7 @@ where F: Fold + ?Sized, { crate::FieldValue { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), member: f.fold_member(node.member), colon_token: node.colon_token, expr: f.fold_expr(node.expr), @@ -1984,7 +2050,7 @@ where { crate::File { shebang: node.shebang, - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), items: fold_vec(node.items, f, F::fold_item), } } @@ -2037,7 +2103,7 @@ where F: Fold + ?Sized, { crate::ForeignItemFn { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), sig: f.fold_signature(node.sig), semi_token: node.semi_token, @@ -2053,7 +2119,7 @@ where F: Fold + ?Sized, { crate::ForeignItemMacro { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), mac: f.fold_macro(node.mac), semi_token: node.semi_token, } @@ -2068,7 +2134,7 @@ where F: Fold + ?Sized, { crate::ForeignItemStatic { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), static_token: node.static_token, mutability: f.fold_static_mutability(node.mutability), @@ -2088,7 +2154,7 @@ where F: Fold + ?Sized, { crate::ForeignItemType { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), type_token: node.type_token, ident: f.fold_ident(node.ident), @@ -2198,7 +2264,7 @@ where F: Fold + ?Sized, { crate::ImplItemConst { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), defaultness: node.defaultness, const_token: node.const_token, @@ -2218,7 +2284,7 @@ where F: Fold + ?Sized, { crate::ImplItemFn { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), defaultness: node.defaultness, sig: f.fold_signature(node.sig), @@ -2235,7 +2301,7 @@ where F: Fold + ?Sized, { crate::ImplItemMacro { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), mac: f.fold_macro(node.mac), semi_token: node.semi_token, } @@ -2250,7 +2316,7 @@ where F: Fold + ?Sized, { crate::ImplItemType { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), defaultness: node.defaultness, type_token: node.type_token, @@ -2333,7 +2399,7 @@ where F: Fold + ?Sized, { crate::ItemConst { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), const_token: node.const_token, ident: f.fold_ident(node.ident), @@ -2352,7 +2418,7 @@ where F: Fold + ?Sized, { crate::ItemEnum { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), enum_token: node.enum_token, ident: f.fold_ident(node.ident), @@ -2371,7 +2437,7 @@ where F: Fold + ?Sized, { crate::ItemExternCrate { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), extern_token: node.extern_token, crate_token: node.crate_token, @@ -2387,7 +2453,7 @@ where F: Fold + ?Sized, { crate::ItemFn { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), sig: f.fold_signature(node.sig), block: Box::new(f.fold_block(*node.block)), @@ -2403,7 +2469,7 @@ where F: Fold + ?Sized, { crate::ItemForeignMod { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), unsafety: node.unsafety, abi: f.fold_abi(node.abi), brace_token: node.brace_token, @@ -2417,7 +2483,7 @@ where F: Fold + ?Sized, { crate::ItemImpl { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), defaultness: node.defaultness, unsafety: node.unsafety, impl_token: node.impl_token, @@ -2435,7 +2501,7 @@ where F: Fold + ?Sized, { crate::ItemMacro { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), ident: (node.ident).map(|it| f.fold_ident(it)), mac: f.fold_macro(node.mac), semi_token: node.semi_token, @@ -2448,7 +2514,7 @@ where F: Fold + ?Sized, { crate::ItemMod { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), unsafety: node.unsafety, mod_token: node.mod_token, @@ -2464,7 +2530,7 @@ where F: Fold + ?Sized, { crate::ItemStatic { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), static_token: node.static_token, mutability: f.fold_static_mutability(node.mutability), @@ -2483,7 +2549,7 @@ where F: Fold + ?Sized, { crate::ItemStruct { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), struct_token: node.struct_token, ident: f.fold_ident(node.ident), @@ -2499,7 +2565,7 @@ where F: Fold + ?Sized, { crate::ItemTrait { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), unsafety: node.unsafety, auto_token: node.auto_token, @@ -2527,7 +2593,7 @@ where F: Fold + ?Sized, { crate::ItemTraitAlias { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), trait_token: node.trait_token, ident: f.fold_ident(node.ident), @@ -2544,7 +2610,7 @@ where F: Fold + ?Sized, { crate::ItemType { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), type_token: node.type_token, ident: f.fold_ident(node.ident), @@ -2561,7 +2627,7 @@ where F: Fold + ?Sized, { crate::ItemUnion { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), union_token: node.union_token, ident: f.fold_ident(node.ident), @@ -2576,7 +2642,7 @@ where F: Fold + ?Sized, { crate::ItemUse { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), vis: f.fold_visibility(node.vis), use_token: node.use_token, leading_colon: node.leading_colon, @@ -2614,7 +2680,7 @@ where F: Fold + ?Sized, { crate::LifetimeParam { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), lifetime: f.fold_lifetime(node.lifetime), colon_token: node.colon_token, bounds: crate::punctuated::fold(node.bounds, f, F::fold_lifetime), @@ -2717,7 +2783,7 @@ where F: Fold + ?Sized, { crate::Local { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), let_token: node.let_token, pat: f.fold_pat(node.pat), init: (node.init).map(|it| f.fold_local_init(it)), @@ -2880,7 +2946,7 @@ where F: Fold + ?Sized, { crate::PatIdent { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), by_ref: node.by_ref, mutability: node.mutability, ident: f.fold_ident(node.ident), @@ -2894,7 +2960,7 @@ where F: Fold + ?Sized, { crate::PatOr { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), leading_vert: node.leading_vert, cases: crate::punctuated::fold(node.cases, f, F::fold_pat), } @@ -2906,7 +2972,7 @@ where F: Fold + ?Sized, { crate::PatParen { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), paren_token: node.paren_token, pat: Box::new(f.fold_pat(*node.pat)), } @@ -2918,7 +2984,7 @@ where F: Fold + ?Sized, { crate::PatReference { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), and_token: node.and_token, mutability: node.mutability, pat: Box::new(f.fold_pat(*node.pat)), @@ -2931,7 +2997,7 @@ where F: Fold + ?Sized, { crate::PatRest { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), dot2_token: node.dot2_token, } } @@ -2942,7 +3008,7 @@ where F: Fold + ?Sized, { crate::PatSlice { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), bracket_token: node.bracket_token, elems: crate::punctuated::fold(node.elems, f, F::fold_pat), } @@ -2954,7 +3020,7 @@ where F: Fold + ?Sized, { crate::PatStruct { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), qself: (node.qself).map(|it| f.fold_qself(it)), path: f.fold_path(node.path), brace_token: node.brace_token, @@ -2969,7 +3035,7 @@ where F: Fold + ?Sized, { crate::PatTuple { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), paren_token: node.paren_token, elems: crate::punctuated::fold(node.elems, f, F::fold_pat), } @@ -2984,7 +3050,7 @@ where F: Fold + ?Sized, { crate::PatTupleStruct { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), qself: (node.qself).map(|it| f.fold_qself(it)), path: f.fold_path(node.path), paren_token: node.paren_token, @@ -2998,7 +3064,7 @@ where F: Fold + ?Sized, { crate::PatType { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), pat: Box::new(f.fold_pat(*node.pat)), colon_token: node.colon_token, ty: Box::new(f.fold_type(*node.ty)), @@ -3011,7 +3077,7 @@ where F: Fold + ?Sized, { crate::PatWild { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), underscore_token: node.underscore_token, } } @@ -3060,6 +3126,40 @@ where arguments: f.fold_path_arguments(node.arguments), } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn fold_pointer_mutability( + f: &mut F, + node: crate::PointerMutability, +) -> crate::PointerMutability +where + F: Fold + ?Sized, +{ + match node { + crate::PointerMutability::Const(_binding_0) => { + crate::PointerMutability::Const(_binding_0) + } + crate::PointerMutability::Mut(_binding_0) => { + crate::PointerMutability::Mut(_binding_0) + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn fold_precise_capture( + f: &mut F, + node: crate::PreciseCapture, +) -> crate::PreciseCapture +where + F: Fold + ?Sized, +{ + crate::PreciseCapture { + use_token: node.use_token, + lt_token: node.lt_token, + params: crate::punctuated::fold(node.params, f, F::fold_captured_param), + gt_token: node.gt_token, + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn fold_predicate_lifetime( @@ -3125,7 +3225,7 @@ where F: Fold + ?Sized, { crate::Receiver { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), reference: (node.reference) .map(|it| ((it).0, ((it).1).map(|it| f.fold_lifetime(it)))), mutability: node.mutability, @@ -3213,7 +3313,7 @@ where F: Fold + ?Sized, { crate::StmtMacro { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), mac: f.fold_macro(node.mac), semi_token: node.semi_token, } @@ -3279,7 +3379,7 @@ where F: Fold + ?Sized, { crate::TraitItemConst { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), const_token: node.const_token, ident: f.fold_ident(node.ident), generics: f.fold_generics(node.generics), @@ -3296,7 +3396,7 @@ where F: Fold + ?Sized, { crate::TraitItemFn { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), sig: f.fold_signature(node.sig), default: (node.default).map(|it| f.fold_block(it)), semi_token: node.semi_token, @@ -3312,7 +3412,7 @@ where F: Fold + ?Sized, { crate::TraitItemMacro { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), mac: f.fold_macro(node.mac), semi_token: node.semi_token, } @@ -3327,7 +3427,7 @@ where F: Fold + ?Sized, { crate::TraitItemType { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), type_token: node.type_token, ident: f.fold_ident(node.ident), generics: f.fold_generics(node.generics), @@ -3477,7 +3577,7 @@ where F: Fold + ?Sized, { crate::TypeParam { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), ident: f.fold_ident(node.ident), colon_token: node.colon_token, bounds: crate::punctuated::fold(node.bounds, f, F::fold_type_param_bound), @@ -3501,6 +3601,11 @@ where crate::TypeParamBound::Lifetime(_binding_0) => { crate::TypeParamBound::Lifetime(f.fold_lifetime(_binding_0)) } + crate::TypeParamBound::PreciseCapture(_binding_0) => { + crate::TypeParamBound::PreciseCapture( + full!(f.fold_precise_capture(_binding_0)), + ) + } crate::TypeParamBound::Verbatim(_binding_0) => { crate::TypeParamBound::Verbatim(_binding_0) } @@ -3691,7 +3796,7 @@ where F: Fold + ?Sized, { crate::Variadic { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), pat: (node.pat).map(|it| (Box::new(f.fold_pat(*(it).0)), (it).1)), dots: node.dots, comma: node.comma, @@ -3704,7 +3809,7 @@ where F: Fold + ?Sized, { crate::Variant { - attrs: fold_vec(node.attrs, f, F::fold_attribute), + attrs: f.fold_attributes(node.attrs), ident: f.fold_ident(node.ident), fields: f.fold_fields(node.fields), discriminant: (node.discriminant).map(|it| ((it).0, f.fold_expr((it).1))), diff --git a/pkg/installer/vendor/syn/src/gen/hash.rs b/pkg/installer/vendor/syn/src/gen/hash.rs index 02097b9d6e2..04f23453a11 100644 --- a/pkg/installer/vendor/syn/src/gen/hash.rs +++ b/pkg/installer/vendor/syn/src/gen/hash.rs @@ -230,6 +230,25 @@ impl Hash for crate::BoundLifetimes { self.lifetimes.hash(state); } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Hash for crate::CapturedParam { + fn hash(&self, state: &mut H) + where + H: Hasher, + { + match self { + crate::CapturedParam::Lifetime(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + crate::CapturedParam::Ident(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + } + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Hash for crate::ConstParam { @@ -456,60 +475,64 @@ impl Hash for crate::Expr { state.write_u8(26u8); v0.hash(state); } - crate::Expr::Reference(v0) => { + #[cfg(feature = "full")] + crate::Expr::RawAddr(v0) => { state.write_u8(27u8); v0.hash(state); } + crate::Expr::Reference(v0) => { + state.write_u8(28u8); + v0.hash(state); + } #[cfg(feature = "full")] crate::Expr::Repeat(v0) => { - state.write_u8(28u8); + state.write_u8(29u8); v0.hash(state); } #[cfg(feature = "full")] crate::Expr::Return(v0) => { - state.write_u8(29u8); + state.write_u8(30u8); v0.hash(state); } crate::Expr::Struct(v0) => { - state.write_u8(30u8); + state.write_u8(31u8); v0.hash(state); } #[cfg(feature = "full")] crate::Expr::Try(v0) => { - state.write_u8(31u8); + state.write_u8(32u8); v0.hash(state); } #[cfg(feature = "full")] crate::Expr::TryBlock(v0) => { - state.write_u8(32u8); + state.write_u8(33u8); v0.hash(state); } - #[cfg(feature = "full")] crate::Expr::Tuple(v0) => { - state.write_u8(33u8); + state.write_u8(34u8); v0.hash(state); } crate::Expr::Unary(v0) => { - state.write_u8(34u8); + state.write_u8(35u8); v0.hash(state); } #[cfg(feature = "full")] crate::Expr::Unsafe(v0) => { - state.write_u8(35u8); + state.write_u8(36u8); v0.hash(state); } crate::Expr::Verbatim(v0) => { - state.write_u8(36u8); + state.write_u8(37u8); TokenStreamHelper(v0).hash(state); } #[cfg(feature = "full")] crate::Expr::While(v0) => { - state.write_u8(37u8); + state.write_u8(38u8); v0.hash(state); } #[cfg(feature = "full")] crate::Expr::Yield(v0) => { - state.write_u8(38u8); + state.write_u8(39u8); v0.hash(state); } #[cfg(not(feature = "full"))] @@ -844,6 +867,18 @@ impl Hash for crate::ExprRange { self.end.hash(state); } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Hash for crate::ExprRawAddr { + fn hash(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.mutability.hash(state); + self.expr.hash(state); + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Hash for crate::ExprReference { @@ -916,7 +951,7 @@ impl Hash for crate::ExprTryBlock { self.block.hash(state); } } -#[cfg(feature = "full")] +#[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Hash for crate::ExprTuple { fn hash(&self, state: &mut H) @@ -2087,6 +2122,33 @@ impl Hash for crate::PathSegment { self.arguments.hash(state); } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Hash for crate::PointerMutability { + fn hash(&self, state: &mut H) + where + H: Hasher, + { + match self { + crate::PointerMutability::Const(_) => { + state.write_u8(0u8); + } + crate::PointerMutability::Mut(_) => { + state.write_u8(1u8); + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] +impl Hash for crate::PreciseCapture { + fn hash(&self, state: &mut H) + where + H: Hasher, + { + self.params.hash(state); + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))] impl Hash for crate::PredicateLifetime { @@ -2535,10 +2597,17 @@ impl Hash for crate::TypeParamBound { state.write_u8(1u8); v0.hash(state); } - crate::TypeParamBound::Verbatim(v0) => { + #[cfg(feature = "full")] + crate::TypeParamBound::PreciseCapture(v0) => { state.write_u8(2u8); + v0.hash(state); + } + crate::TypeParamBound::Verbatim(v0) => { + state.write_u8(3u8); TokenStreamHelper(v0).hash(state); } + #[cfg(not(feature = "full"))] + _ => unreachable!(), } } } diff --git a/pkg/installer/vendor/syn/src/gen/token.css b/pkg/installer/vendor/syn/src/gen/token.css new file mode 100644 index 00000000000..ed82ae1502b --- /dev/null +++ b/pkg/installer/vendor/syn/src/gen/token.css @@ -0,0 +1,737 @@ +a.struct[title="struct syn::token::Abstract"], +a.struct[title="struct syn::token::And"], +a.struct[title="struct syn::token::AndAnd"], +a.struct[title="struct syn::token::AndEq"], +a.struct[title="struct syn::token::As"], +a.struct[title="struct syn::token::Async"], +a.struct[title="struct syn::token::At"], +a.struct[title="struct syn::token::Auto"], +a.struct[title="struct syn::token::Await"], +a.struct[title="struct syn::token::Become"], +a.struct[title="struct syn::token::Box"], +a.struct[title="struct syn::token::Break"], +a.struct[title="struct syn::token::Caret"], +a.struct[title="struct syn::token::CaretEq"], +a.struct[title="struct syn::token::Colon"], +a.struct[title="struct syn::token::Comma"], +a.struct[title="struct syn::token::Const"], +a.struct[title="struct syn::token::Continue"], +a.struct[title="struct syn::token::Crate"], +a.struct[title="struct syn::token::Default"], +a.struct[title="struct syn::token::Do"], +a.struct[title="struct syn::token::Dollar"], +a.struct[title="struct syn::token::Dot"], +a.struct[title="struct syn::token::DotDot"], +a.struct[title="struct syn::token::DotDotDot"], +a.struct[title="struct syn::token::DotDotEq"], +a.struct[title="struct syn::token::Dyn"], +a.struct[title="struct syn::token::Else"], +a.struct[title="struct syn::token::Enum"], +a.struct[title="struct syn::token::Eq"], +a.struct[title="struct syn::token::EqEq"], +a.struct[title="struct syn::token::Extern"], +a.struct[title="struct syn::token::FatArrow"], +a.struct[title="struct syn::token::Final"], +a.struct[title="struct syn::token::Fn"], +a.struct[title="struct syn::token::For"], +a.struct[title="struct syn::token::Ge"], +a.struct[title="struct syn::token::Gt"], +a.struct[title="struct syn::token::If"], +a.struct[title="struct syn::token::Impl"], +a.struct[title="struct syn::token::In"], +a.struct[title="struct syn::token::LArrow"], +a.struct[title="struct syn::token::Le"], +a.struct[title="struct syn::token::Let"], +a.struct[title="struct syn::token::Loop"], +a.struct[title="struct syn::token::Lt"], +a.struct[title="struct syn::token::Macro"], +a.struct[title="struct syn::token::Match"], +a.struct[title="struct syn::token::Minus"], +a.struct[title="struct syn::token::MinusEq"], +a.struct[title="struct syn::token::Mod"], +a.struct[title="struct syn::token::Move"], +a.struct[title="struct syn::token::Mut"], +a.struct[title="struct syn::token::Ne"], +a.struct[title="struct syn::token::Not"], +a.struct[title="struct syn::token::Or"], +a.struct[title="struct syn::token::OrEq"], +a.struct[title="struct syn::token::OrOr"], +a.struct[title="struct syn::token::Override"], +a.struct[title="struct syn::token::PathSep"], +a.struct[title="struct syn::token::Percent"], +a.struct[title="struct syn::token::PercentEq"], +a.struct[title="struct syn::token::Plus"], +a.struct[title="struct syn::token::PlusEq"], +a.struct[title="struct syn::token::Pound"], +a.struct[title="struct syn::token::Priv"], +a.struct[title="struct syn::token::Pub"], +a.struct[title="struct syn::token::Question"], +a.struct[title="struct syn::token::RArrow"], +a.struct[title="struct syn::token::Raw"], +a.struct[title="struct syn::token::Ref"], +a.struct[title="struct syn::token::Return"], +a.struct[title="struct syn::token::SelfType"], +a.struct[title="struct syn::token::SelfValue"], +a.struct[title="struct syn::token::Semi"], +a.struct[title="struct syn::token::Shl"], +a.struct[title="struct syn::token::ShlEq"], +a.struct[title="struct syn::token::Shr"], +a.struct[title="struct syn::token::ShrEq"], +a.struct[title="struct syn::token::Slash"], +a.struct[title="struct syn::token::SlashEq"], +a.struct[title="struct syn::token::Star"], +a.struct[title="struct syn::token::StarEq"], +a.struct[title="struct syn::token::Static"], +a.struct[title="struct syn::token::Struct"], +a.struct[title="struct syn::token::Super"], +a.struct[title="struct syn::token::Tilde"], +a.struct[title="struct syn::token::Trait"], +a.struct[title="struct syn::token::Try"], +a.struct[title="struct syn::token::Type"], +a.struct[title="struct syn::token::Typeof"], +a.struct[title="struct syn::token::Underscore"], +a.struct[title="struct syn::token::Union"], +a.struct[title="struct syn::token::Unsafe"], +a.struct[title="struct syn::token::Unsized"], +a.struct[title="struct syn::token::Use"], +a.struct[title="struct syn::token::Virtual"], +a.struct[title="struct syn::token::Where"], +a.struct[title="struct syn::token::While"], +a.struct[title="struct syn::token::Yield"] { + display: inline-block; + color: transparent; + white-space: nowrap; +} + +a.struct[title="struct syn::token::Abstract"]::before, +a.struct[title="struct syn::token::And"]::before, +a.struct[title="struct syn::token::AndAnd"]::before, +a.struct[title="struct syn::token::AndEq"]::before, +a.struct[title="struct syn::token::As"]::before, +a.struct[title="struct syn::token::Async"]::before, +a.struct[title="struct syn::token::At"]::before, +a.struct[title="struct syn::token::Auto"]::before, +a.struct[title="struct syn::token::Await"]::before, +a.struct[title="struct syn::token::Become"]::before, +a.struct[title="struct syn::token::Box"]::before, +a.struct[title="struct syn::token::Break"]::before, +a.struct[title="struct syn::token::Caret"]::before, +a.struct[title="struct syn::token::CaretEq"]::before, +a.struct[title="struct syn::token::Colon"]::before, +a.struct[title="struct syn::token::Comma"]::before, +a.struct[title="struct syn::token::Const"]::before, +a.struct[title="struct syn::token::Continue"]::before, +a.struct[title="struct syn::token::Crate"]::before, +a.struct[title="struct syn::token::Default"]::before, +a.struct[title="struct syn::token::Do"]::before, +a.struct[title="struct syn::token::Dollar"]::before, +a.struct[title="struct syn::token::Dot"]::before, +a.struct[title="struct syn::token::DotDot"]::before, +a.struct[title="struct syn::token::DotDotDot"]::before, +a.struct[title="struct syn::token::DotDotEq"]::before, +a.struct[title="struct syn::token::Dyn"]::before, +a.struct[title="struct syn::token::Else"]::before, +a.struct[title="struct syn::token::Enum"]::before, +a.struct[title="struct syn::token::Eq"]::before, +a.struct[title="struct syn::token::EqEq"]::before, +a.struct[title="struct syn::token::Extern"]::before, +a.struct[title="struct syn::token::FatArrow"]::before, +a.struct[title="struct syn::token::Final"]::before, +a.struct[title="struct syn::token::Fn"]::before, +a.struct[title="struct syn::token::For"]::before, +a.struct[title="struct syn::token::Ge"]::before, +a.struct[title="struct syn::token::Gt"]::before, +a.struct[title="struct syn::token::If"]::before, +a.struct[title="struct syn::token::Impl"]::before, +a.struct[title="struct syn::token::In"]::before, +a.struct[title="struct syn::token::LArrow"]::before, +a.struct[title="struct syn::token::Le"]::before, +a.struct[title="struct syn::token::Let"]::before, +a.struct[title="struct syn::token::Loop"]::before, +a.struct[title="struct syn::token::Lt"]::before, +a.struct[title="struct syn::token::Macro"]::before, +a.struct[title="struct syn::token::Match"]::before, +a.struct[title="struct syn::token::Minus"]::before, +a.struct[title="struct syn::token::MinusEq"]::before, +a.struct[title="struct syn::token::Mod"]::before, +a.struct[title="struct syn::token::Move"]::before, +a.struct[title="struct syn::token::Mut"]::before, +a.struct[title="struct syn::token::Ne"]::before, +a.struct[title="struct syn::token::Not"]::before, +a.struct[title="struct syn::token::Or"]::before, +a.struct[title="struct syn::token::OrEq"]::before, +a.struct[title="struct syn::token::OrOr"]::before, +a.struct[title="struct syn::token::Override"]::before, +a.struct[title="struct syn::token::PathSep"]::before, +a.struct[title="struct syn::token::Percent"]::before, +a.struct[title="struct syn::token::PercentEq"]::before, +a.struct[title="struct syn::token::Plus"]::before, +a.struct[title="struct syn::token::PlusEq"]::before, +a.struct[title="struct syn::token::Pound"]::before, +a.struct[title="struct syn::token::Priv"]::before, +a.struct[title="struct syn::token::Pub"]::before, +a.struct[title="struct syn::token::Question"]::before, +a.struct[title="struct syn::token::RArrow"]::before, +a.struct[title="struct syn::token::Raw"]::before, +a.struct[title="struct syn::token::Ref"]::before, +a.struct[title="struct syn::token::Return"]::before, +a.struct[title="struct syn::token::SelfType"]::before, +a.struct[title="struct syn::token::SelfValue"]::before, +a.struct[title="struct syn::token::Semi"]::before, +a.struct[title="struct syn::token::Shl"]::before, +a.struct[title="struct syn::token::ShlEq"]::before, +a.struct[title="struct syn::token::Shr"]::before, +a.struct[title="struct syn::token::ShrEq"]::before, +a.struct[title="struct syn::token::Slash"]::before, +a.struct[title="struct syn::token::SlashEq"]::before, +a.struct[title="struct syn::token::Star"]::before, +a.struct[title="struct syn::token::StarEq"]::before, +a.struct[title="struct syn::token::Static"]::before, +a.struct[title="struct syn::token::Struct"]::before, +a.struct[title="struct syn::token::Super"]::before, +a.struct[title="struct syn::token::Tilde"]::before, +a.struct[title="struct syn::token::Trait"]::before, +a.struct[title="struct syn::token::Try"]::before, +a.struct[title="struct syn::token::Type"]::before, +a.struct[title="struct syn::token::Typeof"]::before, +a.struct[title="struct syn::token::Underscore"]::before, +a.struct[title="struct syn::token::Union"]::before, +a.struct[title="struct syn::token::Unsafe"]::before, +a.struct[title="struct syn::token::Unsized"]::before, +a.struct[title="struct syn::token::Use"]::before, +a.struct[title="struct syn::token::Virtual"]::before, +a.struct[title="struct syn::token::Where"]::before, +a.struct[title="struct syn::token::While"]::before, +a.struct[title="struct syn::token::Yield"]::before { + display: inline-block; + color: var(--type-link-color); + width: 0; +} + +a.struct[title="struct syn::token::Abstract"]::before { + content: "Token![abstract]"; +} + +a.struct[title="struct syn::token::And"]::before { + content: "Token![&]"; +} + +a.struct[title="struct syn::token::AndAnd"]::before { + content: "Token![&&]"; +} + +a.struct[title="struct syn::token::AndEq"]::before { + content: "Token![&=]"; +} + +a.struct[title="struct syn::token::As"]::before { + content: "Token![as]"; +} + +a.struct[title="struct syn::token::Async"]::before { + content: "Token![async]"; +} + +a.struct[title="struct syn::token::At"]::before { + content: "Token![@]"; +} + +a.struct[title="struct syn::token::Auto"]::before { + content: "Token![auto]"; +} + +a.struct[title="struct syn::token::Await"]::before { + content: "Token![await]"; +} + +a.struct[title="struct syn::token::Become"]::before { + content: "Token![become]"; +} + +a.struct[title="struct syn::token::Box"]::before { + content: "Token![box]"; +} + +a.struct[title="struct syn::token::Break"]::before { + content: "Token![break]"; +} + +a.struct[title="struct syn::token::Caret"]::before { + content: "Token![^]"; +} + +a.struct[title="struct syn::token::CaretEq"]::before { + content: "Token![^=]"; +} + +a.struct[title="struct syn::token::Colon"]::before { + content: "Token![:]"; +} + +a.struct[title="struct syn::token::Comma"]::before { + content: "Token![,]"; +} + +a.struct[title="struct syn::token::Const"]::before { + content: "Token![const]"; +} + +a.struct[title="struct syn::token::Continue"]::before { + content: "Token![continue]"; +} + +a.struct[title="struct syn::token::Crate"]::before { + content: "Token![crate]"; +} + +a.struct[title="struct syn::token::Default"]::before { + content: "Token![default]"; +} + +a.struct[title="struct syn::token::Do"]::before { + content: "Token![do]"; +} + +a.struct[title="struct syn::token::Dollar"]::before { + content: "Token![$]"; +} + +a.struct[title="struct syn::token::Dot"]::before { + content: "Token![.]"; +} + +a.struct[title="struct syn::token::DotDot"]::before { + content: "Token![..]"; +} + +a.struct[title="struct syn::token::DotDotDot"]::before { + content: "Token![...]"; +} + +a.struct[title="struct syn::token::DotDotEq"]::before { + content: "Token![..=]"; +} + +a.struct[title="struct syn::token::Dyn"]::before { + content: "Token![dyn]"; +} + +a.struct[title="struct syn::token::Else"]::before { + content: "Token![else]"; +} + +a.struct[title="struct syn::token::Enum"]::before { + content: "Token![enum]"; +} + +a.struct[title="struct syn::token::Eq"]::before { + content: "Token![=]"; +} + +a.struct[title="struct syn::token::EqEq"]::before { + content: "Token![==]"; +} + +a.struct[title="struct syn::token::Extern"]::before { + content: "Token![extern]"; +} + +a.struct[title="struct syn::token::FatArrow"]::before { + content: "Token![=>]"; +} + +a.struct[title="struct syn::token::Final"]::before { + content: "Token![final]"; +} + +a.struct[title="struct syn::token::Fn"]::before { + content: "Token![fn]"; +} + +a.struct[title="struct syn::token::For"]::before { + content: "Token![for]"; +} + +a.struct[title="struct syn::token::Ge"]::before { + content: "Token![>=]"; +} + +a.struct[title="struct syn::token::Gt"]::before { + content: "Token![>]"; +} + +a.struct[title="struct syn::token::If"]::before { + content: "Token![if]"; +} + +a.struct[title="struct syn::token::Impl"]::before { + content: "Token![impl]"; +} + +a.struct[title="struct syn::token::In"]::before { + content: "Token![in]"; +} + +a.struct[title="struct syn::token::LArrow"]::before { + content: "Token![<-]"; +} + +a.struct[title="struct syn::token::Le"]::before { + content: "Token![<=]"; +} + +a.struct[title="struct syn::token::Let"]::before { + content: "Token![let]"; +} + +a.struct[title="struct syn::token::Loop"]::before { + content: "Token![loop]"; +} + +a.struct[title="struct syn::token::Lt"]::before { + content: "Token![<]"; +} + +a.struct[title="struct syn::token::Macro"]::before { + content: "Token![macro]"; +} + +a.struct[title="struct syn::token::Match"]::before { + content: "Token![match]"; +} + +a.struct[title="struct syn::token::Minus"]::before { + content: "Token![-]"; +} + +a.struct[title="struct syn::token::MinusEq"]::before { + content: "Token![-=]"; +} + +a.struct[title="struct syn::token::Mod"]::before { + content: "Token![mod]"; +} + +a.struct[title="struct syn::token::Move"]::before { + content: "Token![move]"; +} + +a.struct[title="struct syn::token::Mut"]::before { + content: "Token![mut]"; +} + +a.struct[title="struct syn::token::Ne"]::before { + content: "Token![!=]"; +} + +a.struct[title="struct syn::token::Not"]::before { + content: "Token![!]"; +} + +a.struct[title="struct syn::token::Or"]::before { + content: "Token![|]"; +} + +a.struct[title="struct syn::token::OrEq"]::before { + content: "Token![|=]"; +} + +a.struct[title="struct syn::token::OrOr"]::before { + content: "Token![||]"; +} + +a.struct[title="struct syn::token::Override"]::before { + content: "Token![override]"; +} + +a.struct[title="struct syn::token::PathSep"]::before { + content: "Token![::]"; +} + +a.struct[title="struct syn::token::Percent"]::before { + content: "Token![%]"; +} + +a.struct[title="struct syn::token::PercentEq"]::before { + content: "Token![%=]"; +} + +a.struct[title="struct syn::token::Plus"]::before { + content: "Token![+]"; +} + +a.struct[title="struct syn::token::PlusEq"]::before { + content: "Token![+=]"; +} + +a.struct[title="struct syn::token::Pound"]::before { + content: "Token![#]"; +} + +a.struct[title="struct syn::token::Priv"]::before { + content: "Token![priv]"; +} + +a.struct[title="struct syn::token::Pub"]::before { + content: "Token![pub]"; +} + +a.struct[title="struct syn::token::Question"]::before { + content: "Token![?]"; +} + +a.struct[title="struct syn::token::RArrow"]::before { + content: "Token![->]"; +} + +a.struct[title="struct syn::token::Raw"]::before { + content: "Token![raw]"; +} + +a.struct[title="struct syn::token::Ref"]::before { + content: "Token![ref]"; +} + +a.struct[title="struct syn::token::Return"]::before { + content: "Token![return]"; +} + +a.struct[title="struct syn::token::SelfType"]::before { + content: "Token![Self]"; +} + +a.struct[title="struct syn::token::SelfValue"]::before { + content: "Token![self]"; +} + +a.struct[title="struct syn::token::Semi"]::before { + content: "Token![;]"; +} + +a.struct[title="struct syn::token::Shl"]::before { + content: "Token![<<]"; +} + +a.struct[title="struct syn::token::ShlEq"]::before { + content: "Token![<<=]"; +} + +a.struct[title="struct syn::token::Shr"]::before { + content: "Token![>>]"; +} + +a.struct[title="struct syn::token::ShrEq"]::before { + content: "Token![>>=]"; +} + +a.struct[title="struct syn::token::Slash"]::before { + content: "Token![/]"; +} + +a.struct[title="struct syn::token::SlashEq"]::before { + content: "Token![/=]"; +} + +a.struct[title="struct syn::token::Star"]::before { + content: "Token![*]"; +} + +a.struct[title="struct syn::token::StarEq"]::before { + content: "Token![*=]"; +} + +a.struct[title="struct syn::token::Static"]::before { + content: "Token![static]"; +} + +a.struct[title="struct syn::token::Struct"]::before { + content: "Token![struct]"; +} + +a.struct[title="struct syn::token::Super"]::before { + content: "Token![super]"; +} + +a.struct[title="struct syn::token::Tilde"]::before { + content: "Token![~]"; +} + +a.struct[title="struct syn::token::Trait"]::before { + content: "Token![trait]"; +} + +a.struct[title="struct syn::token::Try"]::before { + content: "Token![try]"; +} + +a.struct[title="struct syn::token::Type"]::before { + content: "Token![type]"; +} + +a.struct[title="struct syn::token::Typeof"]::before { + content: "Token![typeof]"; +} + +a.struct[title="struct syn::token::Underscore"]::before { + content: "Token![_]"; + font-size: calc(100% * 10 / 9); +} + +a.struct[title="struct syn::token::Union"]::before { + content: "Token![union]"; +} + +a.struct[title="struct syn::token::Unsafe"]::before { + content: "Token![unsafe]"; +} + +a.struct[title="struct syn::token::Unsized"]::before { + content: "Token![unsized]"; +} + +a.struct[title="struct syn::token::Use"]::before { + content: "Token![use]"; +} + +a.struct[title="struct syn::token::Virtual"]::before { + content: "Token![virtual]"; +} + +a.struct[title="struct syn::token::Where"]::before { + content: "Token![where]"; +} + +a.struct[title="struct syn::token::While"]::before { + content: "Token![while]"; +} + +a.struct[title="struct syn::token::Yield"]::before { + content: "Token![yield]"; +} + +a.struct[title="struct syn::token::Underscore"] { + font-size: calc(100% * 9 / 10); +} + +a.struct[title="struct syn::token::PercentEq"]::after, +a.struct[title="struct syn::token::Question"]::after { + content: "."; +} + +a.struct[title="struct syn::token::DotDotDot"]::after, +a.struct[title="struct syn::token::FatArrow"]::after, +a.struct[title="struct syn::token::Percent"]::after { + content: ".."; +} + +a.struct[title="struct syn::token::CaretEq"]::after, +a.struct[title="struct syn::token::Dollar"]::after, +a.struct[title="struct syn::token::DotDotEq"]::after, +a.struct[title="struct syn::token::MinusEq"]::after, +a.struct[title="struct syn::token::PathSep"]::after, +a.struct[title="struct syn::token::SelfValue"]::after, +a.struct[title="struct syn::token::SlashEq"]::after { + content: "..."; +} + +a.struct[title="struct syn::token::AndAnd"]::after, +a.struct[title="struct syn::token::Caret"]::after, +a.struct[title="struct syn::token::Colon"]::after, +a.struct[title="struct syn::token::Comma"]::after, +a.struct[title="struct syn::token::DotDot"]::after, +a.struct[title="struct syn::token::LArrow"]::after, +a.struct[title="struct syn::token::Minus"]::after, +a.struct[title="struct syn::token::PlusEq"]::after, +a.struct[title="struct syn::token::Pound"]::after, +a.struct[title="struct syn::token::RArrow"]::after, +a.struct[title="struct syn::token::SelfType"]::after, +a.struct[title="struct syn::token::Slash"]::after, +a.struct[title="struct syn::token::StarEq"]::after, +a.struct[title="struct syn::token::Tilde"]::after { + content: "...."; +} + +a.struct[title="struct syn::token::AndEq"]::after, +a.struct[title="struct syn::token::Plus"]::after, +a.struct[title="struct syn::token::Semi"]::after, +a.struct[title="struct syn::token::Star"]::after { + content: "....."; +} + +a.struct[title="struct syn::token::And"]::after, +a.struct[title="struct syn::token::Dot"]::after, +a.struct[title="struct syn::token::EqEq"]::after, +a.struct[title="struct syn::token::Not"]::after, +a.struct[title="struct syn::token::OrEq"]::after, +a.struct[title="struct syn::token::OrOr"]::after, +a.struct[title="struct syn::token::ShlEq"]::after, +a.struct[title="struct syn::token::ShrEq"]::after { + content: "......"; +} + +a.struct[title="struct syn::token::At"]::after, +a.struct[title="struct syn::token::Eq"]::after, +a.struct[title="struct syn::token::Gt"]::after, +a.struct[title="struct syn::token::Lt"]::after, +a.struct[title="struct syn::token::Or"]::after, +a.struct[title="struct syn::token::Shl"]::after, +a.struct[title="struct syn::token::Shr"]::after { + content: "......."; +} + +a.struct[title="struct syn::token::Abstract"]::after, +a.struct[title="struct syn::token::As"]::after, +a.struct[title="struct syn::token::Async"]::after, +a.struct[title="struct syn::token::Auto"]::after, +a.struct[title="struct syn::token::Await"]::after, +a.struct[title="struct syn::token::Become"]::after, +a.struct[title="struct syn::token::Box"]::after, +a.struct[title="struct syn::token::Break"]::after, +a.struct[title="struct syn::token::Const"]::after, +a.struct[title="struct syn::token::Continue"]::after, +a.struct[title="struct syn::token::Crate"]::after, +a.struct[title="struct syn::token::Default"]::after, +a.struct[title="struct syn::token::Do"]::after, +a.struct[title="struct syn::token::Dyn"]::after, +a.struct[title="struct syn::token::Else"]::after, +a.struct[title="struct syn::token::Enum"]::after, +a.struct[title="struct syn::token::Extern"]::after, +a.struct[title="struct syn::token::Final"]::after, +a.struct[title="struct syn::token::Fn"]::after, +a.struct[title="struct syn::token::For"]::after, +a.struct[title="struct syn::token::Ge"]::after, +a.struct[title="struct syn::token::If"]::after, +a.struct[title="struct syn::token::Impl"]::after, +a.struct[title="struct syn::token::In"]::after, +a.struct[title="struct syn::token::Le"]::after, +a.struct[title="struct syn::token::Let"]::after, +a.struct[title="struct syn::token::Loop"]::after, +a.struct[title="struct syn::token::Macro"]::after, +a.struct[title="struct syn::token::Match"]::after, +a.struct[title="struct syn::token::Mod"]::after, +a.struct[title="struct syn::token::Move"]::after, +a.struct[title="struct syn::token::Mut"]::after, +a.struct[title="struct syn::token::Ne"]::after, +a.struct[title="struct syn::token::Override"]::after, +a.struct[title="struct syn::token::Priv"]::after, +a.struct[title="struct syn::token::Pub"]::after, +a.struct[title="struct syn::token::Raw"]::after, +a.struct[title="struct syn::token::Ref"]::after, +a.struct[title="struct syn::token::Return"]::after, +a.struct[title="struct syn::token::Static"]::after, +a.struct[title="struct syn::token::Struct"]::after, +a.struct[title="struct syn::token::Super"]::after, +a.struct[title="struct syn::token::Trait"]::after, +a.struct[title="struct syn::token::Try"]::after, +a.struct[title="struct syn::token::Type"]::after, +a.struct[title="struct syn::token::Typeof"]::after, +a.struct[title="struct syn::token::Union"]::after, +a.struct[title="struct syn::token::Unsafe"]::after, +a.struct[title="struct syn::token::Unsized"]::after, +a.struct[title="struct syn::token::Use"]::after, +a.struct[title="struct syn::token::Virtual"]::after, +a.struct[title="struct syn::token::Where"]::after, +a.struct[title="struct syn::token::While"]::after, +a.struct[title="struct syn::token::Yield"]::after { + content: "........"; +} diff --git a/pkg/installer/vendor/syn/src/gen/visit.rs b/pkg/installer/vendor/syn/src/gen/visit.rs index b61997f1775..b82f2750c52 100644 --- a/pkg/installer/vendor/syn/src/gen/visit.rs +++ b/pkg/installer/vendor/syn/src/gen/visit.rs @@ -89,6 +89,11 @@ pub trait Visit<'ast> { fn visit_bound_lifetimes(&mut self, i: &'ast crate::BoundLifetimes) { visit_bound_lifetimes(self, i); } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn visit_captured_param(&mut self, i: &'ast crate::CapturedParam) { + visit_captured_param(self, i); + } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn visit_const_param(&mut self, i: &'ast crate::ConstParam) { @@ -264,6 +269,11 @@ pub trait Visit<'ast> { fn visit_expr_range(&mut self, i: &'ast crate::ExprRange) { visit_expr_range(self, i); } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn visit_expr_raw_addr(&mut self, i: &'ast crate::ExprRawAddr) { + visit_expr_raw_addr(self, i); + } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn visit_expr_reference(&mut self, i: &'ast crate::ExprReference) { @@ -294,8 +304,8 @@ pub trait Visit<'ast> { fn visit_expr_try_block(&mut self, i: &'ast crate::ExprTryBlock) { visit_expr_try_block(self, i); } - #[cfg(feature = "full")] - #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + #[cfg(any(feature = "derive", feature = "full"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn visit_expr_tuple(&mut self, i: &'ast crate::ExprTuple) { visit_expr_tuple(self, i); } @@ -685,6 +695,16 @@ pub trait Visit<'ast> { fn visit_path_segment(&mut self, i: &'ast crate::PathSegment) { visit_path_segment(self, i); } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn visit_pointer_mutability(&mut self, i: &'ast crate::PointerMutability) { + visit_pointer_mutability(self, i); + } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn visit_precise_capture(&mut self, i: &'ast crate::PreciseCapture) { + visit_precise_capture(self, i); + } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn visit_predicate_lifetime(&mut self, i: &'ast crate::PredicateLifetime) { @@ -1169,6 +1189,21 @@ where } skip!(node.gt_token); } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn visit_captured_param<'ast, V>(v: &mut V, node: &'ast crate::CapturedParam) +where + V: Visit<'ast> + ?Sized, +{ + match node { + crate::CapturedParam::Lifetime(_binding_0) => { + v.visit_lifetime(_binding_0); + } + crate::CapturedParam::Ident(_binding_0) => { + v.visit_ident(_binding_0); + } + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn visit_const_param<'ast, V>(v: &mut V, node: &'ast crate::ConstParam) @@ -1355,6 +1390,9 @@ where crate::Expr::Range(_binding_0) => { full!(v.visit_expr_range(_binding_0)); } + crate::Expr::RawAddr(_binding_0) => { + full!(v.visit_expr_raw_addr(_binding_0)); + } crate::Expr::Reference(_binding_0) => { v.visit_expr_reference(_binding_0); } @@ -1374,7 +1412,7 @@ where full!(v.visit_expr_try_block(_binding_0)); } crate::Expr::Tuple(_binding_0) => { - full!(v.visit_expr_tuple(_binding_0)); + v.visit_expr_tuple(_binding_0); } crate::Expr::Unary(_binding_0) => { v.visit_expr_unary(_binding_0); @@ -1786,6 +1824,20 @@ where v.visit_expr(&**it); } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn visit_expr_raw_addr<'ast, V>(v: &mut V, node: &'ast crate::ExprRawAddr) +where + V: Visit<'ast> + ?Sized, +{ + for it in &node.attrs { + v.visit_attribute(it); + } + skip!(node.and_token); + skip!(node.raw); + v.visit_pointer_mutability(&node.mutability); + v.visit_expr(&*node.expr); +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn visit_expr_reference<'ast, V>(v: &mut V, node: &'ast crate::ExprReference) @@ -1874,8 +1926,8 @@ where skip!(node.try_token); v.visit_block(&node.block); } -#[cfg(feature = "full")] -#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn visit_expr_tuple<'ast, V>(v: &mut V, node: &'ast crate::ExprTuple) where V: Visit<'ast> + ?Sized, @@ -3142,6 +3194,35 @@ where v.visit_ident(&node.ident); v.visit_path_arguments(&node.arguments); } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn visit_pointer_mutability<'ast, V>(v: &mut V, node: &'ast crate::PointerMutability) +where + V: Visit<'ast> + ?Sized, +{ + match node { + crate::PointerMutability::Const(_binding_0) => { + skip!(_binding_0); + } + crate::PointerMutability::Mut(_binding_0) => { + skip!(_binding_0); + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn visit_precise_capture<'ast, V>(v: &mut V, node: &'ast crate::PreciseCapture) +where + V: Visit<'ast> + ?Sized, +{ + skip!(node.use_token); + skip!(node.lt_token); + for el in Punctuated::pairs(&node.params) { + let it = el.value(); + v.visit_captured_param(it); + } + skip!(node.gt_token); +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn visit_predicate_lifetime<'ast, V>(v: &mut V, node: &'ast crate::PredicateLifetime) @@ -3598,6 +3679,9 @@ where crate::TypeParamBound::Lifetime(_binding_0) => { v.visit_lifetime(_binding_0); } + crate::TypeParamBound::PreciseCapture(_binding_0) => { + full!(v.visit_precise_capture(_binding_0)); + } crate::TypeParamBound::Verbatim(_binding_0) => { skip!(_binding_0); } diff --git a/pkg/installer/vendor/syn/src/gen/visit_mut.rs b/pkg/installer/vendor/syn/src/gen/visit_mut.rs index 9d457f16405..72570094df5 100644 --- a/pkg/installer/vendor/syn/src/gen/visit_mut.rs +++ b/pkg/installer/vendor/syn/src/gen/visit_mut.rs @@ -67,6 +67,13 @@ pub trait VisitMut { } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] + fn visit_attributes_mut(&mut self, i: &mut Vec) { + for attr in i { + self.visit_attribute_mut(attr); + } + } + #[cfg(any(feature = "derive", feature = "full"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn visit_bare_fn_arg_mut(&mut self, i: &mut crate::BareFnArg) { visit_bare_fn_arg_mut(self, i); } @@ -90,6 +97,11 @@ pub trait VisitMut { fn visit_bound_lifetimes_mut(&mut self, i: &mut crate::BoundLifetimes) { visit_bound_lifetimes_mut(self, i); } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn visit_captured_param_mut(&mut self, i: &mut crate::CapturedParam) { + visit_captured_param_mut(self, i); + } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn visit_const_param_mut(&mut self, i: &mut crate::ConstParam) { @@ -265,6 +277,11 @@ pub trait VisitMut { fn visit_expr_range_mut(&mut self, i: &mut crate::ExprRange) { visit_expr_range_mut(self, i); } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn visit_expr_raw_addr_mut(&mut self, i: &mut crate::ExprRawAddr) { + visit_expr_raw_addr_mut(self, i); + } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn visit_expr_reference_mut(&mut self, i: &mut crate::ExprReference) { @@ -295,8 +312,8 @@ pub trait VisitMut { fn visit_expr_try_block_mut(&mut self, i: &mut crate::ExprTryBlock) { visit_expr_try_block_mut(self, i); } - #[cfg(feature = "full")] - #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + #[cfg(any(feature = "derive", feature = "full"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn visit_expr_tuple_mut(&mut self, i: &mut crate::ExprTuple) { visit_expr_tuple_mut(self, i); } @@ -686,6 +703,16 @@ pub trait VisitMut { fn visit_path_segment_mut(&mut self, i: &mut crate::PathSegment) { visit_path_segment_mut(self, i); } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn visit_pointer_mutability_mut(&mut self, i: &mut crate::PointerMutability) { + visit_pointer_mutability_mut(self, i); + } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + fn visit_precise_capture_mut(&mut self, i: &mut crate::PreciseCapture) { + visit_precise_capture_mut(self, i); + } #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] fn visit_predicate_lifetime_mut(&mut self, i: &mut crate::PredicateLifetime) { @@ -959,9 +986,7 @@ pub fn visit_arm_mut(v: &mut V, node: &mut crate::Arm) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_pat_mut(&mut node.pat); if let Some(it) = &mut node.guard { skip!((it).0); @@ -1027,9 +1052,7 @@ pub fn visit_bare_fn_arg_mut(v: &mut V, node: &mut crate::BareFnArg) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.name { v.visit_ident_mut(&mut (it).0); skip!((it).1); @@ -1042,9 +1065,7 @@ pub fn visit_bare_variadic_mut(v: &mut V, node: &mut crate::BareVariadic) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.name { v.visit_ident_mut(&mut (it).0); skip!((it).1); @@ -1170,15 +1191,28 @@ where } skip!(node.gt_token); } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn visit_captured_param_mut(v: &mut V, node: &mut crate::CapturedParam) +where + V: VisitMut + ?Sized, +{ + match node { + crate::CapturedParam::Lifetime(_binding_0) => { + v.visit_lifetime_mut(_binding_0); + } + crate::CapturedParam::Ident(_binding_0) => { + v.visit_ident_mut(_binding_0); + } + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn visit_const_param_mut(v: &mut V, node: &mut crate::ConstParam) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.const_token); v.visit_ident_mut(&mut node.ident); skip!(node.colon_token); @@ -1260,9 +1294,7 @@ pub fn visit_derive_input_mut(v: &mut V, node: &mut crate::DeriveInput) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); v.visit_ident_mut(&mut node.ident); v.visit_generics_mut(&mut node.generics); @@ -1356,6 +1388,9 @@ where crate::Expr::Range(_binding_0) => { full!(v.visit_expr_range_mut(_binding_0)); } + crate::Expr::RawAddr(_binding_0) => { + full!(v.visit_expr_raw_addr_mut(_binding_0)); + } crate::Expr::Reference(_binding_0) => { v.visit_expr_reference_mut(_binding_0); } @@ -1375,7 +1410,7 @@ where full!(v.visit_expr_try_block_mut(_binding_0)); } crate::Expr::Tuple(_binding_0) => { - full!(v.visit_expr_tuple_mut(_binding_0)); + v.visit_expr_tuple_mut(_binding_0); } crate::Expr::Unary(_binding_0) => { v.visit_expr_unary_mut(_binding_0); @@ -1400,9 +1435,7 @@ pub fn visit_expr_array_mut(v: &mut V, node: &mut crate::ExprArray) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.bracket_token); for mut el in Punctuated::pairs_mut(&mut node.elems) { let it = el.value_mut(); @@ -1415,9 +1448,7 @@ pub fn visit_expr_assign_mut(v: &mut V, node: &mut crate::ExprAssign) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_expr_mut(&mut *node.left); skip!(node.eq_token); v.visit_expr_mut(&mut *node.right); @@ -1428,9 +1459,7 @@ pub fn visit_expr_async_mut(v: &mut V, node: &mut crate::ExprAsync) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.async_token); skip!(node.capture); v.visit_block_mut(&mut node.block); @@ -1441,9 +1470,7 @@ pub fn visit_expr_await_mut(v: &mut V, node: &mut crate::ExprAwait) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_expr_mut(&mut *node.base); skip!(node.dot_token); skip!(node.await_token); @@ -1454,9 +1481,7 @@ pub fn visit_expr_binary_mut(v: &mut V, node: &mut crate::ExprBinary) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_expr_mut(&mut *node.left); v.visit_bin_op_mut(&mut node.op); v.visit_expr_mut(&mut *node.right); @@ -1467,9 +1492,7 @@ pub fn visit_expr_block_mut(v: &mut V, node: &mut crate::ExprBlock) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.label { v.visit_label_mut(it); } @@ -1481,9 +1504,7 @@ pub fn visit_expr_break_mut(v: &mut V, node: &mut crate::ExprBreak) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.break_token); if let Some(it) = &mut node.label { v.visit_lifetime_mut(it); @@ -1498,9 +1519,7 @@ pub fn visit_expr_call_mut(v: &mut V, node: &mut crate::ExprCall) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_expr_mut(&mut *node.func); skip!(node.paren_token); for mut el in Punctuated::pairs_mut(&mut node.args) { @@ -1514,9 +1533,7 @@ pub fn visit_expr_cast_mut(v: &mut V, node: &mut crate::ExprCast) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_expr_mut(&mut *node.expr); skip!(node.as_token); v.visit_type_mut(&mut *node.ty); @@ -1527,9 +1544,7 @@ pub fn visit_expr_closure_mut(v: &mut V, node: &mut crate::ExprClosure) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.lifetimes { v.visit_bound_lifetimes_mut(it); } @@ -1552,9 +1567,7 @@ pub fn visit_expr_const_mut(v: &mut V, node: &mut crate::ExprConst) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.const_token); v.visit_block_mut(&mut node.block); } @@ -1564,9 +1577,7 @@ pub fn visit_expr_continue_mut(v: &mut V, node: &mut crate::ExprContinue) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.continue_token); if let Some(it) = &mut node.label { v.visit_lifetime_mut(it); @@ -1578,9 +1589,7 @@ pub fn visit_expr_field_mut(v: &mut V, node: &mut crate::ExprField) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_expr_mut(&mut *node.base); skip!(node.dot_token); v.visit_member_mut(&mut node.member); @@ -1591,9 +1600,7 @@ pub fn visit_expr_for_loop_mut(v: &mut V, node: &mut crate::ExprForLoop) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.label { v.visit_label_mut(it); } @@ -1609,9 +1616,7 @@ pub fn visit_expr_group_mut(v: &mut V, node: &mut crate::ExprGroup) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.group_token); v.visit_expr_mut(&mut *node.expr); } @@ -1621,9 +1626,7 @@ pub fn visit_expr_if_mut(v: &mut V, node: &mut crate::ExprIf) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.if_token); v.visit_expr_mut(&mut *node.cond); v.visit_block_mut(&mut node.then_branch); @@ -1638,9 +1641,7 @@ pub fn visit_expr_index_mut(v: &mut V, node: &mut crate::ExprIndex) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_expr_mut(&mut *node.expr); skip!(node.bracket_token); v.visit_expr_mut(&mut *node.index); @@ -1651,9 +1652,7 @@ pub fn visit_expr_infer_mut(v: &mut V, node: &mut crate::ExprInfer) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.underscore_token); } #[cfg(feature = "full")] @@ -1662,9 +1661,7 @@ pub fn visit_expr_let_mut(v: &mut V, node: &mut crate::ExprLet) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.let_token); v.visit_pat_mut(&mut *node.pat); skip!(node.eq_token); @@ -1676,9 +1673,7 @@ pub fn visit_expr_lit_mut(v: &mut V, node: &mut crate::ExprLit) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_lit_mut(&mut node.lit); } #[cfg(feature = "full")] @@ -1687,9 +1682,7 @@ pub fn visit_expr_loop_mut(v: &mut V, node: &mut crate::ExprLoop) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.label { v.visit_label_mut(it); } @@ -1702,9 +1695,7 @@ pub fn visit_expr_macro_mut(v: &mut V, node: &mut crate::ExprMacro) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_macro_mut(&mut node.mac); } #[cfg(feature = "full")] @@ -1713,9 +1704,7 @@ pub fn visit_expr_match_mut(v: &mut V, node: &mut crate::ExprMatch) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.match_token); v.visit_expr_mut(&mut *node.expr); skip!(node.brace_token); @@ -1729,9 +1718,7 @@ pub fn visit_expr_method_call_mut(v: &mut V, node: &mut crate::ExprMethodCall where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_expr_mut(&mut *node.receiver); skip!(node.dot_token); v.visit_ident_mut(&mut node.method); @@ -1750,9 +1737,7 @@ pub fn visit_expr_paren_mut(v: &mut V, node: &mut crate::ExprParen) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.paren_token); v.visit_expr_mut(&mut *node.expr); } @@ -1762,9 +1747,7 @@ pub fn visit_expr_path_mut(v: &mut V, node: &mut crate::ExprPath) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.qself { v.visit_qself_mut(it); } @@ -1776,9 +1759,7 @@ pub fn visit_expr_range_mut(v: &mut V, node: &mut crate::ExprRange) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.start { v.visit_expr_mut(&mut **it); } @@ -1787,15 +1768,25 @@ where v.visit_expr_mut(&mut **it); } } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn visit_expr_raw_addr_mut(v: &mut V, node: &mut crate::ExprRawAddr) +where + V: VisitMut + ?Sized, +{ + v.visit_attributes_mut(&mut node.attrs); + skip!(node.and_token); + skip!(node.raw); + v.visit_pointer_mutability_mut(&mut node.mutability); + v.visit_expr_mut(&mut *node.expr); +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn visit_expr_reference_mut(v: &mut V, node: &mut crate::ExprReference) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.and_token); skip!(node.mutability); v.visit_expr_mut(&mut *node.expr); @@ -1806,9 +1797,7 @@ pub fn visit_expr_repeat_mut(v: &mut V, node: &mut crate::ExprRepeat) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.bracket_token); v.visit_expr_mut(&mut *node.expr); skip!(node.semi_token); @@ -1820,9 +1809,7 @@ pub fn visit_expr_return_mut(v: &mut V, node: &mut crate::ExprReturn) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.return_token); if let Some(it) = &mut node.expr { v.visit_expr_mut(&mut **it); @@ -1834,9 +1821,7 @@ pub fn visit_expr_struct_mut(v: &mut V, node: &mut crate::ExprStruct) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.qself { v.visit_qself_mut(it); } @@ -1857,9 +1842,7 @@ pub fn visit_expr_try_mut(v: &mut V, node: &mut crate::ExprTry) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_expr_mut(&mut *node.expr); skip!(node.question_token); } @@ -1869,21 +1852,17 @@ pub fn visit_expr_try_block_mut(v: &mut V, node: &mut crate::ExprTryBlock) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.try_token); v.visit_block_mut(&mut node.block); } -#[cfg(feature = "full")] -#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn visit_expr_tuple_mut(v: &mut V, node: &mut crate::ExprTuple) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.paren_token); for mut el in Punctuated::pairs_mut(&mut node.elems) { let it = el.value_mut(); @@ -1896,9 +1875,7 @@ pub fn visit_expr_unary_mut(v: &mut V, node: &mut crate::ExprUnary) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_un_op_mut(&mut node.op); v.visit_expr_mut(&mut *node.expr); } @@ -1908,9 +1885,7 @@ pub fn visit_expr_unsafe_mut(v: &mut V, node: &mut crate::ExprUnsafe) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.unsafe_token); v.visit_block_mut(&mut node.block); } @@ -1920,9 +1895,7 @@ pub fn visit_expr_while_mut(v: &mut V, node: &mut crate::ExprWhile) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.label { v.visit_label_mut(it); } @@ -1936,9 +1909,7 @@ pub fn visit_expr_yield_mut(v: &mut V, node: &mut crate::ExprYield) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.yield_token); if let Some(it) = &mut node.expr { v.visit_expr_mut(&mut **it); @@ -1950,9 +1921,7 @@ pub fn visit_field_mut(v: &mut V, node: &mut crate::Field) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); v.visit_field_mutability_mut(&mut node.mutability); if let Some(it) = &mut node.ident { @@ -1977,9 +1946,7 @@ pub fn visit_field_pat_mut(v: &mut V, node: &mut crate::FieldPat) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_member_mut(&mut node.member); skip!(node.colon_token); v.visit_pat_mut(&mut *node.pat); @@ -1990,9 +1957,7 @@ pub fn visit_field_value_mut(v: &mut V, node: &mut crate::FieldValue) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_member_mut(&mut node.member); skip!(node.colon_token); v.visit_expr_mut(&mut node.expr); @@ -2044,9 +2009,7 @@ where V: VisitMut + ?Sized, { skip!(node.shebang); - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); for it in &mut node.items { v.visit_item_mut(it); } @@ -2096,9 +2059,7 @@ pub fn visit_foreign_item_fn_mut(v: &mut V, node: &mut crate::ForeignItemFn) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); v.visit_signature_mut(&mut node.sig); skip!(node.semi_token); @@ -2109,9 +2070,7 @@ pub fn visit_foreign_item_macro_mut(v: &mut V, node: &mut crate::ForeignItemM where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_macro_mut(&mut node.mac); skip!(node.semi_token); } @@ -2121,9 +2080,7 @@ pub fn visit_foreign_item_static_mut(v: &mut V, node: &mut crate::ForeignItem where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.static_token); v.visit_static_mutability_mut(&mut node.mutability); @@ -2138,9 +2095,7 @@ pub fn visit_foreign_item_type_mut(v: &mut V, node: &mut crate::ForeignItemTy where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.type_token); v.visit_ident_mut(&mut node.ident); @@ -2246,9 +2201,7 @@ pub fn visit_impl_item_const_mut(v: &mut V, node: &mut crate::ImplItemConst) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.defaultness); skip!(node.const_token); @@ -2266,9 +2219,7 @@ pub fn visit_impl_item_fn_mut(v: &mut V, node: &mut crate::ImplItemFn) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.defaultness); v.visit_signature_mut(&mut node.sig); @@ -2280,9 +2231,7 @@ pub fn visit_impl_item_macro_mut(v: &mut V, node: &mut crate::ImplItemMacro) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_macro_mut(&mut node.mac); skip!(node.semi_token); } @@ -2292,9 +2241,7 @@ pub fn visit_impl_item_type_mut(v: &mut V, node: &mut crate::ImplItemType) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.defaultness); skip!(node.type_token); @@ -2384,9 +2331,7 @@ pub fn visit_item_const_mut(v: &mut V, node: &mut crate::ItemConst) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.const_token); v.visit_ident_mut(&mut node.ident); @@ -2403,9 +2348,7 @@ pub fn visit_item_enum_mut(v: &mut V, node: &mut crate::ItemEnum) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.enum_token); v.visit_ident_mut(&mut node.ident); @@ -2422,9 +2365,7 @@ pub fn visit_item_extern_crate_mut(v: &mut V, node: &mut crate::ItemExternCra where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.extern_token); skip!(node.crate_token); @@ -2441,9 +2382,7 @@ pub fn visit_item_fn_mut(v: &mut V, node: &mut crate::ItemFn) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); v.visit_signature_mut(&mut node.sig); v.visit_block_mut(&mut *node.block); @@ -2454,9 +2393,7 @@ pub fn visit_item_foreign_mod_mut(v: &mut V, node: &mut crate::ItemForeignMod where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.unsafety); v.visit_abi_mut(&mut node.abi); skip!(node.brace_token); @@ -2470,9 +2407,7 @@ pub fn visit_item_impl_mut(v: &mut V, node: &mut crate::ItemImpl) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.defaultness); skip!(node.unsafety); skip!(node.impl_token); @@ -2494,9 +2429,7 @@ pub fn visit_item_macro_mut(v: &mut V, node: &mut crate::ItemMacro) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.ident { v.visit_ident_mut(it); } @@ -2509,9 +2442,7 @@ pub fn visit_item_mod_mut(v: &mut V, node: &mut crate::ItemMod) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.unsafety); skip!(node.mod_token); @@ -2530,9 +2461,7 @@ pub fn visit_item_static_mut(v: &mut V, node: &mut crate::ItemStatic) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.static_token); v.visit_static_mutability_mut(&mut node.mutability); @@ -2549,9 +2478,7 @@ pub fn visit_item_struct_mut(v: &mut V, node: &mut crate::ItemStruct) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.struct_token); v.visit_ident_mut(&mut node.ident); @@ -2565,9 +2492,7 @@ pub fn visit_item_trait_mut(v: &mut V, node: &mut crate::ItemTrait) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.unsafety); skip!(node.auto_token); @@ -2593,9 +2518,7 @@ pub fn visit_item_trait_alias_mut(v: &mut V, node: &mut crate::ItemTraitAlias where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.trait_token); v.visit_ident_mut(&mut node.ident); @@ -2613,9 +2536,7 @@ pub fn visit_item_type_mut(v: &mut V, node: &mut crate::ItemType) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.type_token); v.visit_ident_mut(&mut node.ident); @@ -2630,9 +2551,7 @@ pub fn visit_item_union_mut(v: &mut V, node: &mut crate::ItemUnion) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.union_token); v.visit_ident_mut(&mut node.ident); @@ -2645,9 +2564,7 @@ pub fn visit_item_use_mut(v: &mut V, node: &mut crate::ItemUse) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_visibility_mut(&mut node.vis); skip!(node.use_token); skip!(node.leading_colon); @@ -2676,9 +2593,7 @@ pub fn visit_lifetime_param_mut(v: &mut V, node: &mut crate::LifetimeParam) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_lifetime_mut(&mut node.lifetime); skip!(node.colon_token); for mut el in Punctuated::pairs_mut(&mut node.bounds) { @@ -2761,9 +2676,7 @@ pub fn visit_local_mut(v: &mut V, node: &mut crate::Local) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.let_token); v.visit_pat_mut(&mut node.pat); if let Some(it) = &mut node.init { @@ -2948,9 +2861,7 @@ pub fn visit_pat_ident_mut(v: &mut V, node: &mut crate::PatIdent) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.by_ref); skip!(node.mutability); v.visit_ident_mut(&mut node.ident); @@ -2965,9 +2876,7 @@ pub fn visit_pat_or_mut(v: &mut V, node: &mut crate::PatOr) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.leading_vert); for mut el in Punctuated::pairs_mut(&mut node.cases) { let it = el.value_mut(); @@ -2980,9 +2889,7 @@ pub fn visit_pat_paren_mut(v: &mut V, node: &mut crate::PatParen) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.paren_token); v.visit_pat_mut(&mut *node.pat); } @@ -2992,9 +2899,7 @@ pub fn visit_pat_reference_mut(v: &mut V, node: &mut crate::PatReference) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.and_token); skip!(node.mutability); v.visit_pat_mut(&mut *node.pat); @@ -3005,9 +2910,7 @@ pub fn visit_pat_rest_mut(v: &mut V, node: &mut crate::PatRest) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.dot2_token); } #[cfg(feature = "full")] @@ -3016,9 +2919,7 @@ pub fn visit_pat_slice_mut(v: &mut V, node: &mut crate::PatSlice) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.bracket_token); for mut el in Punctuated::pairs_mut(&mut node.elems) { let it = el.value_mut(); @@ -3031,9 +2932,7 @@ pub fn visit_pat_struct_mut(v: &mut V, node: &mut crate::PatStruct) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.qself { v.visit_qself_mut(it); } @@ -3053,9 +2952,7 @@ pub fn visit_pat_tuple_mut(v: &mut V, node: &mut crate::PatTuple) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.paren_token); for mut el in Punctuated::pairs_mut(&mut node.elems) { let it = el.value_mut(); @@ -3068,9 +2965,7 @@ pub fn visit_pat_tuple_struct_mut(v: &mut V, node: &mut crate::PatTupleStruct where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.qself { v.visit_qself_mut(it); } @@ -3087,9 +2982,7 @@ pub fn visit_pat_type_mut(v: &mut V, node: &mut crate::PatType) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_pat_mut(&mut *node.pat); skip!(node.colon_token); v.visit_type_mut(&mut *node.ty); @@ -3100,9 +2993,7 @@ pub fn visit_pat_wild_mut(v: &mut V, node: &mut crate::PatWild) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.underscore_token); } #[cfg(any(feature = "derive", feature = "full"))] @@ -3142,6 +3033,35 @@ where v.visit_ident_mut(&mut node.ident); v.visit_path_arguments_mut(&mut node.arguments); } +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn visit_pointer_mutability_mut(v: &mut V, node: &mut crate::PointerMutability) +where + V: VisitMut + ?Sized, +{ + match node { + crate::PointerMutability::Const(_binding_0) => { + skip!(_binding_0); + } + crate::PointerMutability::Mut(_binding_0) => { + skip!(_binding_0); + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub fn visit_precise_capture_mut(v: &mut V, node: &mut crate::PreciseCapture) +where + V: VisitMut + ?Sized, +{ + skip!(node.use_token); + skip!(node.lt_token); + for mut el in Punctuated::pairs_mut(&mut node.params) { + let it = el.value_mut(); + v.visit_captured_param_mut(it); + } + skip!(node.gt_token); +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "derive", feature = "full"))))] pub fn visit_predicate_lifetime_mut(v: &mut V, node: &mut crate::PredicateLifetime) @@ -3204,9 +3124,7 @@ pub fn visit_receiver_mut(v: &mut V, node: &mut crate::Receiver) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.reference { skip!((it).0); if let Some(it) = &mut (it).1 { @@ -3302,9 +3220,7 @@ pub fn visit_stmt_macro_mut(v: &mut V, node: &mut crate::StmtMacro) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_macro_mut(&mut node.mac); skip!(node.semi_token); } @@ -3364,9 +3280,7 @@ pub fn visit_trait_item_const_mut(v: &mut V, node: &mut crate::TraitItemConst where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.const_token); v.visit_ident_mut(&mut node.ident); v.visit_generics_mut(&mut node.generics); @@ -3384,9 +3298,7 @@ pub fn visit_trait_item_fn_mut(v: &mut V, node: &mut crate::TraitItemFn) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_signature_mut(&mut node.sig); if let Some(it) = &mut node.default { v.visit_block_mut(it); @@ -3399,9 +3311,7 @@ pub fn visit_trait_item_macro_mut(v: &mut V, node: &mut crate::TraitItemMacro where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_macro_mut(&mut node.mac); skip!(node.semi_token); } @@ -3411,9 +3321,7 @@ pub fn visit_trait_item_type_mut(v: &mut V, node: &mut crate::TraitItemType) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); skip!(node.type_token); v.visit_ident_mut(&mut node.ident); v.visit_generics_mut(&mut node.generics); @@ -3568,9 +3476,7 @@ pub fn visit_type_param_mut(v: &mut V, node: &mut crate::TypeParam) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_ident_mut(&mut node.ident); skip!(node.colon_token); for mut el in Punctuated::pairs_mut(&mut node.bounds) { @@ -3595,6 +3501,9 @@ where crate::TypeParamBound::Lifetime(_binding_0) => { v.visit_lifetime_mut(_binding_0); } + crate::TypeParamBound::PreciseCapture(_binding_0) => { + full!(v.visit_precise_capture_mut(_binding_0)); + } crate::TypeParamBound::Verbatim(_binding_0) => { skip!(_binding_0); } @@ -3773,9 +3682,7 @@ pub fn visit_variadic_mut(v: &mut V, node: &mut crate::Variadic) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); if let Some(it) = &mut node.pat { v.visit_pat_mut(&mut *(it).0); skip!((it).1); @@ -3789,9 +3696,7 @@ pub fn visit_variant_mut(v: &mut V, node: &mut crate::Variant) where V: VisitMut + ?Sized, { - for it in &mut node.attrs { - v.visit_attribute_mut(it); - } + v.visit_attributes_mut(&mut node.attrs); v.visit_ident_mut(&mut node.ident); v.visit_fields_mut(&mut node.fields); if let Some(it) = &mut node.discriminant { diff --git a/pkg/installer/vendor/syn/src/generics.rs b/pkg/installer/vendor/syn/src/generics.rs index 692ad530010..1e8fccf039d 100644 --- a/pkg/installer/vendor/syn/src/generics.rs +++ b/pkg/installer/vendor/syn/src/generics.rs @@ -426,6 +426,7 @@ ast_enum_of_structs! { pub enum TypeParamBound { Trait(TraitBound), Lifetime(Lifetime), + PreciseCapture(PreciseCapture), Verbatim(TokenStream), } } @@ -453,6 +454,34 @@ ast_enum! { } } +ast_struct! { + /// Precise capturing bound: the 'use<…>' in `impl Trait + + /// use<'a, T>`. + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + pub struct PreciseCapture #full { + pub use_token: Token![use], + pub lt_token: Token![<], + pub params: Punctuated, + pub gt_token: Token![>], + } +} + +#[cfg(feature = "full")] +ast_enum! { + /// Single parameter in a precise capturing bound. + #[cfg_attr(docsrs, doc(cfg(feature = "full")))] + #[non_exhaustive] + pub enum CapturedParam { + /// A lifetime parameter in precise capturing bound: `fn f<'a>() -> impl + /// Trait + use<'a>`. + Lifetime(Lifetime), + /// A type parameter or const generic parameter in precise capturing + /// bound: `fn f() -> impl Trait + use` or `fn f() -> + /// impl Trait + use`. + Ident(Ident), + } +} + ast_struct! { /// A `where` clause in a definition: `where T: Deserialize<'de>, D: /// 'static`. @@ -509,13 +538,15 @@ ast_struct! { #[cfg(feature = "parsing")] pub(crate) mod parsing { use crate::attr::Attribute; - use crate::error::Result; + use crate::error::{self, Result}; use crate::ext::IdentExt as _; use crate::generics::{ BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeParam, PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound, WhereClause, WherePredicate, }; + #[cfg(feature = "full")] + use crate::generics::{CapturedParam, PreciseCapture}; use crate::ident::Ident; use crate::lifetime::Lifetime; use crate::parse::{Parse, ParseStream}; @@ -706,8 +737,15 @@ pub(crate) mod parsing { if input.peek(Token![,]) || input.peek(Token![>]) || input.peek(Token![=]) { break; } - let value: TypeParamBound = input.parse()?; - bounds.push_value(value); + bounds.push_value({ + let allow_precise_capture = false; + let allow_tilde_const = true; + TypeParamBound::parse_single( + input, + allow_precise_capture, + allow_tilde_const, + )? + }); if !input.peek(Token![+]) { break; } @@ -737,37 +775,39 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for TypeParamBound { fn parse(input: ParseStream) -> Result { + let allow_precise_capture = true; + let allow_tilde_const = true; + Self::parse_single(input, allow_precise_capture, allow_tilde_const) + } + } + + impl TypeParamBound { + pub(crate) fn parse_single( + input: ParseStream, + #[cfg_attr(not(feature = "full"), allow(unused_variables))] allow_precise_capture: bool, + allow_tilde_const: bool, + ) -> Result { if input.peek(Lifetime) { return input.parse().map(TypeParamBound::Lifetime); } let begin = input.fork(); - if cfg!(feature = "full") && input.peek(Token![use]) { - input.parse::()?; - input.parse::()?; - loop { - let lookahead = input.lookahead1(); - if lookahead.peek(Lifetime) { - input.parse::()?; - } else if lookahead.peek(Ident) { - input.parse::()?; - } else if lookahead.peek(Token![>]) { - break; - } else { - return Err(lookahead.error()); - } - let lookahead = input.lookahead1(); - if lookahead.peek(Token![,]) { - input.parse::()?; - } else if lookahead.peek(Token![>]) { - break; + #[cfg(feature = "full")] + { + if input.peek(Token![use]) { + let precise_capture: PreciseCapture = input.parse()?; + return if allow_precise_capture { + Ok(TypeParamBound::PreciseCapture(precise_capture)) } else { - return Err(lookahead.error()); - } + let msg = "`use<...>` precise capturing syntax is not allowed here"; + Err(error::new2( + precise_capture.use_token.span, + precise_capture.gt_token.span, + msg, + )) + }; } - input.parse::]>()?; - return Ok(TypeParamBound::Verbatim(verbatim::between(&begin, input))); } let content; @@ -780,8 +820,12 @@ pub(crate) mod parsing { let is_tilde_const = cfg!(feature = "full") && content.peek(Token![~]) && content.peek2(Token![const]); if is_tilde_const { - content.parse::()?; - content.parse::()?; + let tilde_token: Token![~] = content.parse()?; + let const_token: Token![const] = content.parse()?; + if !allow_tilde_const { + let msg = "`~const` is not allowed here"; + return Err(error::new2(tilde_token.span, const_token.span, msg)); + } } let mut bound: TraitBound = content.parse()?; @@ -793,16 +837,17 @@ pub(crate) mod parsing { Ok(TypeParamBound::Trait(bound)) } } - } - impl TypeParamBound { pub(crate) fn parse_multiple( input: ParseStream, allow_plus: bool, + allow_precise_capture: bool, + allow_tilde_const: bool, ) -> Result> { let mut bounds = Punctuated::new(); loop { - bounds.push_value(input.parse()?); + let bound = Self::parse_single(input, allow_precise_capture, allow_tilde_const)?; + bounds.push_value(bound); if !(allow_plus && input.peek(Token![+])) { break; } @@ -970,8 +1015,15 @@ pub(crate) mod parsing { { break; } - let value = input.parse()?; - bounds.push_value(value); + bounds.push_value({ + let allow_precise_capture = false; + let allow_tilde_const = true; + TypeParamBound::parse_single( + input, + allow_precise_capture, + allow_tilde_const, + )? + }); if !input.peek(Token![+]) { break; } @@ -984,6 +1036,59 @@ pub(crate) mod parsing { } } } + + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] + impl Parse for PreciseCapture { + fn parse(input: ParseStream) -> Result { + let use_token: Token![use] = input.parse()?; + let lt_token: Token![<] = input.parse()?; + let mut params = Punctuated::new(); + loop { + let lookahead = input.lookahead1(); + params.push_value( + if lookahead.peek(Lifetime) || lookahead.peek(Ident) || input.peek(Token![Self]) + { + input.parse::()? + } else if lookahead.peek(Token![>]) { + break; + } else { + return Err(lookahead.error()); + }, + ); + let lookahead = input.lookahead1(); + params.push_punct(if lookahead.peek(Token![,]) { + input.parse::()? + } else if lookahead.peek(Token![>]) { + break; + } else { + return Err(lookahead.error()); + }); + } + let gt_token: Token![>] = input.parse()?; + Ok(PreciseCapture { + use_token, + lt_token, + params, + gt_token, + }) + } + } + + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] + impl Parse for CapturedParam { + fn parse(input: ParseStream) -> Result { + let lookahead = input.lookahead1(); + if lookahead.peek(Lifetime) { + input.parse().map(CapturedParam::Lifetime) + } else if lookahead.peek(Ident) || input.peek(Token![Self]) { + input.call(Ident::parse_any).map(CapturedParam::Ident) + } else { + Err(lookahead.error()) + } + } + } } #[cfg(feature = "printing")] @@ -999,6 +1104,8 @@ pub(crate) mod printing { PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, Turbofish, TypeGenerics, TypeParam, WhereClause, }; + #[cfg(feature = "full")] + use crate::generics::{CapturedParam, PreciseCapture}; use crate::print::TokensOrDefault; use crate::token; use proc_macro2::TokenStream; @@ -1252,6 +1359,47 @@ pub(crate) mod printing { } } + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] + impl ToTokens for PreciseCapture { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.use_token.to_tokens(tokens); + self.lt_token.to_tokens(tokens); + + // Print lifetimes before types and consts, regardless of their + // order in self.params. + let mut trailing_or_empty = true; + for param in self.params.pairs() { + if let CapturedParam::Lifetime(_) = **param.value() { + param.to_tokens(tokens); + trailing_or_empty = param.punct().is_some(); + } + } + for param in self.params.pairs() { + if let CapturedParam::Ident(_) = **param.value() { + if !trailing_or_empty { + ::default().to_tokens(tokens); + trailing_or_empty = true; + } + param.to_tokens(tokens); + } + } + + self.gt_token.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] + impl ToTokens for CapturedParam { + fn to_tokens(&self, tokens: &mut TokenStream) { + match self { + CapturedParam::Lifetime(lifetime) => lifetime.to_tokens(tokens), + CapturedParam::Ident(ident) => ident.to_tokens(tokens), + } + } + } + pub(crate) fn print_const_argument(expr: &Expr, tokens: &mut TokenStream) { match expr { Expr::Lit(expr) => expr.to_tokens(tokens), diff --git a/pkg/installer/vendor/syn/src/item.rs b/pkg/installer/vendor/syn/src/item.rs index fa87b42b965..a24623edb6a 100644 --- a/pkg/installer/vendor/syn/src/item.rs +++ b/pkg/installer/vendor/syn/src/item.rs @@ -952,7 +952,8 @@ pub(crate) mod parsing { let vis: Visibility = ahead.parse()?; let lookahead = ahead.lookahead1(); - let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { + let allow_safe = false; + let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) { let vis: Visibility = input.parse()?; let sig: Signature = input.parse()?; if input.peek(Token![;]) { @@ -1205,7 +1206,15 @@ pub(crate) mod parsing { if input.peek(Token![where]) || input.peek(Token![=]) || input.peek(Token![;]) { break; } - bounds.push_value(input.parse::()?); + bounds.push_value({ + let allow_precise_capture = false; + let allow_tilde_const = true; + TypeParamBound::parse_single( + input, + allow_precise_capture, + allow_tilde_const, + )? + }); if input.peek(Token![where]) || input.peek(Token![=]) || input.peek(Token![;]) { break; } @@ -1411,14 +1420,16 @@ pub(crate) mod parsing { &content, allow_crate_root_in_path && !this_tree_starts_with_crate_root, )? { - Some(tree) => items.push_value(tree), - None => has_any_crate_root_in_path = true, + Some(tree) if !has_any_crate_root_in_path => items.push_value(tree), + _ => has_any_crate_root_in_path = true, } if content.is_empty() { break; } let comma: Token![,] = content.parse()?; - items.push_punct(comma); + if !has_any_crate_root_in_path { + items.push_punct(comma); + } } if has_any_crate_root_in_path { Ok(None) @@ -1483,11 +1494,14 @@ pub(crate) mod parsing { } } - fn peek_signature(input: ParseStream) -> bool { + fn peek_signature(input: ParseStream, allow_safe: bool) -> bool { let fork = input.fork(); fork.parse::>().is_ok() && fork.parse::>().is_ok() - && fork.parse::>().is_ok() + && ((allow_safe + && token::parsing::peek_keyword(fork.cursor(), "safe") + && token::parsing::keyword(&fork, "safe").is_ok()) + || fork.parse::>().is_ok()) && fork.parse::>().is_ok() && fork.peek(Token![fn]) } @@ -1495,22 +1509,37 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for Signature { fn parse(input: ParseStream) -> Result { - let constness: Option = input.parse()?; - let asyncness: Option = input.parse()?; - let unsafety: Option = input.parse()?; - let abi: Option = input.parse()?; - let fn_token: Token![fn] = input.parse()?; - let ident: Ident = input.parse()?; - let mut generics: Generics = input.parse()?; + let allow_safe = false; + parse_signature(input, allow_safe).map(Option::unwrap) + } + } - let content; - let paren_token = parenthesized!(content in input); - let (inputs, variadic) = parse_fn_args(&content)?; + fn parse_signature(input: ParseStream, allow_safe: bool) -> Result> { + let constness: Option = input.parse()?; + let asyncness: Option = input.parse()?; + let unsafety: Option = input.parse()?; + let safe = allow_safe + && unsafety.is_none() + && token::parsing::peek_keyword(input.cursor(), "safe"); + if safe { + token::parsing::keyword(input, "safe")?; + } + let abi: Option = input.parse()?; + let fn_token: Token![fn] = input.parse()?; + let ident: Ident = input.parse()?; + let mut generics: Generics = input.parse()?; - let output: ReturnType = input.parse()?; - generics.where_clause = input.parse()?; + let content; + let paren_token = parenthesized!(content in input); + let (inputs, variadic) = parse_fn_args(&content)?; - Ok(Signature { + let output: ReturnType = input.parse()?; + generics.where_clause = input.parse()?; + + Ok(if safe { + None + } else { + Some(Signature { constness, asyncness, unsafety, @@ -1523,7 +1552,7 @@ pub(crate) mod parsing { variadic, output, }) - } + }) } #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] @@ -1819,35 +1848,55 @@ pub(crate) mod parsing { let vis: Visibility = ahead.parse()?; let lookahead = ahead.lookahead1(); - let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { + let allow_safe = true; + let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) { let vis: Visibility = input.parse()?; - let sig: Signature = input.parse()?; - if input.peek(token::Brace) { + let sig = parse_signature(input, allow_safe)?; + let has_safe = sig.is_none(); + let has_body = input.peek(token::Brace); + let semi_token: Option = if has_body { let content; braced!(content in input); content.call(Attribute::parse_inner)?; content.call(Block::parse_within)?; - + None + } else { + Some(input.parse()?) + }; + if has_safe || has_body { Ok(ForeignItem::Verbatim(verbatim::between(&begin, input))) } else { Ok(ForeignItem::Fn(ForeignItemFn { attrs: Vec::new(), vis, - sig, - semi_token: input.parse()?, + sig: sig.unwrap(), + semi_token: semi_token.unwrap(), })) } - } else if lookahead.peek(Token![static]) { + } else if lookahead.peek(Token![static]) + || ((ahead.peek(Token![unsafe]) + || token::parsing::peek_keyword(ahead.cursor(), "safe")) + && ahead.peek2(Token![static])) + { let vis = input.parse()?; + let unsafety: Option = input.parse()?; + let safe = + unsafety.is_none() && token::parsing::peek_keyword(input.cursor(), "safe"); + if safe { + token::parsing::keyword(input, "safe")?; + } let static_token = input.parse()?; let mutability = input.parse()?; let ident = input.parse()?; let colon_token = input.parse()?; let ty = input.parse()?; - if input.peek(Token![=]) { + let has_value = input.peek(Token![=]); + if has_value { input.parse::()?; input.parse::()?; - input.parse::()?; + } + let semi_token: Token![;] = input.parse()?; + if unsafety.is_some() || safe || has_value { Ok(ForeignItem::Verbatim(verbatim::between(&begin, input))) } else { Ok(ForeignItem::Static(ForeignItemStatic { @@ -1858,7 +1907,7 @@ pub(crate) mod parsing { ident, colon_token, ty, - semi_token: input.parse()?, + semi_token, })) } } else if lookahead.peek(Token![type]) { @@ -2182,7 +2231,11 @@ pub(crate) mod parsing { if input.peek(Token![where]) || input.peek(token::Brace) { break; } - supertraits.push_value(input.parse()?); + supertraits.push_value({ + let allow_precise_capture = false; + let allow_tilde_const = true; + TypeParamBound::parse_single(input, allow_precise_capture, allow_tilde_const)? + }); if input.peek(Token![where]) || input.peek(token::Brace) { break; } @@ -2250,7 +2303,11 @@ pub(crate) mod parsing { if input.peek(Token![where]) || input.peek(Token![;]) { break; } - bounds.push_value(input.parse()?); + bounds.push_value({ + let allow_precise_capture = false; + let allow_tilde_const = false; + TypeParamBound::parse_single(input, allow_precise_capture, allow_tilde_const)? + }); if input.peek(Token![where]) || input.peek(Token![;]) { break; } @@ -2282,7 +2339,8 @@ pub(crate) mod parsing { let ahead = input.fork(); let lookahead = ahead.lookahead1(); - let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { + let allow_safe = false; + let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) { input.parse().map(TraitItem::Fn) } else if lookahead.peek(Token![const]) { let const_token: Token![const] = ahead.parse()?; @@ -2627,7 +2685,8 @@ pub(crate) mod parsing { None }; - let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { + let allow_safe = false; + let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) { let allow_omitted_body = true; if let Some(item) = parse_impl_item_fn(input, allow_omitted_body)? { Ok(ImplItem::Fn(item)) @@ -2894,6 +2953,8 @@ mod printing { UsePath, UseRename, Variadic, }; use crate::mac::MacroDelimiter; + use crate::path; + use crate::path::printing::PathStyle; use crate::print::TokensOrDefault; use crate::ty::Type; use proc_macro2::TokenStream; @@ -3135,7 +3196,7 @@ mod printing { impl ToTokens for ItemMacro { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); - self.mac.path.to_tokens(tokens); + path::printing::print_path(tokens, &self.mac.path, PathStyle::Mod); self.mac.bang_token.to_tokens(tokens); self.ident.to_tokens(tokens); match &self.mac.delimiter { diff --git a/pkg/installer/vendor/syn/src/lib.rs b/pkg/installer/vendor/syn/src/lib.rs index 7f377ea7c14..19736acf92a 100644 --- a/pkg/installer/vendor/syn/src/lib.rs +++ b/pkg/installer/vendor/syn/src/lib.rs @@ -249,7 +249,7 @@ //! dynamic library libproc_macro from rustc toolchain. // Syn types in rustdoc of other crates get linked to here. -#![doc(html_root_url = "https://docs.rs/syn/2.0.74")] +#![doc(html_root_url = "https://docs.rs/syn/2.0.87")] #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(unsafe_op_in_unsafe_fn)] #![allow(non_camel_case_types)] @@ -264,6 +264,7 @@ clippy::derivable_impls, clippy::diverging_sub_expression, clippy::doc_markdown, + clippy::enum_glob_use, clippy::expl_impl_clone_on_copy, clippy::explicit_auto_deref, clippy::if_not_else, @@ -284,11 +285,13 @@ clippy::module_name_repetitions, clippy::must_use_candidate, clippy::needless_doctest_main, + clippy::needless_lifetimes, clippy::needless_pass_by_value, clippy::needless_update, clippy::never_loop, clippy::range_plus_one, clippy::redundant_else, + clippy::ref_option, clippy::return_self_not_must_use, clippy::similar_names, clippy::single_match_else, @@ -305,6 +308,8 @@ clippy::wildcard_imports, )] +extern crate self as syn; + #[cfg(feature = "proc-macro")] extern crate proc_macro; @@ -361,7 +366,7 @@ pub use crate::error::{Error, Result}; mod expr; #[cfg(feature = "full")] #[cfg_attr(docsrs, doc(cfg(feature = "full")))] -pub use crate::expr::{Arm, Label, RangeLimits}; +pub use crate::expr::{Arm, Label, PointerMutability, RangeLimits}; #[cfg(any(feature = "full", feature = "derive"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] pub use crate::expr::{ @@ -373,8 +378,8 @@ pub use crate::expr::{ pub use crate::expr::{ ExprArray, ExprAssign, ExprAsync, ExprAwait, ExprBlock, ExprBreak, ExprClosure, ExprConst, ExprContinue, ExprForLoop, ExprGroup, ExprIf, ExprInfer, ExprLet, ExprLoop, ExprMatch, - ExprRange, ExprRepeat, ExprReturn, ExprTry, ExprTryBlock, ExprTuple, ExprUnsafe, ExprWhile, - ExprYield, + ExprRange, ExprRawAddr, ExprRepeat, ExprReturn, ExprTry, ExprTryBlock, ExprTuple, ExprUnsafe, + ExprWhile, ExprYield, }; #[cfg(feature = "parsing")] @@ -399,6 +404,9 @@ pub use crate::generics::{ PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound, WhereClause, WherePredicate, }; +#[cfg(feature = "full")] +#[cfg_attr(docsrs, doc(cfg(feature = "full")))] +pub use crate::generics::{CapturedParam, PreciseCapture}; #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] #[cfg_attr( docsrs, @@ -504,6 +512,9 @@ pub use crate::restriction::{FieldMutability, VisRestricted, Visibility}; mod sealed; +#[cfg(all(feature = "parsing", feature = "derive", not(feature = "full")))] +mod scan_expr; + mod span; #[cfg(all(feature = "parsing", feature = "printing"))] @@ -884,31 +895,8 @@ pub mod __private; /// /// [`syn::parse2`]: parse2 /// -/// # Examples -/// -/// ``` -/// # extern crate proc_macro; -/// # -/// use proc_macro::TokenStream; -/// use quote::quote; -/// use syn::DeriveInput; -/// -/// # const IGNORE_TOKENS: &str = stringify! { -/// #[proc_macro_derive(MyMacro)] -/// # }; -/// pub fn my_macro(input: TokenStream) -> TokenStream { -/// // Parse the tokens into a syntax tree -/// let ast: DeriveInput = syn::parse(input).unwrap(); -/// -/// // Build the output, possibly using quasi-quotation -/// let expanded = quote! { -/// /* ... */ -/// }; -/// -/// // Convert into a token stream and return it -/// expanded.into() -/// } -/// ``` +/// This function enforces that the input is fully parsed. If there are any +/// unparsed tokens at the end of the stream, an error is returned. #[cfg(all(feature = "parsing", feature = "proc-macro"))] #[cfg_attr(docsrs, doc(cfg(all(feature = "parsing", feature = "proc-macro"))))] pub fn parse(tokens: proc_macro::TokenStream) -> Result { @@ -917,9 +905,6 @@ pub fn parse(tokens: proc_macro::TokenStream) -> Result { /// Parse a proc-macro2 token stream into the chosen syntax tree node. /// -/// This function will check that the input is fully parsed. If there are -/// any unparsed tokens at the end of the stream, an error is returned. -/// /// This function parses a `proc_macro2::TokenStream` which is commonly useful /// when the input comes from a node of the Syn syntax tree, for example the /// body tokens of a [`Macro`] node. When in a procedural macro parsing the @@ -927,6 +912,9 @@ pub fn parse(tokens: proc_macro::TokenStream) -> Result { /// instead. /// /// [`syn::parse`]: parse() +/// +/// This function enforces that the input is fully parsed. If there are any +/// unparsed tokens at the end of the stream, an error is returned. #[cfg(feature = "parsing")] #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] pub fn parse2(tokens: proc_macro2::TokenStream) -> Result { @@ -935,6 +923,9 @@ pub fn parse2(tokens: proc_macro2::TokenStream) -> Result { /// Parse a string of Rust code into the chosen syntax tree node. /// +/// This function enforces that the input is fully parsed. If there are any +/// unparsed tokens at the end of the stream, an error is returned. +/// /// # Hygiene /// /// Every span in the resulting syntax tree will be set to resolve at the macro @@ -973,14 +964,11 @@ pub fn parse_str(s: &str) -> Result { /// /// ```no_run /// use std::error::Error; -/// use std::fs::File; +/// use std::fs; /// use std::io::Read; /// /// fn run() -> Result<(), Box> { -/// let mut file = File::open("path/to/code.rs")?; -/// let mut content = String::new(); -/// file.read_to_string(&mut content)?; -/// +/// let content = fs::read_to_string("path/to/code.rs")?; /// let ast = syn::parse_file(&content)?; /// if let Some(shebang) = ast.shebang { /// println!("{}", shebang); diff --git a/pkg/installer/vendor/syn/src/lookahead.rs b/pkg/installer/vendor/syn/src/lookahead.rs index 75e3a658a37..da13ffc47a7 100644 --- a/pkg/installer/vendor/syn/src/lookahead.rs +++ b/pkg/installer/vendor/syn/src/lookahead.rs @@ -2,8 +2,8 @@ use crate::buffer::Cursor; use crate::error::{self, Error}; use crate::sealed::lookahead::Sealed; use crate::span::IntoSpans; -use crate::token::Token; -use proc_macro2::Span; +use crate::token::{CustomToken, Token}; +use proc_macro2::{Delimiter, Span}; use std::cell::RefCell; /// Support for checking the next token in a stream to decide how to parse. @@ -110,7 +110,18 @@ impl<'a> Lookahead1<'a> { /// The error message will identify all of the expected token types that /// have been peeked against this lookahead instance. pub fn error(self) -> Error { - let comparisons = self.comparisons.into_inner(); + let mut comparisons = self.comparisons.into_inner(); + comparisons.retain_mut(|display| { + if *display == "`)`" { + *display = match self.cursor.scope_delimiter() { + Delimiter::Parenthesis => "`)`", + Delimiter::Brace => "`}`", + Delimiter::Bracket => "`]`", + Delimiter::None => return false, + } + } + true + }); match comparisons.len() { 0 => { if self.cursor.eof() { @@ -150,6 +161,160 @@ pub trait Peek: Sealed { type Token: Token; } +/// Pseudo-token used for peeking the end of a parse stream. +/// +/// This type is only useful as an argument to one of the following functions: +/// +/// - [`ParseStream::peek`][crate::parse::ParseBuffer::peek] +/// - [`ParseStream::peek2`][crate::parse::ParseBuffer::peek2] +/// - [`ParseStream::peek3`][crate::parse::ParseBuffer::peek3] +/// - [`Lookahead1::peek`] +/// +/// The peek will return `true` if there are no remaining tokens after that +/// point in the parse stream. +/// +/// # Example +/// +/// Suppose we are parsing attributes containing core::fmt inspired formatting +/// arguments: +/// +/// - `#[fmt("simple example")]` +/// - `#[fmt("interpolation e{}ample", self.x)]` +/// - `#[fmt("interpolation e{x}ample")]` +/// +/// and we want to recognize the cases where no interpolation occurs so that +/// more efficient code can be generated. +/// +/// The following implementation uses `input.peek(Token![,]) && +/// input.peek2(End)` to recognize the case of a trailing comma without +/// consuming the comma from the parse stream, because if it isn't a trailing +/// comma, that same comma needs to be parsed as part of `args`. +/// +/// ``` +/// use proc_macro2::TokenStream; +/// use quote::quote; +/// use syn::parse::{End, Parse, ParseStream, Result}; +/// use syn::{parse_quote, Attribute, LitStr, Token}; +/// +/// struct FormatArgs { +/// template: LitStr, // "...{}..." +/// args: TokenStream, // , self.x +/// } +/// +/// impl Parse for FormatArgs { +/// fn parse(input: ParseStream) -> Result { +/// let template: LitStr = input.parse()?; +/// +/// let args = if input.is_empty() +/// || input.peek(Token![,]) && input.peek2(End) +/// { +/// input.parse::>()?; +/// TokenStream::new() +/// } else { +/// input.parse()? +/// }; +/// +/// Ok(FormatArgs { +/// template, +/// args, +/// }) +/// } +/// } +/// +/// fn main() -> Result<()> { +/// let attrs: Vec = parse_quote! { +/// #[fmt("simple example")] +/// #[fmt("interpolation e{}ample", self.x)] +/// #[fmt("interpolation e{x}ample")] +/// }; +/// +/// for attr in &attrs { +/// let FormatArgs { template, args } = attr.parse_args()?; +/// let requires_fmt_machinery = +/// !args.is_empty() || template.value().contains(['{', '}']); +/// let out = if requires_fmt_machinery { +/// quote! { +/// ::core::write!(__formatter, #template #args) +/// } +/// } else { +/// quote! { +/// __formatter.write_str(#template) +/// } +/// }; +/// println!("{}", out); +/// } +/// Ok(()) +/// } +/// ``` +/// +/// Implementing this parsing logic without `peek2(End)` is more clumsy because +/// we'd need a parse stream actually advanced past the comma before being able +/// to find out whether there is anything after it. It would look something +/// like: +/// +/// ``` +/// # use proc_macro2::TokenStream; +/// # use syn::parse::{ParseStream, Result}; +/// # use syn::Token; +/// # +/// # fn parse(input: ParseStream) -> Result<()> { +/// use syn::parse::discouraged::Speculative as _; +/// +/// let ahead = input.fork(); +/// ahead.parse::>()?; +/// let args = if ahead.is_empty() { +/// input.advance_to(&ahead); +/// TokenStream::new() +/// } else { +/// input.parse()? +/// }; +/// # Ok(()) +/// # } +/// ``` +/// +/// or: +/// +/// ``` +/// # use proc_macro2::TokenStream; +/// # use syn::parse::{ParseStream, Result}; +/// # use syn::Token; +/// # +/// # fn parse(input: ParseStream) -> Result<()> { +/// use quote::ToTokens as _; +/// +/// let comma: Option = input.parse()?; +/// let mut args = TokenStream::new(); +/// if !input.is_empty() { +/// comma.to_tokens(&mut args); +/// input.parse::()?.to_tokens(&mut args); +/// } +/// # Ok(()) +/// # } +/// ``` +pub struct End; + +impl Copy for End {} + +impl Clone for End { + fn clone(&self) -> Self { + *self + } +} + +impl Peek for End { + type Token = Self; +} + +impl CustomToken for End { + fn peek(cursor: Cursor) -> bool { + cursor.eof() + } + + fn display() -> &'static str { + "`)`" // Lookahead1 error message will fill in the expected close delimiter + } +} + impl T, T: Token> Peek for F { type Token = T; } @@ -163,3 +328,5 @@ impl IntoSpans for TokenMarker { } impl T, T: Token> Sealed for F {} + +impl Sealed for End {} diff --git a/pkg/installer/vendor/syn/src/mac.rs b/pkg/installer/vendor/syn/src/mac.rs index 7e1876c6482..15107801cfe 100644 --- a/pkg/installer/vendor/syn/src/mac.rs +++ b/pkg/installer/vendor/syn/src/mac.rs @@ -197,6 +197,8 @@ pub(crate) mod parsing { #[cfg(feature = "printing")] mod printing { use crate::mac::{Macro, MacroDelimiter}; + use crate::path; + use crate::path::printing::PathStyle; use crate::token; use proc_macro2::{Delimiter, TokenStream}; use quote::ToTokens; @@ -215,7 +217,7 @@ mod printing { #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for Macro { fn to_tokens(&self, tokens: &mut TokenStream) { - self.path.to_tokens(tokens); + path::printing::print_path(tokens, &self.path, PathStyle::Mod); self.bang_token.to_tokens(tokens); self.delimiter.surround(tokens, self.tokens.clone()); } diff --git a/pkg/installer/vendor/syn/src/parse.rs b/pkg/installer/vendor/syn/src/parse.rs index 0dae9259d1c..b7f8831d672 100644 --- a/pkg/installer/vendor/syn/src/parse.rs +++ b/pkg/installer/vendor/syn/src/parse.rs @@ -202,7 +202,7 @@ use std::rc::Rc; use std::str::FromStr; pub use crate::error::{Error, Result}; -pub use crate::lookahead::{Lookahead1, Peek}; +pub use crate::lookahead::{End, Lookahead1, Peek}; /// Parsing interface implemented by all types that can be parsed in a default /// way from a token stream. @@ -751,6 +751,11 @@ impl<'a> ParseBuffer<'a> { /// set of delimiters, as well as at the end of the tokens provided to the /// outermost parsing entry point. /// + /// This is equivalent to + /// .peek(syn::parse::End). + /// Use `.peek2(End)` or `.peek3(End)` to look for the end of a parse stream + /// further ahead than the current position. + /// /// # Example /// /// ``` @@ -1236,14 +1241,14 @@ pub trait Parser: Sized { /// Parse a proc-macro2 token stream into the chosen syntax tree node. /// - /// This function will check that the input is fully parsed. If there are - /// any unparsed tokens at the end of the stream, an error is returned. + /// This function enforces that the input is fully parsed. If there are any + /// unparsed tokens at the end of the stream, an error is returned. fn parse2(self, tokens: TokenStream) -> Result; /// Parse tokens of source code into the chosen syntax tree node. /// - /// This function will check that the input is fully parsed. If there are - /// any unparsed tokens at the end of the stream, an error is returned. + /// This function enforces that the input is fully parsed. If there are any + /// unparsed tokens at the end of the stream, an error is returned. #[cfg(feature = "proc-macro")] #[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))] fn parse(self, tokens: proc_macro::TokenStream) -> Result { @@ -1252,8 +1257,8 @@ pub trait Parser: Sized { /// Parse a string of Rust code into the chosen syntax tree node. /// - /// This function will check that the input is fully parsed. If there are - /// any unparsed tokens at the end of the string, an error is returned. + /// This function enforces that the input is fully parsed. If there are any + /// unparsed tokens at the end of the string, an error is returned. /// /// # Hygiene /// diff --git a/pkg/installer/vendor/syn/src/parse_quote.rs b/pkg/installer/vendor/syn/src/parse_quote.rs index 22cd98effb5..fa7ea79f472 100644 --- a/pkg/installer/vendor/syn/src/parse_quote.rs +++ b/pkg/installer/vendor/syn/src/parse_quote.rs @@ -153,6 +153,17 @@ impl ParseQuote for Attribute { } } +#[cfg(any(feature = "full", feature = "derive"))] +impl ParseQuote for Vec { + fn parse(input: ParseStream) -> Result { + let mut attrs = Vec::new(); + while !input.is_empty() { + attrs.push(ParseQuote::parse(input)?); + } + Ok(attrs) + } +} + #[cfg(any(feature = "full", feature = "derive"))] impl ParseQuote for Field { fn parse(input: ParseStream) -> Result { diff --git a/pkg/installer/vendor/syn/src/pat.rs b/pkg/installer/vendor/syn/src/pat.rs index e647f2f4d04..81a2f183f6b 100644 --- a/pkg/installer/vendor/syn/src/pat.rs +++ b/pkg/installer/vendor/syn/src/pat.rs @@ -417,7 +417,8 @@ pub(crate) mod parsing { } fn pat_path_or_macro_or_struct_or_range(input: ParseStream) -> Result { - let (qself, path) = path::parsing::qpath(input, true)?; + let expr_style = true; + let (qself, path) = path::parsing::qpath(input, expr_style)?; if qself.is_none() && input.peek(Token![!]) @@ -811,6 +812,7 @@ mod printing { PatTuple, PatTupleStruct, PatType, PatWild, }; use crate::path; + use crate::path::printing::PathStyle; use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; @@ -879,7 +881,7 @@ mod printing { impl ToTokens for PatStruct { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); - path::printing::print_path(tokens, &self.qself, &self.path); + path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::Expr); self.brace_token.surround(tokens, |tokens| { self.fields.to_tokens(tokens); // NOTE: We need a comma before the dot2 token if it is present. @@ -914,7 +916,7 @@ mod printing { impl ToTokens for PatTupleStruct { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); - path::printing::print_path(tokens, &self.qself, &self.path); + path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::Expr); self.paren_token.surround(tokens, |tokens| { self.elems.to_tokens(tokens); }); diff --git a/pkg/installer/vendor/syn/src/path.rs b/pkg/installer/vendor/syn/src/path.rs index 636d5d5e8fa..ce38eff3139 100644 --- a/pkg/installer/vendor/syn/src/path.rs +++ b/pkg/installer/vendor/syn/src/path.rs @@ -377,8 +377,15 @@ pub(crate) mod parsing { if input.peek(Token![,]) || input.peek(Token![>]) { break; } - let value: TypeParamBound = input.parse()?; - bounds.push_value(value); + bounds.push_value({ + let allow_precise_capture = false; + let allow_tilde_const = true; + TypeParamBound::parse_single( + input, + allow_precise_capture, + allow_tilde_const, + )? + }); if !input.peek(Token![+]) { break; } @@ -702,33 +709,62 @@ pub(crate) mod printing { use quote::ToTokens; use std::cmp; + pub(crate) enum PathStyle { + Expr, + Mod, + AsWritten, + } + + impl Copy for PathStyle {} + + impl Clone for PathStyle { + fn clone(&self) -> Self { + *self + } + } + #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for Path { fn to_tokens(&self, tokens: &mut TokenStream) { - self.leading_colon.to_tokens(tokens); - self.segments.to_tokens(tokens); + print_path(tokens, self, PathStyle::AsWritten); + } + } + + pub(crate) fn print_path(tokens: &mut TokenStream, path: &Path, style: PathStyle) { + path.leading_colon.to_tokens(tokens); + for segment in path.segments.pairs() { + print_path_segment(tokens, segment.value(), style); + segment.punct().to_tokens(tokens); } } #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for PathSegment { fn to_tokens(&self, tokens: &mut TokenStream) { - self.ident.to_tokens(tokens); - self.arguments.to_tokens(tokens); + print_path_segment(tokens, self, PathStyle::AsWritten); } } + fn print_path_segment(tokens: &mut TokenStream, segment: &PathSegment, style: PathStyle) { + segment.ident.to_tokens(tokens); + print_path_arguments(tokens, &segment.arguments, style); + } + #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for PathArguments { fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - PathArguments::None => {} - PathArguments::AngleBracketed(arguments) => { - arguments.to_tokens(tokens); - } - PathArguments::Parenthesized(arguments) => { - arguments.to_tokens(tokens); - } + print_path_arguments(tokens, self, PathStyle::AsWritten); + } + } + + fn print_path_arguments(tokens: &mut TokenStream, arguments: &PathArguments, style: PathStyle) { + match arguments { + PathArguments::None => {} + PathArguments::AngleBracketed(arguments) => { + print_angle_bracketed_generic_arguments(tokens, arguments, style); + } + PathArguments::Parenthesized(arguments) => { + print_parenthesized_generic_arguments(tokens, arguments, style); } } } @@ -753,44 +789,56 @@ pub(crate) mod printing { #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for AngleBracketedGenericArguments { fn to_tokens(&self, tokens: &mut TokenStream) { - self.colon2_token.to_tokens(tokens); - self.lt_token.to_tokens(tokens); - - // Print lifetimes before types/consts/bindings, regardless of their - // order in self.args. - let mut trailing_or_empty = true; - for param in self.args.pairs() { - match param.value() { - GenericArgument::Lifetime(_) => { - param.to_tokens(tokens); - trailing_or_empty = param.punct().is_some(); - } - GenericArgument::Type(_) - | GenericArgument::Const(_) - | GenericArgument::AssocType(_) - | GenericArgument::AssocConst(_) - | GenericArgument::Constraint(_) => {} + print_angle_bracketed_generic_arguments(tokens, self, PathStyle::AsWritten); + } + } + + pub(crate) fn print_angle_bracketed_generic_arguments( + tokens: &mut TokenStream, + arguments: &AngleBracketedGenericArguments, + style: PathStyle, + ) { + if let PathStyle::Mod = style { + return; + } + + conditionally_print_turbofish(tokens, &arguments.colon2_token, style); + arguments.lt_token.to_tokens(tokens); + + // Print lifetimes before types/consts/bindings, regardless of their + // order in args. + let mut trailing_or_empty = true; + for param in arguments.args.pairs() { + match param.value() { + GenericArgument::Lifetime(_) => { + param.to_tokens(tokens); + trailing_or_empty = param.punct().is_some(); } + GenericArgument::Type(_) + | GenericArgument::Const(_) + | GenericArgument::AssocType(_) + | GenericArgument::AssocConst(_) + | GenericArgument::Constraint(_) => {} } - for param in self.args.pairs() { - match param.value() { - GenericArgument::Type(_) - | GenericArgument::Const(_) - | GenericArgument::AssocType(_) - | GenericArgument::AssocConst(_) - | GenericArgument::Constraint(_) => { - if !trailing_or_empty { - ::default().to_tokens(tokens); - } - param.to_tokens(tokens); - trailing_or_empty = param.punct().is_some(); + } + for param in arguments.args.pairs() { + match param.value() { + GenericArgument::Type(_) + | GenericArgument::Const(_) + | GenericArgument::AssocType(_) + | GenericArgument::AssocConst(_) + | GenericArgument::Constraint(_) => { + if !trailing_or_empty { + ::default().to_tokens(tokens); } - GenericArgument::Lifetime(_) => {} + param.to_tokens(tokens); + trailing_or_empty = param.punct().is_some(); } + GenericArgument::Lifetime(_) => {} } - - self.gt_token.to_tokens(tokens); } + + arguments.gt_token.to_tokens(tokens); } #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] @@ -826,18 +874,36 @@ pub(crate) mod printing { #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for ParenthesizedGenericArguments { fn to_tokens(&self, tokens: &mut TokenStream) { - self.paren_token.surround(tokens, |tokens| { - self.inputs.to_tokens(tokens); - }); - self.output.to_tokens(tokens); + print_parenthesized_generic_arguments(tokens, self, PathStyle::AsWritten); } } - pub(crate) fn print_path(tokens: &mut TokenStream, qself: &Option, path: &Path) { + fn print_parenthesized_generic_arguments( + tokens: &mut TokenStream, + arguments: &ParenthesizedGenericArguments, + style: PathStyle, + ) { + if let PathStyle::Mod = style { + return; + } + + conditionally_print_turbofish(tokens, &None, style); + arguments.paren_token.surround(tokens, |tokens| { + arguments.inputs.to_tokens(tokens); + }); + arguments.output.to_tokens(tokens); + } + + pub(crate) fn print_qpath( + tokens: &mut TokenStream, + qself: &Option, + path: &Path, + style: PathStyle, + ) { let qself = match qself { Some(qself) => qself, None => { - path.to_tokens(tokens); + print_path(tokens, path, style); return; } }; @@ -850,20 +916,31 @@ pub(crate) mod printing { TokensOrDefault(&qself.as_token).to_tokens(tokens); path.leading_colon.to_tokens(tokens); for (i, segment) in segments.by_ref().take(pos).enumerate() { + print_path_segment(tokens, segment.value(), PathStyle::AsWritten); if i + 1 == pos { - segment.value().to_tokens(tokens); qself.gt_token.to_tokens(tokens); - segment.punct().to_tokens(tokens); - } else { - segment.to_tokens(tokens); } + segment.punct().to_tokens(tokens); } } else { qself.gt_token.to_tokens(tokens); path.leading_colon.to_tokens(tokens); } for segment in segments { - segment.to_tokens(tokens); + print_path_segment(tokens, segment.value(), style); + segment.punct().to_tokens(tokens); + } + } + + fn conditionally_print_turbofish( + tokens: &mut TokenStream, + colon2_token: &Option, + style: PathStyle, + ) { + match style { + PathStyle::Expr => TokensOrDefault(colon2_token).to_tokens(tokens), + PathStyle::Mod => unreachable!(), + PathStyle::AsWritten => colon2_token.to_tokens(tokens), } } diff --git a/pkg/installer/vendor/syn/src/precedence.rs b/pkg/installer/vendor/syn/src/precedence.rs index 1a26f195db7..936a0c51d2d 100644 --- a/pkg/installer/vendor/syn/src/precedence.rs +++ b/pkg/installer/vendor/syn/src/precedence.rs @@ -102,7 +102,7 @@ impl Precedence { Expr::Binary(e) => Precedence::of_binop(&e.op), Expr::Let(_) => Precedence::Let, Expr::Cast(_) => Precedence::Cast, - Expr::Reference(_) | Expr::Unary(_) => Precedence::Prefix, + Expr::RawAddr(_) | Expr::Reference(_) | Expr::Unary(_) => Precedence::Prefix, Expr::Array(_) | Expr::Async(_) diff --git a/pkg/installer/vendor/syn/src/restriction.rs b/pkg/installer/vendor/syn/src/restriction.rs index 8a4d4706a55..6e6758f3cd7 100644 --- a/pkg/installer/vendor/syn/src/restriction.rs +++ b/pkg/installer/vendor/syn/src/restriction.rs @@ -146,6 +146,8 @@ pub(crate) mod parsing { #[cfg(feature = "printing")] mod printing { + use crate::path; + use crate::path::printing::PathStyle; use crate::restriction::{VisRestricted, Visibility}; use proc_macro2::TokenStream; use quote::ToTokens; @@ -169,7 +171,7 @@ mod printing { // TODO: If we have a path which is not "self" or "super" or // "crate", automatically add the "in" token. self.in_token.to_tokens(tokens); - self.path.to_tokens(tokens); + path::printing::print_path(tokens, &self.path, PathStyle::Mod); }); } } diff --git a/pkg/installer/vendor/syn/src/scan_expr.rs b/pkg/installer/vendor/syn/src/scan_expr.rs new file mode 100644 index 00000000000..155b5b63bf0 --- /dev/null +++ b/pkg/installer/vendor/syn/src/scan_expr.rs @@ -0,0 +1,264 @@ +use self::{Action::*, Input::*}; +use proc_macro2::{Delimiter, Ident, Spacing, TokenTree}; +use syn::parse::{ParseStream, Result}; +use syn::{AngleBracketedGenericArguments, BinOp, Expr, ExprPath, Lifetime, Lit, Token, Type}; + +enum Input { + Keyword(&'static str), + Punct(&'static str), + ConsumeAny, + ConsumeBinOp, + ConsumeBrace, + ConsumeDelimiter, + ConsumeIdent, + ConsumeLifetime, + ConsumeLiteral, + ConsumeNestedBrace, + ExpectPath, + ExpectTurbofish, + ExpectType, + CanBeginExpr, + Otherwise, + Empty, +} + +enum Action { + SetState(&'static [(Input, Action)]), + IncDepth, + DecDepth, + Finish, +} + +static INIT: [(Input, Action); 28] = [ + (ConsumeDelimiter, SetState(&POSTFIX)), + (Keyword("async"), SetState(&ASYNC)), + (Keyword("break"), SetState(&BREAK_LABEL)), + (Keyword("const"), SetState(&CONST)), + (Keyword("continue"), SetState(&CONTINUE)), + (Keyword("for"), SetState(&FOR)), + (Keyword("if"), IncDepth), + (Keyword("let"), SetState(&PATTERN)), + (Keyword("loop"), SetState(&BLOCK)), + (Keyword("match"), IncDepth), + (Keyword("move"), SetState(&CLOSURE)), + (Keyword("return"), SetState(&RETURN)), + (Keyword("static"), SetState(&CLOSURE)), + (Keyword("unsafe"), SetState(&BLOCK)), + (Keyword("while"), IncDepth), + (Keyword("yield"), SetState(&RETURN)), + (Keyword("_"), SetState(&POSTFIX)), + (Punct("!"), SetState(&INIT)), + (Punct("#"), SetState(&[(ConsumeDelimiter, SetState(&INIT))])), + (Punct("&"), SetState(&REFERENCE)), + (Punct("*"), SetState(&INIT)), + (Punct("-"), SetState(&INIT)), + (Punct("..="), SetState(&INIT)), + (Punct(".."), SetState(&RANGE)), + (Punct("|"), SetState(&CLOSURE_ARGS)), + (ConsumeLifetime, SetState(&[(Punct(":"), SetState(&INIT))])), + (ConsumeLiteral, SetState(&POSTFIX)), + (ExpectPath, SetState(&PATH)), +]; + +static POSTFIX: [(Input, Action); 10] = [ + (Keyword("as"), SetState(&[(ExpectType, SetState(&POSTFIX))])), + (Punct("..="), SetState(&INIT)), + (Punct(".."), SetState(&RANGE)), + (Punct("."), SetState(&DOT)), + (Punct("?"), SetState(&POSTFIX)), + (ConsumeBinOp, SetState(&INIT)), + (Punct("="), SetState(&INIT)), + (ConsumeNestedBrace, SetState(&IF_THEN)), + (ConsumeDelimiter, SetState(&POSTFIX)), + (Empty, Finish), +]; + +static ASYNC: [(Input, Action); 3] = [ + (Keyword("move"), SetState(&ASYNC)), + (Punct("|"), SetState(&CLOSURE_ARGS)), + (ConsumeBrace, SetState(&POSTFIX)), +]; + +static BLOCK: [(Input, Action); 1] = [(ConsumeBrace, SetState(&POSTFIX))]; + +static BREAK_LABEL: [(Input, Action); 2] = [ + (ConsumeLifetime, SetState(&BREAK_VALUE)), + (Otherwise, SetState(&BREAK_VALUE)), +]; + +static BREAK_VALUE: [(Input, Action); 3] = [ + (ConsumeNestedBrace, SetState(&IF_THEN)), + (CanBeginExpr, SetState(&INIT)), + (Otherwise, SetState(&POSTFIX)), +]; + +static CLOSURE: [(Input, Action); 6] = [ + (Keyword("async"), SetState(&CLOSURE)), + (Keyword("move"), SetState(&CLOSURE)), + (Punct(","), SetState(&CLOSURE)), + (Punct(">"), SetState(&CLOSURE)), + (Punct("|"), SetState(&CLOSURE_ARGS)), + (ConsumeLifetime, SetState(&CLOSURE)), +]; + +static CLOSURE_ARGS: [(Input, Action); 2] = [ + (Punct("|"), SetState(&CLOSURE_RET)), + (ConsumeAny, SetState(&CLOSURE_ARGS)), +]; + +static CLOSURE_RET: [(Input, Action); 2] = [ + (Punct("->"), SetState(&[(ExpectType, SetState(&BLOCK))])), + (Otherwise, SetState(&INIT)), +]; + +static CONST: [(Input, Action); 2] = [ + (Punct("|"), SetState(&CLOSURE_ARGS)), + (ConsumeBrace, SetState(&POSTFIX)), +]; + +static CONTINUE: [(Input, Action); 2] = [ + (ConsumeLifetime, SetState(&POSTFIX)), + (Otherwise, SetState(&POSTFIX)), +]; + +static DOT: [(Input, Action); 3] = [ + (Keyword("await"), SetState(&POSTFIX)), + (ConsumeIdent, SetState(&METHOD)), + (ConsumeLiteral, SetState(&POSTFIX)), +]; + +static FOR: [(Input, Action); 2] = [ + (Punct("<"), SetState(&CLOSURE)), + (Otherwise, SetState(&PATTERN)), +]; + +static IF_ELSE: [(Input, Action); 2] = [(Keyword("if"), SetState(&INIT)), (ConsumeBrace, DecDepth)]; +static IF_THEN: [(Input, Action); 2] = + [(Keyword("else"), SetState(&IF_ELSE)), (Otherwise, DecDepth)]; + +static METHOD: [(Input, Action); 1] = [(ExpectTurbofish, SetState(&POSTFIX))]; + +static PATH: [(Input, Action); 4] = [ + (Punct("!="), SetState(&INIT)), + (Punct("!"), SetState(&INIT)), + (ConsumeNestedBrace, SetState(&IF_THEN)), + (Otherwise, SetState(&POSTFIX)), +]; + +static PATTERN: [(Input, Action); 15] = [ + (ConsumeDelimiter, SetState(&PATTERN)), + (Keyword("box"), SetState(&PATTERN)), + (Keyword("in"), IncDepth), + (Keyword("mut"), SetState(&PATTERN)), + (Keyword("ref"), SetState(&PATTERN)), + (Keyword("_"), SetState(&PATTERN)), + (Punct("!"), SetState(&PATTERN)), + (Punct("&"), SetState(&PATTERN)), + (Punct("..="), SetState(&PATTERN)), + (Punct(".."), SetState(&PATTERN)), + (Punct("="), SetState(&INIT)), + (Punct("@"), SetState(&PATTERN)), + (Punct("|"), SetState(&PATTERN)), + (ConsumeLiteral, SetState(&PATTERN)), + (ExpectPath, SetState(&PATTERN)), +]; + +static RANGE: [(Input, Action); 6] = [ + (Punct("..="), SetState(&INIT)), + (Punct(".."), SetState(&RANGE)), + (Punct("."), SetState(&DOT)), + (ConsumeNestedBrace, SetState(&IF_THEN)), + (Empty, Finish), + (Otherwise, SetState(&INIT)), +]; + +static RAW: [(Input, Action); 3] = [ + (Keyword("const"), SetState(&INIT)), + (Keyword("mut"), SetState(&INIT)), + (Otherwise, SetState(&POSTFIX)), +]; + +static REFERENCE: [(Input, Action); 3] = [ + (Keyword("mut"), SetState(&INIT)), + (Keyword("raw"), SetState(&RAW)), + (Otherwise, SetState(&INIT)), +]; + +static RETURN: [(Input, Action); 2] = [ + (CanBeginExpr, SetState(&INIT)), + (Otherwise, SetState(&POSTFIX)), +]; + +pub(crate) fn scan_expr(input: ParseStream) -> Result<()> { + let mut state = INIT.as_slice(); + let mut depth = 0usize; + 'table: loop { + for rule in state { + if match rule.0 { + Input::Keyword(expected) => input.step(|cursor| match cursor.ident() { + Some((ident, rest)) if ident == expected => Ok((true, rest)), + _ => Ok((false, *cursor)), + })?, + Input::Punct(expected) => input.step(|cursor| { + let begin = *cursor; + let mut cursor = begin; + for (i, ch) in expected.chars().enumerate() { + match cursor.punct() { + Some((punct, _)) if punct.as_char() != ch => break, + Some((_, rest)) if i == expected.len() - 1 => { + return Ok((true, rest)); + } + Some((punct, rest)) if punct.spacing() == Spacing::Joint => { + cursor = rest; + } + _ => break, + } + } + Ok((false, begin)) + })?, + Input::ConsumeAny => input.parse::>()?.is_some(), + Input::ConsumeBinOp => input.parse::().is_ok(), + Input::ConsumeBrace | Input::ConsumeNestedBrace => { + (matches!(rule.0, Input::ConsumeBrace) || depth > 0) + && input.step(|cursor| match cursor.group(Delimiter::Brace) { + Some((_inside, _span, rest)) => Ok((true, rest)), + None => Ok((false, *cursor)), + })? + } + Input::ConsumeDelimiter => input.step(|cursor| match cursor.any_group() { + Some((_inside, _delimiter, _span, rest)) => Ok((true, rest)), + None => Ok((false, *cursor)), + })?, + Input::ConsumeIdent => input.parse::>()?.is_some(), + Input::ConsumeLifetime => input.parse::>()?.is_some(), + Input::ConsumeLiteral => input.parse::>()?.is_some(), + Input::ExpectPath => { + input.parse::()?; + true + } + Input::ExpectTurbofish => { + if input.peek(Token![::]) { + input.parse::()?; + } + true + } + Input::ExpectType => { + Type::without_plus(input)?; + true + } + Input::CanBeginExpr => Expr::peek(input), + Input::Otherwise => true, + Input::Empty => input.is_empty() || input.peek(Token![,]), + } { + state = match rule.1 { + Action::SetState(next) => next, + Action::IncDepth => (depth += 1, &INIT).1, + Action::DecDepth => (depth -= 1, &POSTFIX).1, + Action::Finish => return if depth == 0 { Ok(()) } else { break }, + }; + continue 'table; + } + } + return Err(input.error("unsupported expression")); + } +} diff --git a/pkg/installer/vendor/syn/src/stmt.rs b/pkg/installer/vendor/syn/src/stmt.rs index 51d000581af..ac8238a98aa 100644 --- a/pkg/installer/vendor/syn/src/stmt.rs +++ b/pkg/installer/vendor/syn/src/stmt.rs @@ -367,6 +367,7 @@ pub(crate) mod parsing { | Expr::Paren(_) | Expr::Path(_) | Expr::Range(_) + | Expr::RawAddr(_) | Expr::Reference(_) | Expr::Repeat(_) | Expr::Return(_) diff --git a/pkg/installer/vendor/syn/src/token.rs b/pkg/installer/vendor/syn/src/token.rs index 061e8806ca9..6462713254e 100644 --- a/pkg/installer/vendor/syn/src/token.rs +++ b/pkg/installer/vendor/syn/src/token.rs @@ -721,6 +721,7 @@ define_keywords! { "override" pub struct Override "priv" pub struct Priv "pub" pub struct Pub + "raw" pub struct Raw "ref" pub struct Ref "return" pub struct Return "Self" pub struct SelfType @@ -899,6 +900,7 @@ macro_rules! Token { [override] => { $crate::token::Override }; [priv] => { $crate::token::Priv }; [pub] => { $crate::token::Pub }; + [raw] => { $crate::token::Raw }; [ref] => { $crate::token::Ref }; [return] => { $crate::token::Return }; [Self] => { $crate::token::SelfType }; diff --git a/pkg/installer/vendor/syn/src/ty.rs b/pkg/installer/vendor/syn/src/ty.rs index a1543be0564..ff43ae560eb 100644 --- a/pkg/installer/vendor/syn/src/ty.rs +++ b/pkg/installer/vendor/syn/src/ty.rs @@ -402,7 +402,15 @@ pub(crate) mod parsing { })); while let Some(plus) = input.parse()? { bounds.push_punct(plus); - bounds.push_value(input.parse()?); + bounds.push_value({ + let allow_precise_capture = false; + let allow_tilde_const = false; + TypeParamBound::parse_single( + input, + allow_precise_capture, + allow_tilde_const, + )? + }); } bounds }, @@ -457,6 +465,7 @@ pub(crate) mod parsing { }) } other @ (TypeParamBound::Lifetime(_) + | TypeParamBound::PreciseCapture(_) | TypeParamBound::Verbatim(_)) => other, } } @@ -469,7 +478,15 @@ pub(crate) mod parsing { bounds.push_value(first); while let Some(plus) = input.parse()? { bounds.push_punct(plus); - bounds.push_value(input.parse()?); + bounds.push_value({ + let allow_precise_capture = false; + let allow_tilde_const = false; + TypeParamBound::parse_single( + input, + allow_precise_capture, + allow_tilde_const, + )? + }); } bounds }, @@ -532,7 +549,15 @@ pub(crate) mod parsing { { break; } - bounds.push_value(input.parse()?); + bounds.push_value({ + let allow_precise_capture = false; + let allow_tilde_const = false; + TypeParamBound::parse_single( + input, + allow_precise_capture, + allow_tilde_const, + )? + }); } } return Ok(Type::TraitObject(TypeTraitObject { @@ -823,18 +848,28 @@ pub(crate) mod parsing { input: ParseStream, allow_plus: bool, ) -> Result> { - let bounds = TypeParamBound::parse_multiple(input, allow_plus)?; + let allow_precise_capture = false; + let allow_tilde_const = false; + let bounds = TypeParamBound::parse_multiple( + input, + allow_plus, + allow_precise_capture, + allow_tilde_const, + )?; let mut last_lifetime_span = None; let mut at_least_one_trait = false; for bound in &bounds { match bound { - TypeParamBound::Trait(_) | TypeParamBound::Verbatim(_) => { + TypeParamBound::Trait(_) => { at_least_one_trait = true; break; } TypeParamBound::Lifetime(lifetime) => { last_lifetime_span = Some(lifetime.ident.span()); } + TypeParamBound::PreciseCapture(_) | TypeParamBound::Verbatim(_) => { + unreachable!() + } } } // Just lifetimes like `'a + 'b` is not a TraitObject. @@ -863,17 +898,40 @@ pub(crate) mod parsing { pub(crate) fn parse(input: ParseStream, allow_plus: bool) -> Result { let impl_token: Token![impl] = input.parse()?; - let bounds = TypeParamBound::parse_multiple(input, allow_plus)?; - let mut last_lifetime_span = None; + let allow_precise_capture = true; + let allow_tilde_const = false; + let bounds = TypeParamBound::parse_multiple( + input, + allow_plus, + allow_precise_capture, + allow_tilde_const, + )?; + let mut last_nontrait_span = None; let mut at_least_one_trait = false; for bound in &bounds { match bound { - TypeParamBound::Trait(_) | TypeParamBound::Verbatim(_) => { + TypeParamBound::Trait(_) => { at_least_one_trait = true; break; } TypeParamBound::Lifetime(lifetime) => { - last_lifetime_span = Some(lifetime.ident.span()); + last_nontrait_span = Some(lifetime.ident.span()); + } + TypeParamBound::PreciseCapture(precise_capture) => { + #[cfg(feature = "full")] + { + last_nontrait_span = Some(precise_capture.gt_token.span); + } + #[cfg(not(feature = "full"))] + { + _ = precise_capture; + unreachable!(); + } + } + TypeParamBound::Verbatim(_) => { + // ~const Trait + at_least_one_trait = true; + break; } } } @@ -881,7 +939,7 @@ pub(crate) mod parsing { let msg = "at least one trait must be specified"; return Err(error::new2( impl_token.span, - last_lifetime_span.unwrap(), + last_nontrait_span.unwrap(), msg, )); } @@ -1018,6 +1076,7 @@ pub(crate) mod parsing { mod printing { use crate::attr::FilterAttrs; use crate::path; + use crate::path::printing::PathStyle; use crate::print::TokensOrDefault; use crate::ty::{ Abi, BareFnArg, BareVariadic, ReturnType, TypeArray, TypeBareFn, TypeGroup, TypeImplTrait, @@ -1116,7 +1175,7 @@ mod printing { #[cfg_attr(docsrs, doc(cfg(feature = "printing")))] impl ToTokens for TypePath { fn to_tokens(&self, tokens: &mut TokenStream) { - path::printing::print_path(tokens, &self.qself, &self.path); + path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::AsWritten); } } diff --git a/pkg/installer/vendor/syn/tests/common/eq.rs b/pkg/installer/vendor/syn/tests/common/eq.rs index 57c6432b1b5..119df2b73ec 100644 --- a/pkg/installer/vendor/syn/tests/common/eq.rs +++ b/pkg/installer/vendor/syn/tests/common/eq.rs @@ -10,6 +10,7 @@ use rustc_ast::ast::AngleBracketedArg; use rustc_ast::ast::AngleBracketedArgs; use rustc_ast::ast::AnonConst; use rustc_ast::ast::Arm; +use rustc_ast::ast::AsmMacro; use rustc_ast::ast::AssocItemConstraint; use rustc_ast::ast::AssocItemConstraintKind; use rustc_ast::ast::AssocItemKind; @@ -103,6 +104,7 @@ use rustc_ast::ast::MacStmtStyle; use rustc_ast::ast::MacroDef; use rustc_ast::ast::MatchKind; use rustc_ast::ast::MetaItem; +use rustc_ast::ast::MetaItemInner; use rustc_ast::ast::MetaItemKind; use rustc_ast::ast::MetaItemLit; use rustc_ast::ast::MethodCall; @@ -111,7 +113,6 @@ use rustc_ast::ast::ModSpans; use rustc_ast::ast::Movability; use rustc_ast::ast::MutTy; use rustc_ast::ast::Mutability; -use rustc_ast::ast::NestedMetaItem; use rustc_ast::ast::NodeId; use rustc_ast::ast::NormalAttr; use rustc_ast::ast::Param; @@ -497,7 +498,7 @@ spanless_eq_struct!(Fn; defaultness generics sig body); spanless_eq_struct!(FnDecl; inputs output); spanless_eq_struct!(FnHeader; constness coroutine_kind safety ext); spanless_eq_struct!(FnSig; header decl span); -spanless_eq_struct!(ForeignMod; safety abi items); +spanless_eq_struct!(ForeignMod; extern_span safety abi items); spanless_eq_struct!(FormatArgPosition; index kind span); spanless_eq_struct!(FormatArgs; span template arguments); spanless_eq_struct!(FormatArgument; kind expr); @@ -506,7 +507,7 @@ spanless_eq_struct!(FormatPlaceholder; argument span format_trait format_options spanless_eq_struct!(GenericParam; id ident attrs bounds is_placeholder kind !colon_span); spanless_eq_struct!(Generics; params where_clause span); spanless_eq_struct!(Impl; defaultness safety generics constness polarity of_trait self_ty items); -spanless_eq_struct!(InlineAsm; template template_strs operands clobber_abis options line_spans); +spanless_eq_struct!(InlineAsm; asm_macro template template_strs operands clobber_abis options line_spans); spanless_eq_struct!(InlineAsmSym; id qself path); spanless_eq_struct!(Item; attrs id span vis ident kind !tokens); spanless_eq_struct!(Label; ident); @@ -527,7 +528,7 @@ spanless_eq_struct!(Pat; id kind span tokens); spanless_eq_struct!(PatField; ident pat is_shorthand attrs id span is_placeholder); spanless_eq_struct!(Path; span segments tokens); spanless_eq_struct!(PathSegment; ident id args); -spanless_eq_struct!(PolyTraitRef; bound_generic_params trait_ref span); +spanless_eq_struct!(PolyTraitRef; bound_generic_params modifiers trait_ref span); spanless_eq_struct!(QSelf; ty path_span position); spanless_eq_struct!(StaticItem; ty safety mutability expr); spanless_eq_struct!(Stmt; id kind span); @@ -549,6 +550,7 @@ spanless_eq_struct!(WhereClause; has_where_token predicates span); spanless_eq_struct!(WhereEqPredicate; span lhs_ty rhs_ty); spanless_eq_struct!(WhereRegionPredicate; span lifetime bounds); spanless_eq_enum!(AngleBracketedArg; Arg(0) Constraint(0)); +spanless_eq_enum!(AsmMacro; Asm GlobalAsm NakedAsm); spanless_eq_enum!(AssocItemConstraintKind; Equality(term) Bound(bounds)); spanless_eq_enum!(AssocItemKind; Const(0) Fn(0) Type(0) MacCall(0) Delegation(0) DelegationMac(0)); spanless_eq_enum!(AttrArgs; Empty Delimited(0) Eq(0 1)); @@ -582,7 +584,7 @@ spanless_eq_enum!(FormatTrait; Display Debug LowerExp UpperExp Octal Pointer Bin spanless_eq_enum!(GenBlockKind; Async Gen AsyncGen); spanless_eq_enum!(GenericArg; Lifetime(0) Type(0) Const(0)); spanless_eq_enum!(GenericArgs; AngleBracketed(0) Parenthesized(0) ParenthesizedElided(0)); -spanless_eq_enum!(GenericBound; Trait(0 1) Outlives(0) Use(0 1)); +spanless_eq_enum!(GenericBound; Trait(0) Outlives(0) Use(0 1)); spanless_eq_enum!(GenericParamKind; Lifetime Type(default) Const(ty kw_span default)); spanless_eq_enum!(ImplPolarity; Positive Negative(0)); spanless_eq_enum!(Inline; Yes No); @@ -596,10 +598,10 @@ spanless_eq_enum!(LocalKind; Decl Init(0) InitElse(0 1)); spanless_eq_enum!(MacStmtStyle; Semicolon Braces NoBraces); spanless_eq_enum!(MatchKind; Prefix Postfix); spanless_eq_enum!(MetaItemKind; Word List(0) NameValue(0)); +spanless_eq_enum!(MetaItemInner; MetaItem(0) Lit(0)); spanless_eq_enum!(ModKind; Loaded(0 1 2) Unloaded); spanless_eq_enum!(Movability; Static Movable); spanless_eq_enum!(Mutability; Mut Not); -spanless_eq_enum!(NestedMetaItem; MetaItem(0) Lit(0)); spanless_eq_enum!(PatFieldsRest; Rest None); spanless_eq_enum!(PreciseCapturingArg; Lifetime(0) Arg(0 1)); spanless_eq_enum!(RangeEnd; Included(0) Excluded); @@ -642,10 +644,9 @@ spanless_eq_enum!(LitKind; Str(0 1) ByteStr(0 1) CStr(0 1) Byte(0) Char(0) spanless_eq_enum!(PatKind; Wild Ident(0 1 2) Struct(0 1 2 3) TupleStruct(0 1 2) Or(0) Path(0 1) Tuple(0) Box(0) Deref(0) Ref(0 1) Lit(0) Range(0 1 2) Slice(0) Rest Never Paren(0) MacCall(0) Err(0)); -spanless_eq_enum!(TyKind; Slice(0) Array(0 1) Ptr(0) Ref(0 1) BareFn(0) Never - Tup(0) AnonStruct(0 1) AnonUnion(0 1) Path(0 1) TraitObject(0 1) - ImplTrait(0 1) Paren(0) Typeof(0) Infer ImplicitSelf MacCall(0) CVarArgs - Pat(0 1) Dummy Err(0)); +spanless_eq_enum!(TyKind; Slice(0) Array(0 1) Ptr(0) Ref(0 1) PinnedRef(0 1) + BareFn(0) Never Tup(0) Path(0 1) TraitObject(0 1) ImplTrait(0 1) Paren(0) + Typeof(0) Infer ImplicitSelf MacCall(0) CVarArgs Pat(0 1) Dummy Err(0)); impl SpanlessEq for Ident { fn eq(&self, other: &Self) -> bool { diff --git a/pkg/installer/vendor/syn/tests/debug/gen.rs b/pkg/installer/vendor/syn/tests/debug/gen.rs index 9f726683a2a..d766a8e300d 100644 --- a/pkg/installer/vendor/syn/tests/debug/gen.rs +++ b/pkg/installer/vendor/syn/tests/debug/gen.rs @@ -314,6 +314,27 @@ impl Debug for Lite { formatter.finish() } } +impl Debug for Lite { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match &self.value { + syn::CapturedParam::Lifetime(_val) => { + formatter.write_str("CapturedParam::Lifetime")?; + formatter.write_str("(")?; + Debug::fmt(Lite(_val), formatter)?; + formatter.write_str(")")?; + Ok(()) + } + syn::CapturedParam::Ident(_val) => { + formatter.write_str("CapturedParam::Ident")?; + formatter.write_str("(")?; + Debug::fmt(Lite(_val), formatter)?; + formatter.write_str(")")?; + Ok(()) + } + _ => unreachable!(), + } + } +} impl Debug for Lite { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let mut formatter = formatter.debug_struct("ConstParam"); @@ -856,6 +877,15 @@ impl Debug for Lite { } formatter.finish() } + syn::Expr::RawAddr(_val) => { + let mut formatter = formatter.debug_struct("Expr::RawAddr"); + if !_val.attrs.is_empty() { + formatter.field("attrs", Lite(&_val.attrs)); + } + formatter.field("mutability", Lite(&_val.mutability)); + formatter.field("expr", Lite(&_val.expr)); + formatter.finish() + } syn::Expr::Reference(_val) => { let mut formatter = formatter.debug_struct("Expr::Reference"); if !_val.attrs.is_empty() { @@ -1513,6 +1543,17 @@ impl Debug for Lite { formatter.finish() } } +impl Debug for Lite { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprRawAddr"); + if !self.value.attrs.is_empty() { + formatter.field("attrs", Lite(&self.value.attrs)); + } + formatter.field("mutability", Lite(&self.value.mutability)); + formatter.field("expr", Lite(&self.value.expr)); + formatter.finish() + } +} impl Debug for Lite { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let mut formatter = formatter.debug_struct("ExprReference"); @@ -3532,6 +3573,29 @@ impl Debug for Lite { formatter.finish() } } +impl Debug for Lite { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match &self.value { + syn::PointerMutability::Const(_val) => { + formatter.write_str("PointerMutability::Const")?; + Ok(()) + } + syn::PointerMutability::Mut(_val) => { + formatter.write_str("PointerMutability::Mut")?; + Ok(()) + } + } + } +} +impl Debug for Lite { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PreciseCapture"); + if !self.value.params.is_empty() { + formatter.field("params", Lite(&self.value.params)); + } + formatter.finish() + } +} impl Debug for Lite { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let mut formatter = formatter.debug_struct("PredicateLifetime"); @@ -4354,6 +4418,13 @@ impl Debug for Lite { formatter.field("ident", Lite(&_val.ident)); formatter.finish() } + syn::TypeParamBound::PreciseCapture(_val) => { + formatter.write_str("TypeParamBound::PreciseCapture")?; + formatter.write_str("(")?; + Debug::fmt(Lite(_val), formatter)?; + formatter.write_str(")")?; + Ok(()) + } syn::TypeParamBound::Verbatim(_val) => { formatter.write_str("TypeParamBound::Verbatim")?; formatter.write_str("(`")?; @@ -5011,6 +5082,11 @@ impl Debug for Lite { formatter.write_str("Token![->]") } } +impl Debug for Lite { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("Token![raw]") + } +} impl Debug for Lite { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("Token![ref]") diff --git a/pkg/installer/vendor/syn/tests/debug/mod.rs b/pkg/installer/vendor/syn/tests/debug/mod.rs index c9925a6d5c7..7ab2b795d5d 100644 --- a/pkg/installer/vendor/syn/tests/debug/mod.rs +++ b/pkg/installer/vendor/syn/tests/debug/mod.rs @@ -82,7 +82,7 @@ impl Debug for Lite { } } -impl<'a, T> Debug for Lite<&'a T> +impl Debug for Lite<&T> where Lite: Debug, { diff --git a/pkg/installer/vendor/syn/tests/macros/mod.rs b/pkg/installer/vendor/syn/tests/macros/mod.rs index 1c1bacf4590..024075c0462 100644 --- a/pkg/installer/vendor/syn/tests/macros/mod.rs +++ b/pkg/installer/vendor/syn/tests/macros/mod.rs @@ -79,7 +79,7 @@ pub trait TryIntoTokens { fn try_into_tokens(self) -> Result; } -impl<'a> TryIntoTokens for &'a str { +impl TryIntoTokens for &str { fn try_into_tokens(self) -> Result { let tokens = proc_macro2::TokenStream::from_str(self)?; Ok(tokens) diff --git a/pkg/installer/vendor/syn/tests/repo/mod.rs b/pkg/installer/vendor/syn/tests/repo/mod.rs index 6c367c944ca..96f039cb352 100644 --- a/pkg/installer/vendor/syn/tests/repo/mod.rs +++ b/pkg/installer/vendor/syn/tests/repo/mod.rs @@ -15,23 +15,10 @@ use std::path::{Path, PathBuf}; use tar::Archive; use walkdir::{DirEntry, WalkDir}; -const REVISION: &str = "5069856495870486134dd2ca0b0e2516308c5c2a"; +const REVISION: &str = "86d69c705a552236a622eee3fdea94bf13c5f102"; #[rustfmt::skip] static EXCLUDE_FILES: &[&str] = &[ - // TODO: `unsafe static`, `safe fn` - // https://github.com/dtolnay/syn/issues/1675 - "src/tools/rustfmt/tests/target/unsafe_extern_blocks.rs", - "tests/rustdoc/unsafe-extern-blocks.rs", - "tests/ui/rust-2024/unsafe-extern-blocks/safe-items.rs", - - // TODO: unsafe attributes: `#[unsafe(path::to)]` - // https://github.com/dtolnay/syn/issues/1710 - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0213_metas.rs", - "src/tools/rustfmt/tests/target/unsafe_attributes.rs", - "tests/ui/attributes/unsafe/unsafe-attributes.rs", - "tests/ui/rust-2024/unsafe-attributes/unsafe-attribute-marked.rs", - // TODO: non-lifetime binders: `where for<'a, T> &'a Struct: Trait` // https://github.com/dtolnay/syn/issues/1435 "src/tools/rustfmt/tests/source/issue_5721.rs", @@ -42,21 +29,37 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/rustdoc/inline_cross/auxiliary/non_lifetime_binders.rs", "tests/rustdoc/non_lifetime_binders.rs", - // TODO: return type notation: `where T: Trait` + // TODO: return type notation: `where T: Trait` and `where T::method(..): Send` // https://github.com/dtolnay/syn/issues/1434 - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0208_associated_return_type_bounds.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/return_type_syntax_assoc_type_bound.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/return_type_syntax_in_path.rs", "src/tools/rustfmt/tests/target/return-type-notation.rs", "tests/ui/associated-type-bounds/return-type-notation/basic.rs", + "tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.rs", + "tests/ui/associated-type-bounds/return-type-notation/namespace-conflict.rs", + "tests/ui/associated-type-bounds/return-type-notation/path-constrained-in-method.rs", + "tests/ui/associated-type-bounds/return-type-notation/path-self-qself.rs", + "tests/ui/associated-type-bounds/return-type-notation/path-works.rs", "tests/ui/associated-type-bounds/return-type-notation/unpretty-parenthesized.rs", + "tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.rs", + "tests/ui/async-await/return-type-notation/rtn-implied-in-supertrait.rs", + "tests/ui/async-await/return-type-notation/supertrait-bound.rs", + "tests/ui/borrowck/alias-liveness/rtn-static.rs", "tests/ui/feature-gates/feature-gate-return_type_notation.rs", // TODO: lazy type alias syntax with where-clause in trailing position // https://github.com/dtolnay/syn/issues/1525 + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/type_item_where_clause.rs", + "src/tools/rustfmt/tests/source/type-alias-where-clauses-with-comments.rs", + "src/tools/rustfmt/tests/source/type-alias-where-clauses.rs", + "src/tools/rustfmt/tests/target/type-alias-where-clauses-with-comments.rs", + "src/tools/rustfmt/tests/target/type-alias-where-clauses.rs", "tests/rustdoc/typedef-inner-variants-lazy_type_alias.rs", // TODO: gen blocks and functions // https://github.com/dtolnay/syn/issues/1526 "compiler/rustc_codegen_cranelift/example/gen_block_iterate.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/gen_blocks.rs", "tests/ui/coroutine/async-gen-deduce-yield.rs", "tests/ui/coroutine/async-gen-yield-ty-is-unit.rs", "tests/ui/coroutine/async_gen_fn_iter.rs", @@ -65,9 +68,10 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/ui/coroutine/gen_block_iterate.rs", "tests/ui/coroutine/gen_fn_iter.rs", "tests/ui/coroutine/gen_fn_lifetime_capture.rs", + "tests/ui/coroutine/other-attribute-on-gen.rs", "tests/ui/coroutine/return-types-diverge.rs", "tests/ui/higher-ranked/builtin-closure-like-bounds.rs", - "tests/ui/sanitizer/cfi-coroutine.rs", + "tests/ui/sanitizer/cfi/coroutine.rs", // TODO: `!` as a pattern // https://github.com/dtolnay/syn/issues/1546 @@ -79,23 +83,30 @@ static EXCLUDE_FILES: &[&str] = &[ // https://github.com/dtolnay/syn/issues/1628 "src/tools/miri/tests/pass/async-closure-captures.rs", "src/tools/miri/tests/pass/async-closure-drop.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0211_async_trait_bound.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0212_const_trait_bound.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/async_trait_bound.rs", "src/tools/rustfmt/tests/target/asyncness.rs", "tests/codegen/async-closure-debug.rs", + "tests/coverage/async_closure.rs", "tests/ui/async-await/async-closures/async-fn-mut-for-async-fn.rs", "tests/ui/async-await/async-closures/async-fn-once-for-async-fn.rs", "tests/ui/async-await/async-closures/auxiliary/foreign.rs", + "tests/ui/async-await/async-closures/body-check-on-non-fnmut.rs", + "tests/ui/async-await/async-closures/box-deref-in-debuginfo.rs", "tests/ui/async-await/async-closures/brand.rs", "tests/ui/async-await/async-closures/captures.rs", + "tests/ui/async-await/async-closures/clone-closure.rs", "tests/ui/async-await/async-closures/constrained-but-no-upvars-yet.rs", + "tests/ui/async-await/async-closures/debuginfo-by-move-body.rs", "tests/ui/async-await/async-closures/drop.rs", "tests/ui/async-await/async-closures/force-move-due-to-inferred-kind.rs", + "tests/ui/async-await/async-closures/foreign.rs", + "tests/ui/async-await/async-closures/inline-body.rs", "tests/ui/async-await/async-closures/mangle.rs", "tests/ui/async-await/async-closures/moro-example.rs", "tests/ui/async-await/async-closures/move-is-async-fn.rs", "tests/ui/async-await/async-closures/mut-ref-reborrow.rs", "tests/ui/async-await/async-closures/no-borrow-from-env.rs", + "tests/ui/async-await/async-closures/non-copy-arg-does-not-force-inner-move.rs", "tests/ui/async-await/async-closures/overlapping-projs.rs", "tests/ui/async-await/async-closures/precise-captures.rs", "tests/ui/async-await/async-closures/refd.rs", @@ -130,6 +141,12 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/ui/delegation/explicit-paths-pass.rs", "tests/ui/delegation/explicit-paths-signature-pass.rs", "tests/ui/delegation/fn-header.rs", + "tests/ui/delegation/generics/free-fn-to-free-fn-pass.rs", + "tests/ui/delegation/generics/free-fn-to-trait-method-pass.rs", + "tests/ui/delegation/generics/impl-to-free-fn-pass.rs", + "tests/ui/delegation/generics/impl-trait-to-trait-method-pass.rs", + "tests/ui/delegation/generics/inherent-impl-to-trait-method-pass.rs", + "tests/ui/delegation/generics/trait-method-to-other-pass.rs", "tests/ui/delegation/glob-glob.rs", "tests/ui/delegation/glob-override.rs", "tests/ui/delegation/glob.rs", @@ -148,25 +165,40 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/ui/async-await/for-await-passthrough.rs", "tests/ui/async-await/for-await.rs", - // TODO: const trait bound: `T: const Trait` + // TODO: const trait bound: `T: const Trait` and `impl const Trait` and `~const Trait` // https://github.com/dtolnay/syn/issues/1632 + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/const_trait_bound.rs", "tests/ui/generic-const-items/const-trait-impl.rs", - "tests/ui/rfcs/rfc-2632-const-trait-impl/const-fns-are-early-bound.rs", - "tests/ui/rfcs/rfc-2632-const-trait-impl/const-trait-bounds.rs", - "tests/ui/rfcs/rfc-2632-const-trait-impl/effects/minicore.rs", + "tests/ui/traits/const-traits/tilde-const-syntax.rs", + + // TODO: unparenthesized half-open range pattern inside slice pattern: `[1..]` + // https://github.com/dtolnay/syn/issues/1769 + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/range_pat.rs", + "tests/ui/consts/miri_unleashed/const_refers_to_static_cross_crate.rs", + + // TODO: pinned type sugar: `&pin const Self` + // https://github.com/dtolnay/syn/issues/1770 + "src/tools/rustfmt/tests/source/pin_sugar.rs", + "src/tools/rustfmt/tests/target/pin_sugar.rs", + "tests/ui/async-await/pin-sugar.rs", // TODO: `|| .. .method()` - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0208_closure_range_method_call.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/closure_range_method_call.rs", "src/tools/rustfmt/tests/source/issue-4808.rs", // Several of the above "tests/ui/unpretty/expanded-exhaustive.rs", + // Rustc bug: https://github.com/rust-lang/rust/issues/132080 + "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0073_safe_declarations_in_extern_blocks.rs", + // Compile-fail expr parameter in const generic position: f::<1 + 2>() "tests/ui/const-generics/early/closing-args-token.rs", "tests/ui/const-generics/early/const-expression-parameter.rs", // Compile-fail variadics in not the last position of a function parameter list + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/fn_def_param.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/param_list_vararg.rs", "tests/ui/parser/variadic-ffi-syntactic-pass.rs", // Need at least one trait in impl Trait, no such type as impl 'static @@ -176,11 +208,8 @@ static EXCLUDE_FILES: &[&str] = &[ "src/tools/rustfmt/tests/target/negative-bounds.rs", "tests/ui/traits/negative-bounds/supertrait.rs", - // Lifetime bound inside for<>: `T: ~const ?for<'a: 'b> Trait<'a>` - "tests/ui/rfcs/rfc-2632-const-trait-impl/tilde-const-syntax.rs", - // Const impl that is not a trait impl: `impl ~const T {}` - "tests/ui/rfcs/rfc-2632-const-trait-impl/syntax.rs", + "tests/ui/traits/const-traits/syntax.rs", // Lifetimes and types out of order in angle bracketed path arguments "tests/ui/parser/constraints-before-generic-args-syntactic-pass.rs", @@ -202,10 +231,10 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/rustdoc/generic-associated-types/gats.rs", // Deprecated trait object syntax with parenthesized generic arguments and no dyn keyword - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0004_value_parameters_no_patterns.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0104_path_fn_trait_args.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0202_typepathfn_with_coloncolon.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0209_bare_dyn_types_with_paren_as_generic_args.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/bare_dyn_types_with_paren_as_generic_args.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/path_fn_trait_args.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/typepathfn_with_coloncolon.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/value_parameters_no_patterns.rs", "src/tools/rustfmt/tests/source/attrib.rs", "src/tools/rustfmt/tests/source/closure.rs", "src/tools/rustfmt/tests/source/existential_type.rs", @@ -238,17 +267,9 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/ui/lifetimes/bare-trait-object.rs", "tests/ui/parser/bounds-obj-parens.rs", - // Invalid unparenthesized range pattern inside slice pattern: `[1..]` - "tests/ui/consts/miri_unleashed/const_refers_to_static_cross_crate.rs", - // Various extensions to Rust syntax made up by rust-analyzer - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0012_type_item_where_clause.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0058_range_pat.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0123_param_list_vararg.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0131_existential_type.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0156_fn_def_param.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0179_use_tree_abs_star.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0188_const_param_default_path.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/const_param_default_path.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/use_tree_abs_star.rs", "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0015_use_tree.rs", "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0029_range_forms.rs", "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0051_parameter_attrs.rs", @@ -262,17 +283,16 @@ static EXCLUDE_FILES: &[&str] = &[ // Placeholder syntax for "throw expressions" "compiler/rustc_errors/src/translation.rs", "compiler/rustc_expand/src/module.rs", - "compiler/rustc_infer/src/infer/need_type_info.rs", + "compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs", "src/tools/clippy/tests/ui/needless_return.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0204_yeet_expr.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/yeet_expr.rs", "tests/pretty/yeet-expr.rs", "tests/ui/try-trait/yeet-for-option.rs", "tests/ui/try-trait/yeet-for-result.rs", // Edition 2015 code using identifiers that are now keywords // TODO: some of these we should probably parse - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0159_try_macro_fallback.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0160_try_macro_rules.rs", + "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/dyn_trait_type_weak.rs", "src/tools/rustfmt/tests/source/configs/indent_style/block_call.rs", "src/tools/rustfmt/tests/source/configs/use_try_shorthand/false.rs", "src/tools/rustfmt/tests/source/configs/use_try_shorthand/true.rs", @@ -308,15 +328,13 @@ static EXCLUDE_FILES: &[&str] = &[ "src/tools/rustfmt/tests/target/configs/spaces_around_ranges/false.rs", "src/tools/rustfmt/tests/target/configs/spaces_around_ranges/true.rs", "src/tools/rustfmt/tests/target/type.rs", + "src/tools/rustfmt/tests/target/unsafe_extern_blocks.rs", "tests/run-make/translation/test.rs", "tests/ui/generics/issue-94432-garbage-ice.rs", // Generated file containing a top-level expression, used with `include!` "compiler/rustc_codegen_gcc/src/intrinsic/archs.rs", - // Clippy lint lists represented as expressions - "src/tools/clippy/clippy_lints/src/lib.deprecated.rs", - // Not actually test cases "tests/ui/lint/expansion-time-include.rs", "tests/ui/macros/auxiliary/macro-comma-support.rs", diff --git a/pkg/installer/vendor/syn/tests/test_asyncness.rs b/pkg/installer/vendor/syn/tests/test_asyncness.rs index 9968934490d..e409bc9c368 100644 --- a/pkg/installer/vendor/syn/tests/test_asyncness.rs +++ b/pkg/installer/vendor/syn/tests/test_asyncness.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -9,7 +9,7 @@ use syn::{Expr, Item}; fn test_async_fn() { let input = "async fn process() {}"; - snapshot!(input as Item, @r###" + snapshot!(input as Item, @r#" Item::Fn { vis: Visibility::Inherited, sig: Signature { @@ -22,14 +22,14 @@ fn test_async_fn() { stmts: [], }, } - "###); + "#); } #[test] fn test_async_closure() { let input = "async || {}"; - snapshot!(input as Expr, @r###" + snapshot!(input as Expr, @r#" Expr::Closure { asyncness: Some, output: ReturnType::Default, @@ -39,5 +39,5 @@ fn test_async_closure() { }, }, } - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_attribute.rs b/pkg/installer/vendor/syn/tests/test_attribute.rs index 597ae3adc86..739b894d1a1 100644 --- a/pkg/installer/vendor/syn/tests/test_attribute.rs +++ b/pkg/installer/vendor/syn/tests/test_attribute.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -10,7 +10,7 @@ use syn::{Attribute, Meta}; fn test_meta_item_word() { let meta = test("#[foo]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::Path { segments: [ PathSegment { @@ -18,14 +18,14 @@ fn test_meta_item_word() { }, ], } - "###); + "#); } #[test] fn test_meta_item_name_value() { let meta = test("#[foo = 5]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::NameValue { path: Path { segments: [ @@ -38,14 +38,14 @@ fn test_meta_item_name_value() { lit: 5, }, } - "###); + "#); } #[test] fn test_meta_item_bool_value() { let meta = test("#[foo = true]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::NameValue { path: Path { segments: [ @@ -60,11 +60,11 @@ fn test_meta_item_bool_value() { }, }, } - "###); + "#); let meta = test("#[foo = false]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::NameValue { path: Path { segments: [ @@ -79,14 +79,14 @@ fn test_meta_item_bool_value() { }, }, } - "###); + "#); } #[test] fn test_meta_item_list_lit() { let meta = test("#[foo(5)]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::List { path: Path { segments: [ @@ -98,14 +98,14 @@ fn test_meta_item_list_lit() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`5`), } - "###); + "#); } #[test] fn test_meta_item_list_word() { let meta = test("#[foo(bar)]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::List { path: Path { segments: [ @@ -117,14 +117,14 @@ fn test_meta_item_list_word() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`bar`), } - "###); + "#); } #[test] fn test_meta_item_list_name_value() { let meta = test("#[foo(bar = 5)]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::List { path: Path { segments: [ @@ -136,14 +136,14 @@ fn test_meta_item_list_name_value() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`bar = 5`), } - "###); + "#); } #[test] fn test_meta_item_list_bool_value() { let meta = test("#[foo(bar = true)]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::List { path: Path { segments: [ @@ -155,14 +155,14 @@ fn test_meta_item_list_bool_value() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`bar = true`), } - "###); + "#); } #[test] fn test_meta_item_multiple() { let meta = test("#[foo(word, name = 5, list(name2 = 6), word2)]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::List { path: Path { segments: [ @@ -174,14 +174,14 @@ fn test_meta_item_multiple() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`word , name = 5 , list (name2 = 6) , word2`), } - "###); + "#); } #[test] fn test_bool_lit() { let meta = test("#[foo(true)]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::List { path: Path { segments: [ @@ -193,14 +193,14 @@ fn test_bool_lit() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`true`), } - "###); + "#); } #[test] fn test_negative_lit() { let meta = test("#[form(min = -1, max = 200)]"); - snapshot!(meta, @r###" + snapshot!(meta, @r#" Meta::List { path: Path { segments: [ @@ -212,7 +212,7 @@ fn test_negative_lit() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`min = - 1 , max = 200`), } - "###); + "#); } fn test(input: &str) -> Meta { diff --git a/pkg/installer/vendor/syn/tests/test_derive_input.rs b/pkg/installer/vendor/syn/tests/test_derive_input.rs index c3d31eb0e91..9cf1e11e24e 100644 --- a/pkg/installer/vendor/syn/tests/test_derive_input.rs +++ b/pkg/installer/vendor/syn/tests/test_derive_input.rs @@ -1,6 +1,7 @@ #![allow( clippy::assertions_on_result_states, clippy::manual_let_else, + clippy::needless_lifetimes, clippy::too_many_lines, clippy::uninlined_format_args )] @@ -17,7 +18,7 @@ fn test_unit() { struct Unit; }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Inherited, ident: "Unit", @@ -27,7 +28,7 @@ fn test_unit() { semi_token: Some, }, } - "###); + "#); } #[test] @@ -40,7 +41,7 @@ fn test_struct() { } }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { attrs: [ Attribute { @@ -110,9 +111,9 @@ fn test_struct() { }, }, } - "###); + "#); - snapshot!(&input.attrs[0].meta, @r###" + snapshot!(&input.attrs[0].meta, @r#" Meta::List { path: Path { segments: [ @@ -124,7 +125,7 @@ fn test_struct() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`Debug , Clone`), } - "###); + "#); } #[test] @@ -136,7 +137,7 @@ fn test_union() { } }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Inherited, ident: "MaybeUninit", @@ -177,7 +178,7 @@ fn test_union() { }, }, } - "###); + "#); } #[test] @@ -197,7 +198,7 @@ fn test_enum() { } }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { attrs: [ Attribute { @@ -314,11 +315,11 @@ fn test_enum() { ], }, } - "###); + "#); let meta_items: Vec<_> = input.attrs.into_iter().map(|attr| attr.meta).collect(); - snapshot!(meta_items, @r###" + snapshot!(meta_items, @r#" [ Meta::NameValue { path: Path { @@ -340,7 +341,7 @@ fn test_enum() { ], }, ] - "###); + "#); } #[test] @@ -360,7 +361,7 @@ fn test_attr_with_mod_style_path_with_self() { struct S; }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { attrs: [ Attribute { @@ -386,9 +387,9 @@ fn test_attr_with_mod_style_path_with_self() { semi_token: Some, }, } - "###); + "#); - snapshot!(&input.attrs[0].meta, @r###" + snapshot!(&input.attrs[0].meta, @r#" Meta::Path { segments: [ PathSegment { @@ -400,7 +401,7 @@ fn test_attr_with_mod_style_path_with_self() { }, ], } - "###); + "#); } #[test] @@ -410,7 +411,7 @@ fn test_pub_restricted() { pub(in m) struct Z(pub(in m::n) u8); }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Restricted { in_token: Some, @@ -457,7 +458,7 @@ fn test_pub_restricted() { semi_token: Some, }, } - "###); + "#); } #[test] @@ -466,7 +467,7 @@ fn test_pub_restricted_crate() { pub(crate) struct S; }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Restricted { path: Path { @@ -484,7 +485,7 @@ fn test_pub_restricted_crate() { semi_token: Some, }, } - "###); + "#); } #[test] @@ -493,7 +494,7 @@ fn test_pub_restricted_super() { pub(super) struct S; }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Restricted { path: Path { @@ -511,7 +512,7 @@ fn test_pub_restricted_super() { semi_token: Some, }, } - "###); + "#); } #[test] @@ -520,7 +521,7 @@ fn test_pub_restricted_in_super() { pub(in super) struct S; }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Restricted { in_token: Some, @@ -539,7 +540,7 @@ fn test_pub_restricted_in_super() { semi_token: Some, }, } - "###); + "#); } #[test] @@ -548,7 +549,7 @@ fn test_fields_on_unit_struct() { struct S; }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Inherited, ident: "S", @@ -558,7 +559,7 @@ fn test_fields_on_unit_struct() { semi_token: Some, }, } - "###); + "#); let data = match input.data { Data::Struct(data) => data, @@ -577,7 +578,7 @@ fn test_fields_on_named_struct() { } }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Inherited, ident: "S", @@ -619,14 +620,14 @@ fn test_fields_on_named_struct() { }, }, } - "###); + "#); let data = match input.data { Data::Struct(data) => data, _ => panic!("expected a struct"), }; - snapshot!(data.fields.into_iter().collect::>(), @r###" + snapshot!(data.fields.into_iter().collect::>(), @r#" [ Field { vis: Visibility::Inherited, @@ -657,7 +658,7 @@ fn test_fields_on_named_struct() { }, }, ] - "###); + "#); } #[test] @@ -666,7 +667,7 @@ fn test_fields_on_tuple_struct() { struct S(i32, pub String); }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Inherited, ident: "S", @@ -704,14 +705,14 @@ fn test_fields_on_tuple_struct() { semi_token: Some, }, } - "###); + "#); let data = match input.data { Data::Struct(data) => data, _ => panic!("expected a struct"), }; - snapshot!(data.fields.iter().collect::>(), @r###" + snapshot!(data.fields.iter().collect::>(), @r#" [ Field { vis: Visibility::Inherited, @@ -738,7 +739,7 @@ fn test_fields_on_tuple_struct() { }, }, ] - "###); + "#); } #[test] @@ -748,7 +749,7 @@ fn test_ambiguous_crate() { struct S(crate::X); }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Inherited, ident: "S", @@ -777,5 +778,5 @@ fn test_ambiguous_crate() { semi_token: Some, }, } - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_expr.rs b/pkg/installer/vendor/syn/tests/test_expr.rs index d20cce8d6a4..f01fcb8ce26 100644 --- a/pkg/installer/vendor/syn/tests/test_expr.rs +++ b/pkg/installer/vendor/syn/tests/test_expr.rs @@ -1,4 +1,8 @@ -#![allow(clippy::single_element_loop, clippy::uninlined_format_args)] +#![allow( + clippy::needless_lifetimes, + clippy::single_element_loop, + clippy::uninlined_format_args +)] #[macro_use] mod macros; @@ -13,24 +17,24 @@ use syn::{parse_quote, token, Expr, ExprRange, ExprTuple, Stmt, Token}; #[test] fn test_expr_parse() { let tokens = quote!(..100u32); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Range { limits: RangeLimits::HalfOpen, end: Some(Expr::Lit { lit: 100u32, }), } - "###); + "#); let tokens = quote!(..100u32); - snapshot!(tokens as ExprRange, @r###" + snapshot!(tokens as ExprRange, @r#" ExprRange { limits: RangeLimits::HalfOpen, end: Some(Expr::Lit { lit: 100u32, }), } - "###); + "#); } #[test] @@ -38,7 +42,7 @@ fn test_await() { // Must not parse as Expr::Field. let tokens = quote!(fut.await); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Await { base: Expr::Path { path: Path { @@ -50,13 +54,13 @@ fn test_await() { }, }, } - "###); + "#); } #[rustfmt::skip] #[test] fn test_tuple_multi_index() { - let expected = snapshot!("tuple.0.0" as Expr, @r###" + let expected = snapshot!("tuple.0.0" as Expr, @r#" Expr::Field { base: Expr::Field { base: Expr::Path { @@ -76,7 +80,7 @@ fn test_tuple_multi_index() { index: 0, }), } - "###); + "#); for &input in &[ "tuple .0.0", @@ -106,7 +110,7 @@ fn test_macro_variable_func() { let path = Group::new(Delimiter::None, quote!(f)); let tokens = quote!(#path()); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Call { func: Expr::Group { expr: Expr::Path { @@ -120,12 +124,12 @@ fn test_macro_variable_func() { }, }, } - "###); + "#); let path = Group::new(Delimiter::None, quote! { #[inside] f }); let tokens = quote!(#[outside] #path()); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Call { attrs: [ Attribute { @@ -163,7 +167,7 @@ fn test_macro_variable_func() { }, }, } - "###); + "#); } #[test] @@ -172,7 +176,7 @@ fn test_macro_variable_macro() { let mac = Group::new(Delimiter::None, quote!(m)); let tokens = quote!(#mac!()); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Macro { mac: Macro { path: Path { @@ -186,7 +190,7 @@ fn test_macro_variable_macro() { tokens: TokenStream(``), }, } - "###); + "#); } #[test] @@ -195,7 +199,7 @@ fn test_macro_variable_struct() { let s = Group::new(Delimiter::None, quote! { S }); let tokens = quote!(#s {}); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Struct { path: Path { segments: [ @@ -205,7 +209,7 @@ fn test_macro_variable_struct() { ], }, } - "###); + "#); } #[test] @@ -213,7 +217,7 @@ fn test_macro_variable_unary() { // mimics the token stream corresponding to `$expr.method()` where expr is `&self` let inner = Group::new(Delimiter::None, quote!(&self)); let tokens = quote!(#inner.method()); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::MethodCall { receiver: Expr::Group { expr: Expr::Reference { @@ -230,7 +234,7 @@ fn test_macro_variable_unary() { }, method: "method", } - "###); + "#); } #[test] @@ -238,7 +242,7 @@ fn test_macro_variable_match_arm() { // mimics the token stream corresponding to `match v { _ => $expr }` let expr = Group::new(Delimiter::None, quote! { #[a] () }); let tokens = quote!(match v { _ => #expr }); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Match { expr: Expr::Path { path: Path { @@ -271,11 +275,11 @@ fn test_macro_variable_match_arm() { }, ], } - "###); + "#); let expr = Group::new(Delimiter::None, quote!(loop {} + 1)); let tokens = quote!(match v { _ => #expr }); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Match { expr: Expr::Path { path: Path { @@ -305,7 +309,7 @@ fn test_macro_variable_match_arm() { }, ], } - "###); + "#); } // https://github.com/dtolnay/syn/issues/1019 @@ -313,7 +317,7 @@ fn test_macro_variable_match_arm() { fn test_closure_vs_rangefull() { #[rustfmt::skip] // rustfmt bug: https://github.com/rust-lang/rustfmt/issues/4808 let tokens = quote!(|| .. .method()); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::MethodCall { receiver: Expr::Closure { output: ReturnType::Default, @@ -323,7 +327,7 @@ fn test_closure_vs_rangefull() { }, method: "method", } - "###); + "#); } #[test] @@ -352,16 +356,16 @@ fn test_range_kinds() { #[test] fn test_range_precedence() { - snapshot!(".. .." as Expr, @r###" + snapshot!(".. .." as Expr, @r#" Expr::Range { limits: RangeLimits::HalfOpen, end: Some(Expr::Range { limits: RangeLimits::HalfOpen, }), } - "###); + "#); - snapshot!(".. .. ()" as Expr, @r###" + snapshot!(".. .. ()" as Expr, @r#" Expr::Range { limits: RangeLimits::HalfOpen, end: Some(Expr::Range { @@ -369,9 +373,9 @@ fn test_range_precedence() { end: Some(Expr::Tuple), }), } - "###); + "#); - snapshot!("() .. .." as Expr, @r###" + snapshot!("() .. .." as Expr, @r#" Expr::Range { start: Some(Expr::Tuple), limits: RangeLimits::HalfOpen, @@ -379,7 +383,7 @@ fn test_range_precedence() { limits: RangeLimits::HalfOpen, }), } - "###); + "#); // A range with a lower bound cannot be the upper bound of another range, // and a range with an upper bound cannot be the lower bound of another @@ -422,7 +426,7 @@ fn test_extended_interpolated_path() { let path = Group::new(Delimiter::None, quote!(a::b)); let tokens = quote!(if #path {}); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::If { cond: Expr::Group { expr: Expr::Path { @@ -443,10 +447,10 @@ fn test_extended_interpolated_path() { stmts: [], }, } - "###); + "#); let tokens = quote!(#path {}); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Struct { path: Path { segments: [ @@ -460,10 +464,10 @@ fn test_extended_interpolated_path() { ], }, } - "###); + "#); let tokens = quote!(#path :: c); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Path { path: Path { segments: [ @@ -481,11 +485,11 @@ fn test_extended_interpolated_path() { ], }, } - "###); + "#); let nested = Group::new(Delimiter::None, quote!(a::b || true)); let tokens = quote!(if #nested && false {}); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::If { cond: Expr::Binary { left: Expr::Group { @@ -522,7 +526,7 @@ fn test_extended_interpolated_path() { stmts: [], }, } - "###); + "#); } #[test] @@ -536,27 +540,27 @@ fn test_tuple_comma() { expr.elems.push_value(parse_quote!(continue)); // Must not parse to Expr::Paren - snapshot!(expr.to_token_stream() as Expr, @r###" + snapshot!(expr.to_token_stream() as Expr, @r#" Expr::Tuple { elems: [ Expr::Continue, Token![,], ], } - "###); + "#); expr.elems.push_punct(::default()); - snapshot!(expr.to_token_stream() as Expr, @r###" + snapshot!(expr.to_token_stream() as Expr, @r#" Expr::Tuple { elems: [ Expr::Continue, Token![,], ], } - "###); + "#); expr.elems.push_value(parse_quote!(continue)); - snapshot!(expr.to_token_stream() as Expr, @r###" + snapshot!(expr.to_token_stream() as Expr, @r#" Expr::Tuple { elems: [ Expr::Continue, @@ -564,10 +568,10 @@ fn test_tuple_comma() { Expr::Continue, ], } - "###); + "#); expr.elems.push_punct(::default()); - snapshot!(expr.to_token_stream() as Expr, @r###" + snapshot!(expr.to_token_stream() as Expr, @r#" Expr::Tuple { elems: [ Expr::Continue, @@ -576,13 +580,13 @@ fn test_tuple_comma() { Token![,], ], } - "###); + "#); } #[test] fn test_binop_associativity() { // Left to right. - snapshot!("() + () + ()" as Expr, @r###" + snapshot!("() + () + ()" as Expr, @r#" Expr::Binary { left: Expr::Binary { left: Expr::Tuple, @@ -592,10 +596,10 @@ fn test_binop_associativity() { op: BinOp::Add, right: Expr::Tuple, } - "###); + "#); // Right to left. - snapshot!("() += () += ()" as Expr, @r###" + snapshot!("() += () += ()" as Expr, @r#" Expr::Binary { left: Expr::Tuple, op: BinOp::AddAssign, @@ -605,7 +609,7 @@ fn test_binop_associativity() { right: Expr::Tuple, }, } - "###); + "#); // Parenthesization is required. syn::parse_str::("() == () == ()").unwrap_err(); @@ -615,7 +619,7 @@ fn test_binop_associativity() { fn test_assign_range_precedence() { // Range has higher precedence as the right-hand of an assignment, but // ambiguous precedence as the left-hand of an assignment. - snapshot!("() = () .. ()" as Expr, @r###" + snapshot!("() = () .. ()" as Expr, @r#" Expr::Assign { left: Expr::Tuple, right: Expr::Range { @@ -624,9 +628,9 @@ fn test_assign_range_precedence() { end: Some(Expr::Tuple), }, } - "###); + "#); - snapshot!("() += () .. ()" as Expr, @r###" + snapshot!("() += () .. ()" as Expr, @r#" Expr::Binary { left: Expr::Tuple, op: BinOp::AddAssign, @@ -636,12 +640,29 @@ fn test_assign_range_precedence() { end: Some(Expr::Tuple), }, } - "###); + "#); syn::parse_str::("() .. () = ()").unwrap_err(); syn::parse_str::("() .. () += ()").unwrap_err(); } +#[test] +fn test_chained_comparison() { + // https://github.com/dtolnay/syn/issues/1738 + let _ = syn::parse_str::("a = a < a <"); + let _ = syn::parse_str::("a = a .. a .."); + let _ = syn::parse_str::("a = a .. a +="); + + let err = syn::parse_str::("a < a < a").unwrap_err(); + assert_eq!("comparison operators cannot be chained", err.to_string()); + + let err = syn::parse_str::("a .. a .. a").unwrap_err(); + assert_eq!("unexpected token", err.to_string()); + + let err = syn::parse_str::("a .. a += a").unwrap_err(); + assert_eq!("unexpected token", err.to_string()); +} + #[test] fn test_fixup() { struct FlattenParens; diff --git a/pkg/installer/vendor/syn/tests/test_generics.rs b/pkg/installer/vendor/syn/tests/test_generics.rs index 3faf0dba59e..9f405e733b4 100644 --- a/pkg/installer/vendor/syn/tests/test_generics.rs +++ b/pkg/installer/vendor/syn/tests/test_generics.rs @@ -1,5 +1,6 @@ #![allow( clippy::manual_let_else, + clippy::needless_lifetimes, clippy::too_many_lines, clippy::uninlined_format_args )] @@ -16,7 +17,7 @@ fn test_split_for_impl() { struct S<'a, 'b: 'a, #[may_dangle] T: 'a = ()> where T: Debug; }; - snapshot!(input as DeriveInput, @r###" + snapshot!(input as DeriveInput, @r#" DeriveInput { vis: Visibility::Inherited, ident: "S", @@ -98,7 +99,7 @@ fn test_split_for_impl() { semi_token: Some, }, } - "###); + "#); let generics = input.generics; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); @@ -128,21 +129,21 @@ fn test_split_for_impl() { #[test] fn test_ty_param_bound() { let tokens = quote!('a); - snapshot!(tokens as TypeParamBound, @r###" + snapshot!(tokens as TypeParamBound, @r#" TypeParamBound::Lifetime { ident: "a", } - "###); + "#); let tokens = quote!('_); - snapshot!(tokens as TypeParamBound, @r###" + snapshot!(tokens as TypeParamBound, @r#" TypeParamBound::Lifetime { ident: "_", } - "###); + "#); let tokens = quote!(Debug); - snapshot!(tokens as TypeParamBound, @r###" + snapshot!(tokens as TypeParamBound, @r#" TypeParamBound::Trait(TraitBound { path: Path { segments: [ @@ -152,10 +153,10 @@ fn test_ty_param_bound() { ], }, }) - "###); + "#); let tokens = quote!(?Sized); - snapshot!(tokens as TypeParamBound, @r###" + snapshot!(tokens as TypeParamBound, @r#" TypeParamBound::Trait(TraitBound { modifier: TraitBoundModifier::Maybe, path: Path { @@ -166,7 +167,7 @@ fn test_ty_param_bound() { ], }, }) - "###); + "#); } #[test] @@ -181,7 +182,7 @@ fn test_fn_precedence_in_where_clause() { } }; - snapshot!(input as ItemFn, @r###" + snapshot!(input as ItemFn, @r#" ItemFn { vis: Visibility::Inherited, sig: Signature { @@ -251,7 +252,7 @@ fn test_fn_precedence_in_where_clause() { stmts: [], }, } - "###); + "#); let where_clause = input.sig.generics.where_clause.as_ref().unwrap(); assert_eq!(where_clause.predicates.len(), 1); diff --git a/pkg/installer/vendor/syn/tests/test_grouping.rs b/pkg/installer/vendor/syn/tests/test_grouping.rs index 326909feb59..9809db07115 100644 --- a/pkg/installer/vendor/syn/tests/test_grouping.rs +++ b/pkg/installer/vendor/syn/tests/test_grouping.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -25,7 +25,7 @@ fn test_grouping() { assert_eq!(tokens.to_string(), "1i32 + 2i32 + 3i32 * 4i32"); - snapshot!(tokens as Expr, @r###" + snapshot!(tokens as Expr, @r#" Expr::Binary { left: Expr::Lit { lit: 1i32, @@ -49,5 +49,5 @@ fn test_grouping() { }, }, } - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_item.rs b/pkg/installer/vendor/syn/tests/test_item.rs index 5c088bbe60f..51a5ba915ec 100644 --- a/pkg/installer/vendor/syn/tests/test_item.rs +++ b/pkg/installer/vendor/syn/tests/test_item.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -18,7 +18,7 @@ fn test_macro_variable_attr() { TokenTree::Group(Group::new(Delimiter::Brace, TokenStream::new())), ]); - snapshot!(tokens as Item, @r###" + snapshot!(tokens as Item, @r#" Item::Fn { attrs: [ Attribute { @@ -42,7 +42,7 @@ fn test_macro_variable_attr() { stmts: [], }, } - "###); + "#); } #[test] @@ -54,12 +54,12 @@ fn test_negative_impl() { let tokens = quote! { impl ! {} }; - snapshot!(tokens as Item, @r###" + snapshot!(tokens as Item, @r#" Item::Impl { generics: Generics, self_ty: Type::Never, } - "###); + "#); #[cfg(any())] #[rustfmt::skip] @@ -67,19 +67,19 @@ fn test_negative_impl() { let tokens = quote! { impl !Trait {} }; - snapshot!(tokens as Item, @r###" + snapshot!(tokens as Item, @r#" Item::Impl { generics: Generics, self_ty: Type::Verbatim(`! Trait`), } - "###); + "#); #[cfg(any())] impl !Trait for T {} let tokens = quote! { impl !Trait for T {} }; - snapshot!(tokens as Item, @r###" + snapshot!(tokens as Item, @r#" Item::Impl { generics: Generics, trait_: Some(( @@ -102,7 +102,7 @@ fn test_negative_impl() { }, }, } - "###); + "#); #[cfg(any())] #[rustfmt::skip] @@ -110,12 +110,12 @@ fn test_negative_impl() { let tokens = quote! { impl !! {} }; - snapshot!(tokens as Item, @r###" + snapshot!(tokens as Item, @r#" Item::Impl { generics: Generics, self_ty: Type::Verbatim(`! !`), } - "###); + "#); } #[test] @@ -129,7 +129,7 @@ fn test_macro_variable_impl() { TokenTree::Group(Group::new(Delimiter::Brace, TokenStream::new())), ]); - snapshot!(tokens as Item, @r###" + snapshot!(tokens as Item, @r#" Item::Impl { generics: Generics, trait_: Some(( @@ -154,7 +154,7 @@ fn test_macro_variable_impl() { }, }, } - "###); + "#); } #[test] @@ -163,7 +163,7 @@ fn test_supertraits() { #[rustfmt::skip] let tokens = quote!(trait Trait where {}); - snapshot!(tokens as ItemTrait, @r###" + snapshot!(tokens as ItemTrait, @r#" ItemTrait { vis: Visibility::Inherited, ident: "Trait", @@ -171,11 +171,11 @@ fn test_supertraits() { where_clause: Some(WhereClause), }, } - "###); + "#); #[rustfmt::skip] let tokens = quote!(trait Trait: where {}); - snapshot!(tokens as ItemTrait, @r###" + snapshot!(tokens as ItemTrait, @r#" ItemTrait { vis: Visibility::Inherited, ident: "Trait", @@ -184,11 +184,11 @@ fn test_supertraits() { }, colon_token: Some, } - "###); + "#); #[rustfmt::skip] let tokens = quote!(trait Trait: Sized where {}); - snapshot!(tokens as ItemTrait, @r###" + snapshot!(tokens as ItemTrait, @r#" ItemTrait { vis: Visibility::Inherited, ident: "Trait", @@ -208,11 +208,11 @@ fn test_supertraits() { }), ], } - "###); + "#); #[rustfmt::skip] let tokens = quote!(trait Trait: Sized + where {}); - snapshot!(tokens as ItemTrait, @r###" + snapshot!(tokens as ItemTrait, @r#" ItemTrait { vis: Visibility::Inherited, ident: "Trait", @@ -233,7 +233,7 @@ fn test_supertraits() { Token![+], ], } - "###); + "#); } #[test] @@ -245,7 +245,7 @@ fn test_type_empty_bounds() { } }; - snapshot!(tokens as ItemTrait, @r###" + snapshot!(tokens as ItemTrait, @r#" ItemTrait { vis: Visibility::Inherited, ident: "Foo", @@ -258,7 +258,7 @@ fn test_type_empty_bounds() { }, ], } - "###); + "#); } #[test] @@ -277,7 +277,7 @@ fn test_impl_type_parameter_defaults() { let tokens = quote! { impl () {} }; - snapshot!(tokens as Item, @r###" + snapshot!(tokens as Item, @r#" Item::Impl { generics: Generics { lt_token: Some, @@ -292,7 +292,7 @@ fn test_impl_type_parameter_defaults() { }, self_ty: Type::Tuple, } - "###); + "#); } #[test] @@ -301,7 +301,7 @@ fn test_impl_trait_trailing_plus() { fn f() -> impl Sized + {} }; - snapshot!(tokens as Item, @r###" + snapshot!(tokens as Item, @r#" Item::Fn { vis: Visibility::Inherited, sig: Signature { @@ -328,5 +328,5 @@ fn test_impl_trait_trailing_plus() { stmts: [], }, } - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_iterators.rs b/pkg/installer/vendor/syn/tests/test_iterators.rs index 4090bcc8e82..3f0637ceb82 100644 --- a/pkg/installer/vendor/syn/tests/test_iterators.rs +++ b/pkg/installer/vendor/syn/tests/test_iterators.rs @@ -1,4 +1,8 @@ -#![allow(clippy::map_unwrap_or, clippy::uninlined_format_args)] +#![allow( + clippy::map_unwrap_or, + clippy::needless_lifetimes, + clippy::uninlined_format_args +)] use syn::punctuated::{Pair, Punctuated}; use syn::{parse_quote, GenericParam, Generics, Lifetime, LifetimeParam, Token}; diff --git a/pkg/installer/vendor/syn/tests/test_lit.rs b/pkg/installer/vendor/syn/tests/test_lit.rs index 0d5ecdcef5b..a7194ab8e8b 100644 --- a/pkg/installer/vendor/syn/tests/test_lit.rs +++ b/pkg/installer/vendor/syn/tests/test_lit.rs @@ -1,5 +1,6 @@ #![allow( clippy::float_cmp, + clippy::needless_lifetimes, clippy::needless_raw_string_hashes, clippy::non_ascii_literal, clippy::single_match_else, diff --git a/pkg/installer/vendor/syn/tests/test_meta.rs b/pkg/installer/vendor/syn/tests/test_meta.rs index ea6093115a9..abb842be3dd 100644 --- a/pkg/installer/vendor/syn/tests/test_meta.rs +++ b/pkg/installer/vendor/syn/tests/test_meta.rs @@ -1,4 +1,5 @@ #![allow( + clippy::needless_lifetimes, clippy::shadow_unrelated, clippy::too_many_lines, clippy::uninlined_format_args @@ -13,7 +14,7 @@ use syn::{Meta, MetaList, MetaNameValue}; fn test_parse_meta_item_word() { let input = "hello"; - snapshot!(input as Meta, @r###" + snapshot!(input as Meta, @r#" Meta::Path { segments: [ PathSegment { @@ -21,7 +22,7 @@ fn test_parse_meta_item_word() { }, ], } - "###); + "#); } #[test] @@ -29,7 +30,7 @@ fn test_parse_meta_name_value() { let input = "foo = 5"; let (inner, meta) = (input, input); - snapshot!(inner as MetaNameValue, @r###" + snapshot!(inner as MetaNameValue, @r#" MetaNameValue { path: Path { segments: [ @@ -42,9 +43,9 @@ fn test_parse_meta_name_value() { lit: 5, }, } - "###); + "#); - snapshot!(meta as Meta, @r###" + snapshot!(meta as Meta, @r#" Meta::NameValue { path: Path { segments: [ @@ -57,7 +58,7 @@ fn test_parse_meta_name_value() { lit: 5, }, } - "###); + "#); assert_eq!(meta, Meta::NameValue(inner)); } @@ -67,7 +68,7 @@ fn test_parse_meta_item_list_lit() { let input = "foo(5)"; let (inner, meta) = (input, input); - snapshot!(inner as MetaList, @r###" + snapshot!(inner as MetaList, @r#" MetaList { path: Path { segments: [ @@ -79,9 +80,9 @@ fn test_parse_meta_item_list_lit() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`5`), } - "###); + "#); - snapshot!(meta as Meta, @r###" + snapshot!(meta as Meta, @r#" Meta::List { path: Path { segments: [ @@ -93,7 +94,7 @@ fn test_parse_meta_item_list_lit() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`5`), } - "###); + "#); assert_eq!(meta, Meta::List(inner)); } @@ -103,7 +104,7 @@ fn test_parse_meta_item_multiple() { let input = "foo(word, name = 5, list(name2 = 6), word2)"; let (inner, meta) = (input, input); - snapshot!(inner as MetaList, @r###" + snapshot!(inner as MetaList, @r#" MetaList { path: Path { segments: [ @@ -115,9 +116,9 @@ fn test_parse_meta_item_multiple() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`word , name = 5 , list (name2 = 6) , word2`), } - "###); + "#); - snapshot!(meta as Meta, @r###" + snapshot!(meta as Meta, @r#" Meta::List { path: Path { segments: [ @@ -129,7 +130,7 @@ fn test_parse_meta_item_multiple() { delimiter: MacroDelimiter::Paren, tokens: TokenStream(`word , name = 5 , list (name2 = 6) , word2`), } - "###); + "#); assert_eq!(meta, Meta::List(inner)); } @@ -137,7 +138,7 @@ fn test_parse_meta_item_multiple() { #[test] fn test_parse_path() { let input = "::serde::Serialize"; - snapshot!(input as Meta, @r###" + snapshot!(input as Meta, @r#" Meta::Path { leading_colon: Some, segments: [ @@ -150,5 +151,5 @@ fn test_parse_path() { }, ], } - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_parse_quote.rs b/pkg/installer/vendor/syn/tests/test_parse_quote.rs index c0e753260a1..c3a9004a124 100644 --- a/pkg/installer/vendor/syn/tests/test_parse_quote.rs +++ b/pkg/installer/vendor/syn/tests/test_parse_quote.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -9,7 +9,7 @@ use syn::{parse_quote, Attribute, Field, Lit, Pat, Stmt, Token}; #[test] fn test_attribute() { let attr: Attribute = parse_quote!(#[test]); - snapshot!(attr, @r###" + snapshot!(attr, @r#" Attribute { style: AttrStyle::Outer, meta: Meta::Path { @@ -20,10 +20,10 @@ fn test_attribute() { ], }, } - "###); + "#); let attr: Attribute = parse_quote!(#![no_std]); - snapshot!(attr, @r###" + snapshot!(attr, @r#" Attribute { style: AttrStyle::Inner, meta: Meta::Path { @@ -34,13 +34,13 @@ fn test_attribute() { ], }, } - "###); + "#); } #[test] fn test_field() { let field: Field = parse_quote!(pub enabled: bool); - snapshot!(field, @r###" + snapshot!(field, @r#" Field { vis: Visibility::Public, ident: Some("enabled"), @@ -55,10 +55,10 @@ fn test_field() { }, }, } - "###); + "#); let field: Field = parse_quote!(primitive::bool); - snapshot!(field, @r###" + snapshot!(field, @r#" Field { vis: Visibility::Inherited, ty: Type::Path { @@ -75,13 +75,13 @@ fn test_field() { }, }, } - "###); + "#); } #[test] fn test_pat() { let pat: Pat = parse_quote!(Some(false) | None); - snapshot!(&pat, @r###" + snapshot!(&pat, @r#" Pat::Or { cases: [ Pat::TupleStruct { @@ -106,7 +106,7 @@ fn test_pat() { }, ], } - "###); + "#); let boxed_pat: Box = parse_quote!(Some(false) | None); assert_eq!(*boxed_pat, pat); @@ -115,7 +115,7 @@ fn test_pat() { #[test] fn test_punctuated() { let punctuated: Punctuated = parse_quote!(true | true); - snapshot!(punctuated, @r###" + snapshot!(punctuated, @r#" [ Lit::Bool { value: true, @@ -125,10 +125,10 @@ fn test_punctuated() { value: true, }, ] - "###); + "#); let punctuated: Punctuated = parse_quote!(true | true |); - snapshot!(punctuated, @r###" + snapshot!(punctuated, @r#" [ Lit::Bool { value: true, @@ -139,7 +139,7 @@ fn test_punctuated() { }, Token![|], ] - "###); + "#); } #[test] @@ -148,7 +148,7 @@ fn test_vec_stmt() { let _; true }; - snapshot!(stmts, @r###" + snapshot!(stmts, @r#" [ Stmt::Local { pat: Pat::Wild, @@ -162,5 +162,5 @@ fn test_vec_stmt() { None, ), ] - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_pat.rs b/pkg/installer/vendor/syn/tests/test_pat.rs index 3d13385fd97..eabba407be2 100644 --- a/pkg/installer/vendor/syn/tests/test_pat.rs +++ b/pkg/installer/vendor/syn/tests/test_pat.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -51,7 +51,7 @@ fn test_group() { let tokens = TokenStream::from_iter([TokenTree::Group(group)]); let pat = Pat::parse_single.parse2(tokens).unwrap(); - snapshot!(pat, @r###" + snapshot!(pat, @r#" Pat::TupleStruct { path: Path { segments: [ @@ -64,7 +64,7 @@ fn test_group() { Pat::Wild, ], } - "###); + "#); } #[test] @@ -108,27 +108,27 @@ fn test_tuple_comma() { expr.elems.push_value(parse_quote!(_)); // Must not parse to Pat::Paren - snapshot!(expr.to_token_stream() as Pat, @r###" + snapshot!(expr.to_token_stream() as Pat, @r#" Pat::Tuple { elems: [ Pat::Wild, Token![,], ], } - "###); + "#); expr.elems.push_punct(::default()); - snapshot!(expr.to_token_stream() as Pat, @r###" + snapshot!(expr.to_token_stream() as Pat, @r#" Pat::Tuple { elems: [ Pat::Wild, Token![,], ], } - "###); + "#); expr.elems.push_value(parse_quote!(_)); - snapshot!(expr.to_token_stream() as Pat, @r###" + snapshot!(expr.to_token_stream() as Pat, @r#" Pat::Tuple { elems: [ Pat::Wild, @@ -136,10 +136,10 @@ fn test_tuple_comma() { Pat::Wild, ], } - "###); + "#); expr.elems.push_punct(::default()); - snapshot!(expr.to_token_stream() as Pat, @r###" + snapshot!(expr.to_token_stream() as Pat, @r#" Pat::Tuple { elems: [ Pat::Wild, @@ -148,5 +148,5 @@ fn test_tuple_comma() { Token![,], ], } - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_path.rs b/pkg/installer/vendor/syn/tests/test_path.rs index 628b9f853ac..bdb2749ff96 100644 --- a/pkg/installer/vendor/syn/tests/test_path.rs +++ b/pkg/installer/vendor/syn/tests/test_path.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -17,7 +17,7 @@ fn parse_interpolated_leading_component() { TokenTree::Ident(Ident::new("rest", Span::call_site())), ]); - snapshot!(tokens.clone() as Expr, @r###" + snapshot!(tokens.clone() as Expr, @r#" Expr::Path { path: Path { segments: [ @@ -31,9 +31,9 @@ fn parse_interpolated_leading_component() { ], }, } - "###); + "#); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::Path { path: Path { segments: [ @@ -47,58 +47,38 @@ fn parse_interpolated_leading_component() { ], }, } - "###); + "#); } #[test] fn print_incomplete_qpath() { // qpath with `as` token let mut ty: TypePath = parse_quote!(::Q); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(`< Self as A > :: Q`) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(`< Self as A > :: Q`)"); assert!(ty.path.segments.pop().is_some()); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(`< Self as A > ::`) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(`< Self as A > ::`)"); assert!(ty.path.segments.pop().is_some()); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(`< Self >`) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(`< Self >`)"); assert!(ty.path.segments.pop().is_none()); // qpath without `as` token let mut ty: TypePath = parse_quote!(::A::B); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(`< Self > :: A :: B`) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(`< Self > :: A :: B`)"); assert!(ty.path.segments.pop().is_some()); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(`< Self > :: A ::`) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(`< Self > :: A ::`)"); assert!(ty.path.segments.pop().is_some()); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(`< Self > ::`) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(`< Self > ::`)"); assert!(ty.path.segments.pop().is_none()); // normal path let mut ty: TypePath = parse_quote!(Self::A::B); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(`Self :: A :: B`) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(`Self :: A :: B`)"); assert!(ty.path.segments.pop().is_some()); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(`Self :: A ::`) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(`Self :: A ::`)"); assert!(ty.path.segments.pop().is_some()); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(`Self ::`) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(`Self ::`)"); assert!(ty.path.segments.pop().is_some()); - snapshot!(ty.to_token_stream(), @r###" - TokenStream(``) - "###); + snapshot!(ty.to_token_stream(), @"TokenStream(``)"); assert!(ty.path.segments.pop().is_none()); } @@ -106,7 +86,7 @@ fn print_incomplete_qpath() { fn parse_parenthesized_path_arguments_with_disambiguator() { #[rustfmt::skip] let tokens = quote!(dyn FnOnce::() -> !); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::TraitObject { dyn_token: Some, bounds: [ @@ -126,5 +106,5 @@ fn parse_parenthesized_path_arguments_with_disambiguator() { }), ], } - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_precedence.rs b/pkg/installer/vendor/syn/tests/test_precedence.rs index bee0c759e36..1fa64b32050 100644 --- a/pkg/installer/vendor/syn/tests/test_precedence.rs +++ b/pkg/installer/vendor/syn/tests/test_precedence.rs @@ -25,6 +25,7 @@ clippy::manual_let_else, clippy::match_like_matches_macro, clippy::match_wildcard_for_single_variants, + clippy::needless_lifetimes, clippy::too_many_lines, clippy::uninlined_format_args )] @@ -48,6 +49,7 @@ use std::fs; use std::path::Path; use std::process; use std::sync::atomic::{AtomicUsize, Ordering}; +use syn::parse::Parser as _; #[macro_use] mod macros; @@ -55,6 +57,9 @@ mod macros; mod common; mod repo; +#[path = "../src/scan_expr.rs"] +mod scan_expr; + #[test] fn test_rustc_precedence() { repo::rayon_init(); @@ -114,7 +119,8 @@ fn test_expressions(path: &Path, edition: Edition, exprs: Vec) -> (us rustc_span::create_session_if_not_set_then(edition, |_| { for expr in exprs { - let source_code = expr.to_token_stream().to_string(); + let expr_tokens = expr.to_token_stream(); + let source_code = expr_tokens.to_string(); let librustc_ast = if let Some(e) = librustc_parse_and_rewrite(&source_code) { e } else { @@ -172,6 +178,16 @@ fn test_expressions(path: &Path, edition: Edition, exprs: Vec) -> (us continue; } + if scan_expr::scan_expr.parse2(expr_tokens).is_err() { + failed += 1; + errorf!( + "\nFAIL {} - failed to scan expr\n{}\n", + path.display(), + source_code, + ); + continue; + } + passed += 1; } }); @@ -185,8 +201,8 @@ fn librustc_parse_and_rewrite(input: &str) -> Option> { fn librustc_parenthesize(mut librustc_expr: P) -> P { use rustc_ast::ast::{ - AssocItem, AssocItemKind, Attribute, BinOpKind, Block, BorrowKind, BoundConstness, Expr, - ExprField, ExprKind, GenericArg, GenericBound, Local, LocalKind, Pat, Stmt, StmtKind, + AssocItem, AssocItemKind, Attribute, BinOpKind, Block, BoundConstness, Expr, ExprField, + ExprKind, GenericArg, GenericBound, Local, LocalKind, Pat, PolyTraitRef, Stmt, StmtKind, StructExpr, StructRest, TraitBoundModifiers, Ty, }; use rustc_ast::mut_visit::{walk_flat_map_item, MutVisitor}; @@ -239,7 +255,7 @@ fn librustc_parenthesize(mut librustc_expr: P) -> P { fn noop_visit_expr(e: &mut Expr, vis: &mut T) { match &mut e.kind { - ExprKind::AddrOf(BorrowKind::Raw, ..) | ExprKind::Become(..) => {} + ExprKind::Become(..) => {} ExprKind::Struct(expr) => { let StructExpr { qself, @@ -295,16 +311,17 @@ fn librustc_parenthesize(mut librustc_expr: P) -> P { fn visit_param_bound(&mut self, bound: &mut GenericBound, _ctxt: BoundKind) { match bound { - GenericBound::Trait( - _, - TraitBoundModifiers { - constness: BoundConstness::Maybe(_), - .. - }, - ) + GenericBound::Trait(PolyTraitRef { + modifiers: + TraitBoundModifiers { + constness: BoundConstness::Maybe(_), + .. + }, + .. + }) | GenericBound::Outlives(..) | GenericBound::Use(..) => {} - GenericBound::Trait(ty, _modifier) => self.visit_poly_trait_ref(ty), + GenericBound::Trait(ty) => self.visit_poly_trait_ref(ty), } } diff --git a/pkg/installer/vendor/syn/tests/test_receiver.rs b/pkg/installer/vendor/syn/tests/test_receiver.rs index 8decb555c50..c4a63176f15 100644 --- a/pkg/installer/vendor/syn/tests/test_receiver.rs +++ b/pkg/installer/vendor/syn/tests/test_receiver.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -10,7 +10,7 @@ fn test_by_value() { let TraitItemFn { sig, .. } = parse_quote! { fn by_value(self: Self); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { colon_token: Some, ty: Type::Path { @@ -23,7 +23,7 @@ fn test_by_value() { }, }, }) - "###); + "#); } #[test] @@ -31,7 +31,7 @@ fn test_by_mut_value() { let TraitItemFn { sig, .. } = parse_quote! { fn by_mut(mut self: Self); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { mutability: Some, colon_token: Some, @@ -45,7 +45,7 @@ fn test_by_mut_value() { }, }, }) - "###); + "#); } #[test] @@ -53,7 +53,7 @@ fn test_by_ref() { let TraitItemFn { sig, .. } = parse_quote! { fn by_ref(self: &Self); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { colon_token: Some, ty: Type::Reference { @@ -68,7 +68,7 @@ fn test_by_ref() { }, }, }) - "###); + "#); } #[test] @@ -76,7 +76,7 @@ fn test_by_box() { let TraitItemFn { sig, .. } = parse_quote! { fn by_box(self: Box); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { colon_token: Some, ty: Type::Path { @@ -102,7 +102,7 @@ fn test_by_box() { }, }, }) - "###); + "#); } #[test] @@ -110,7 +110,7 @@ fn test_by_pin() { let TraitItemFn { sig, .. } = parse_quote! { fn by_pin(self: Pin); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { colon_token: Some, ty: Type::Path { @@ -136,7 +136,7 @@ fn test_by_pin() { }, }, }) - "###); + "#); } #[test] @@ -144,7 +144,7 @@ fn test_explicit_type() { let TraitItemFn { sig, .. } = parse_quote! { fn explicit_type(self: Pin); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { colon_token: Some, ty: Type::Path { @@ -170,7 +170,7 @@ fn test_explicit_type() { }, }, }) - "###); + "#); } #[test] @@ -178,7 +178,7 @@ fn test_value_shorthand() { let TraitItemFn { sig, .. } = parse_quote! { fn value_shorthand(self); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { ty: Type::Path { path: Path { @@ -190,7 +190,7 @@ fn test_value_shorthand() { }, }, }) - "###); + "#); } #[test] @@ -198,7 +198,7 @@ fn test_mut_value_shorthand() { let TraitItemFn { sig, .. } = parse_quote! { fn mut_value_shorthand(mut self); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { mutability: Some, ty: Type::Path { @@ -211,7 +211,7 @@ fn test_mut_value_shorthand() { }, }, }) - "###); + "#); } #[test] @@ -219,7 +219,7 @@ fn test_ref_shorthand() { let TraitItemFn { sig, .. } = parse_quote! { fn ref_shorthand(&self); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { reference: Some(None), ty: Type::Reference { @@ -234,7 +234,7 @@ fn test_ref_shorthand() { }, }, }) - "###); + "#); } #[test] @@ -242,7 +242,7 @@ fn test_ref_shorthand_with_lifetime() { let TraitItemFn { sig, .. } = parse_quote! { fn ref_shorthand(&'a self); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { reference: Some(Some(Lifetime { ident: "a", @@ -262,7 +262,7 @@ fn test_ref_shorthand_with_lifetime() { }, }, }) - "###); + "#); } #[test] @@ -270,7 +270,7 @@ fn test_ref_mut_shorthand() { let TraitItemFn { sig, .. } = parse_quote! { fn ref_mut_shorthand(&mut self); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { reference: Some(None), mutability: Some, @@ -287,7 +287,7 @@ fn test_ref_mut_shorthand() { }, }, }) - "###); + "#); } #[test] @@ -295,7 +295,7 @@ fn test_ref_mut_shorthand_with_lifetime() { let TraitItemFn { sig, .. } = parse_quote! { fn ref_mut_shorthand(&'a mut self); }; - snapshot!(&sig.inputs[0], @r###" + snapshot!(&sig.inputs[0], @r#" FnArg::Receiver(Receiver { reference: Some(Some(Lifetime { ident: "a", @@ -317,5 +317,5 @@ fn test_ref_mut_shorthand_with_lifetime() { }, }, }) - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_round_trip.rs b/pkg/installer/vendor/syn/tests/test_round_trip.rs index 9d459d9e1f5..197552f8016 100644 --- a/pkg/installer/vendor/syn/tests/test_round_trip.rs +++ b/pkg/installer/vendor/syn/tests/test_round_trip.rs @@ -7,6 +7,7 @@ clippy::manual_assert, clippy::manual_let_else, clippy::match_like_matches_macro, + clippy::needless_lifetimes, clippy::uninlined_format_args )] diff --git a/pkg/installer/vendor/syn/tests/test_shebang.rs b/pkg/installer/vendor/syn/tests/test_shebang.rs index 843916180f8..994ab1c44e4 100644 --- a/pkg/installer/vendor/syn/tests/test_shebang.rs +++ b/pkg/installer/vendor/syn/tests/test_shebang.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -7,7 +7,7 @@ mod macros; fn test_basic() { let content = "#!/usr/bin/env rustx\nfn main() {}"; let file = syn::parse_file(content).unwrap(); - snapshot!(file, @r###" + snapshot!(file, @r##" File { shebang: Some("#!/usr/bin/env rustx"), items: [ @@ -24,14 +24,14 @@ fn test_basic() { }, ], } - "###); + "##); } #[test] fn test_comment() { let content = "#!//am/i/a/comment\n[allow(dead_code)] fn main() {}"; let file = syn::parse_file(content).unwrap(); - snapshot!(file, @r###" + snapshot!(file, @r#" File { attrs: [ Attribute { @@ -63,5 +63,5 @@ fn test_comment() { }, ], } - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_stmt.rs b/pkg/installer/vendor/syn/tests/test_stmt.rs index 318e18b069f..b2a49b0532a 100644 --- a/pkg/installer/vendor/syn/tests/test_stmt.rs +++ b/pkg/installer/vendor/syn/tests/test_stmt.rs @@ -1,5 +1,6 @@ #![allow( clippy::assertions_on_result_states, + clippy::needless_lifetimes, clippy::non_ascii_literal, clippy::uninlined_format_args )] @@ -16,21 +17,32 @@ use syn::{Block, Stmt}; fn test_raw_operator() { let stmt = syn::parse_str::("let _ = &raw const x;").unwrap(); - snapshot!(stmt, @r###" + snapshot!(stmt, @r#" Stmt::Local { pat: Pat::Wild, init: Some(LocalInit { - expr: Expr::Verbatim(`& raw const x`), + expr: Expr::RawAddr { + mutability: PointerMutability::Const, + expr: Expr::Path { + path: Path { + segments: [ + PathSegment { + ident: "x", + }, + ], + }, + }, + }, }), } - "###); + "#); } #[test] fn test_raw_variable() { let stmt = syn::parse_str::("let _ = &raw;").unwrap(); - snapshot!(stmt, @r###" + snapshot!(stmt, @r#" Stmt::Local { pat: Pat::Wild, init: Some(LocalInit { @@ -47,7 +59,7 @@ fn test_raw_variable() { }, }), } - "###); + "#); } #[test] @@ -68,7 +80,7 @@ fn test_none_group() { TokenTree::Group(Group::new(Delimiter::Brace, TokenStream::new())), ]), ))]); - snapshot!(tokens as Stmt, @r###" + snapshot!(tokens as Stmt, @r#" Stmt::Item(Item::Fn { vis: Visibility::Inherited, sig: Signature { @@ -81,11 +93,11 @@ fn test_none_group() { stmts: [], }, }) - "###); + "#); let tokens = Group::new(Delimiter::None, quote!(let None = None)).to_token_stream(); let stmts = Block::parse_within.parse2(tokens).unwrap(); - snapshot!(stmts, @r###" + snapshot!(stmts, @r#" [ Stmt::Expr( Expr::Group { @@ -107,7 +119,7 @@ fn test_none_group() { None, ), ] - "###); + "#); } #[test] @@ -116,7 +128,7 @@ fn test_let_dot_dot() { let .. = 10; }; - snapshot!(tokens as Stmt, @r###" + snapshot!(tokens as Stmt, @r#" Stmt::Local { pat: Pat::Rest, init: Some(LocalInit { @@ -125,7 +137,7 @@ fn test_let_dot_dot() { }, }), } - "###); + "#); } #[test] @@ -134,7 +146,7 @@ fn test_let_else() { let Some(x) = None else { return 0; }; }; - snapshot!(tokens as Stmt, @r###" + snapshot!(tokens as Stmt, @r#" Stmt::Local { pat: Pat::TupleStruct { path: Path { @@ -176,7 +188,7 @@ fn test_let_else() { }), }), } - "###); + "#); } #[test] @@ -190,7 +202,7 @@ fn test_macros() { } }; - snapshot!(tokens as Stmt, @r###" + snapshot!(tokens as Stmt, @r#" Stmt::Item(Item::Fn { vis: Visibility::Inherited, sig: Signature { @@ -260,7 +272,7 @@ fn test_macros() { ], }, }) - "###); + "#); } #[test] @@ -274,7 +286,7 @@ fn test_early_parse_loop() { let stmts = Block::parse_within.parse2(tokens).unwrap(); - snapshot!(stmts, @r###" + snapshot!(stmts, @r#" [ Stmt::Expr( Expr::Loop { @@ -289,7 +301,7 @@ fn test_early_parse_loop() { None, ), ] - "###); + "#); let tokens = quote! { 'a: loop {} @@ -298,7 +310,7 @@ fn test_early_parse_loop() { let stmts = Block::parse_within.parse2(tokens).unwrap(); - snapshot!(stmts, @r###" + snapshot!(stmts, @r#" [ Stmt::Expr( Expr::Loop { @@ -318,5 +330,5 @@ fn test_early_parse_loop() { None, ), ] - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_token_trees.rs b/pkg/installer/vendor/syn/tests/test_token_trees.rs index f5a067fd238..9bd73b165e5 100644 --- a/pkg/installer/vendor/syn/tests/test_token_trees.rs +++ b/pkg/installer/vendor/syn/tests/test_token_trees.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -17,11 +17,11 @@ fn test_struct() { } "; - snapshot!(input as TokenStream, @r###" + snapshot!(input as TokenStream, @r##" TokenStream( `# [derive (Debug , Clone)] pub struct Item { pub ident : Ident , pub attrs : Vec < Attribute >, }`, ) - "###); + "##); } #[test] diff --git a/pkg/installer/vendor/syn/tests/test_ty.rs b/pkg/installer/vendor/syn/tests/test_ty.rs index d85479de45c..ea55d9456a8 100644 --- a/pkg/installer/vendor/syn/tests/test_ty.rs +++ b/pkg/installer/vendor/syn/tests/test_ty.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -28,7 +28,7 @@ fn test_macro_variable_type() { TokenTree::Punct(Punct::new('>', Spacing::Alone)), ]); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::Path { path: Path { segments: [ @@ -51,7 +51,7 @@ fn test_macro_variable_type() { ], }, } - "###); + "#); // mimics the token stream corresponding to `$ty::` let tokens = TokenStream::from_iter([ @@ -63,7 +63,7 @@ fn test_macro_variable_type() { TokenTree::Punct(Punct::new('>', Spacing::Alone)), ]); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::Path { path: Path { segments: [ @@ -87,7 +87,7 @@ fn test_macro_variable_type() { ], }, } - "###); + "#); } #[test] @@ -100,7 +100,7 @@ fn test_group_angle_brackets() { TokenTree::Punct(Punct::new('>', Spacing::Alone)), ]); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::Path { path: Path { segments: [ @@ -138,7 +138,7 @@ fn test_group_angle_brackets() { ], }, } - "###); + "#); } #[test] @@ -151,7 +151,7 @@ fn test_group_colons() { TokenTree::Ident(Ident::new("Item", Span::call_site())), ]); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::Path { path: Path { segments: [ @@ -178,7 +178,7 @@ fn test_group_colons() { ], }, } - "###); + "#); let tokens = TokenStream::from_iter([ TokenTree::Group(Group::new(Delimiter::None, quote! { [T] })), @@ -187,7 +187,7 @@ fn test_group_colons() { TokenTree::Ident(Ident::new("Element", Span::call_site())), ]); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::Path { qself: Some(QSelf { ty: Type::Slice { @@ -212,13 +212,13 @@ fn test_group_colons() { ], }, } - "###); + "#); } #[test] fn test_trait_object() { let tokens = quote!(dyn for<'a> Trait<'a> + 'static); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::TraitObject { dyn_token: Some, bounds: [ @@ -253,10 +253,10 @@ fn test_trait_object() { }, ], } - "###); + "#); let tokens = quote!(dyn 'a + Trait); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::TraitObject { dyn_token: Some, bounds: [ @@ -275,7 +275,7 @@ fn test_trait_object() { }), ], } - "###); + "#); // None of the following are valid Rust types. syn::parse_str::("for<'a> dyn Trait<'a>").unwrap_err(); @@ -286,7 +286,7 @@ fn test_trait_object() { fn test_trailing_plus() { #[rustfmt::skip] let tokens = quote!(impl Trait +); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::ImplTrait { bounds: [ TypeParamBound::Trait(TraitBound { @@ -301,11 +301,11 @@ fn test_trailing_plus() { Token![+], ], } - "###); + "#); #[rustfmt::skip] let tokens = quote!(dyn Trait +); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::TraitObject { dyn_token: Some, bounds: [ @@ -321,11 +321,11 @@ fn test_trailing_plus() { Token![+], ], } - "###); + "#); #[rustfmt::skip] let tokens = quote!(Trait +); - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::TraitObject { bounds: [ TypeParamBound::Trait(TraitBound { @@ -340,7 +340,7 @@ fn test_trailing_plus() { Token![+], ], } - "###); + "#); } #[test] @@ -353,27 +353,27 @@ fn test_tuple_comma() { expr.elems.push_value(parse_quote!(_)); // Must not parse to Type::Paren - snapshot!(expr.to_token_stream() as Type, @r###" + snapshot!(expr.to_token_stream() as Type, @r#" Type::Tuple { elems: [ Type::Infer, Token![,], ], } - "###); + "#); expr.elems.push_punct(::default()); - snapshot!(expr.to_token_stream() as Type, @r###" + snapshot!(expr.to_token_stream() as Type, @r#" Type::Tuple { elems: [ Type::Infer, Token![,], ], } - "###); + "#); expr.elems.push_value(parse_quote!(_)); - snapshot!(expr.to_token_stream() as Type, @r###" + snapshot!(expr.to_token_stream() as Type, @r#" Type::Tuple { elems: [ Type::Infer, @@ -381,10 +381,10 @@ fn test_tuple_comma() { Type::Infer, ], } - "###); + "#); expr.elems.push_punct(::default()); - snapshot!(expr.to_token_stream() as Type, @r###" + snapshot!(expr.to_token_stream() as Type, @r#" Type::Tuple { elems: [ Type::Infer, @@ -393,7 +393,7 @@ fn test_tuple_comma() { Token![,], ], } - "###); + "#); } #[test] @@ -402,7 +402,7 @@ fn test_impl_trait_use() { impl Sized + use<'_, 'a, A, Test> }; - snapshot!(tokens as Type, @r###" + snapshot!(tokens as Type, @r#" Type::ImplTrait { bounds: [ TypeParamBound::Trait(TraitBound { @@ -415,16 +415,30 @@ fn test_impl_trait_use() { }, }), Token![+], - TypeParamBound::Verbatim(`use < '_ , 'a , A , Test >`), + TypeParamBound::PreciseCapture(PreciseCapture { + params: [ + CapturedParam::Lifetime(Lifetime { + ident: "_", + }), + Token![,], + CapturedParam::Lifetime(Lifetime { + ident: "a", + }), + Token![,], + CapturedParam::Ident("A"), + Token![,], + CapturedParam::Ident("Test"), + ], + }), ], } - "###); + "#); let trailing = quote! { impl Sized + use<'_,> }; - snapshot!(trailing as Type, @r###" + snapshot!(trailing as Type, @r#" Type::ImplTrait { bounds: [ TypeParamBound::Trait(TraitBound { @@ -437,8 +451,15 @@ fn test_impl_trait_use() { }, }), Token![+], - TypeParamBound::Verbatim(`use < '_ , >`), + TypeParamBound::PreciseCapture(PreciseCapture { + params: [ + CapturedParam::Lifetime(Lifetime { + ident: "_", + }), + Token![,], + ], + }), ], } - "###); + "#); } diff --git a/pkg/installer/vendor/syn/tests/test_unparenthesize.rs b/pkg/installer/vendor/syn/tests/test_unparenthesize.rs index 69166aca20c..5db2e57a527 100644 --- a/pkg/installer/vendor/syn/tests/test_unparenthesize.rs +++ b/pkg/installer/vendor/syn/tests/test_unparenthesize.rs @@ -1,5 +1,9 @@ #![cfg(not(miri))] -#![allow(clippy::manual_assert, clippy::uninlined_format_args)] +#![allow( + clippy::manual_assert, + clippy::needless_lifetimes, + clippy::uninlined_format_args +)] use quote::ToTokens as _; use std::fs; diff --git a/pkg/installer/vendor/syn/tests/test_visibility.rs b/pkg/installer/vendor/syn/tests/test_visibility.rs index e6e8bd7291b..6c065d0c56b 100644 --- a/pkg/installer/vendor/syn/tests/test_visibility.rs +++ b/pkg/installer/vendor/syn/tests/test_visibility.rs @@ -1,4 +1,4 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] #[macro_use] mod macros; @@ -117,7 +117,7 @@ fn test_inherited_vis_named_field() { )), ]); - snapshot!(tokens as DeriveInput, @r###" + snapshot!(tokens as DeriveInput, @r#" DeriveInput { vis: Visibility::Inherited, ident: "S", @@ -135,7 +135,7 @@ fn test_inherited_vis_named_field() { }, }, } - "###); + "#); } #[test] @@ -154,7 +154,7 @@ fn test_inherited_vis_unnamed_field() { TokenTree::Punct(Punct::new(';', Spacing::Alone)), ]); - snapshot!(tokens as DeriveInput, @r###" + snapshot!(tokens as DeriveInput, @r#" DeriveInput { vis: Visibility::Inherited, ident: "S", @@ -181,5 +181,5 @@ fn test_inherited_vis_unnamed_field() { semi_token: Some, }, } - "###); + "#); } diff --git a/pkg/installer/vendor/time-core/.cargo-checksum.json b/pkg/installer/vendor/time-core/.cargo-checksum.json index 322fa934705..f7cb92e448a 100644 --- a/pkg/installer/vendor/time-core/.cargo-checksum.json +++ b/pkg/installer/vendor/time-core/.cargo-checksum.json @@ -1 +1 @@ -{"files":{".cargo_vcs_info.json":"3913a1ae7bda6098b9c4e9d1780ab806ea84a2006424d076916624f347de6bb8","Cargo.toml":"d90c41d20f37fc3dbc3d88f7715cacafb5aea973030f498e9b2833decdbe63f0","Cargo.toml.orig":"aac965a67b3c14fc6e2331fc3d3c6c14e3bd5386395a870b96e4ae7d1a05b6a2","LICENSE-Apache":"b8929fea28678da67251fb2daf9438f67503814211051861612441806d8edb05","LICENSE-MIT":"04620bf27e4a643dd47bf27652320c205acdb776c1f9f24bb8c3bfaba10804c5","src/convert.rs":"354a1b05e8bb1e92eda5dcdecf33dc6cf2ce72b11115ae4cb0909dcd51d2b294","src/lib.rs":"461b752a45b0f819284e8d8e6b2f49d52b3b661026ab84ee64bf04f4daa0a2d2","src/util.rs":"52c1fbf68b71c3582caf0d9a8255378c6c14a737e2df8d7e6d6603b0eb12ca06"},"package":"ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"} \ No newline at end of file +{"files":{".cargo_vcs_info.json":"bc86ab685208263ac6369904fd8748b688cbd59c45c4270ed62bf71faa899160","Cargo.lock":"4c5d778cc2810e8cd1847c50f91e025b935159ee6ddb82172784c2fbb1cfff08","Cargo.toml":"d3aa5f1f016bda5ae46593324dfd730ed0fdf1f0ed137b4be38f55d98530389e","Cargo.toml.orig":"f4a9d0a9ff738e8938baf1ad379cce1f46b34ce255547ec2ca8464e2855917f2","LICENSE-Apache":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"2537228d9a1b44a5dc595241349cae7090b326c8de165aaf89bfddef4a00d0fc","src/convert.rs":"be8ba4d8da4220daabf3bad647f8c745cc496883bed38fea821b7dc0b08c8a94","src/hint.rs":"3ab785980313b8c7593a6f06f0a09e0c32863e602b56faeba35b198042f21619","src/lib.rs":"3c727b5ea68b6992751cad27282921055cec1dfa700bb0f885d25a25c118247e","src/util.rs":"d8aea82023758a2d81c01ed28c08274cc56b3444ff95510af5d67b0cba54c171"},"package":"7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"} \ No newline at end of file diff --git a/pkg/installer/vendor/time-core/.cargo_vcs_info.json b/pkg/installer/vendor/time-core/.cargo_vcs_info.json index 283f88de9e3..809c7c30259 100644 --- a/pkg/installer/vendor/time-core/.cargo_vcs_info.json +++ b/pkg/installer/vendor/time-core/.cargo_vcs_info.json @@ -1,6 +1,6 @@ { "git": { - "sha1": "c96bb1a4474b9af1289edbdf34514fbfe95fa833" + "sha1": "14da652cc731cbe86afbc5b99442f3a0cd747e60" }, "path_in_vcs": "time-core" } \ No newline at end of file diff --git a/pkg/installer/vendor/time-core/Cargo.lock b/pkg/installer/vendor/time-core/Cargo.lock new file mode 100644 index 00000000000..a77866f353e --- /dev/null +++ b/pkg/installer/vendor/time-core/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "time-core" +version = "0.1.8" diff --git a/pkg/installer/vendor/time-core/Cargo.toml b/pkg/installer/vendor/time-core/Cargo.toml index 3d6555ebd5f..e637c604d75 100644 --- a/pkg/installer/vendor/time-core/Cargo.toml +++ b/pkg/installer/vendor/time-core/Cargo.toml @@ -10,15 +10,22 @@ # See Cargo.toml.orig for the original contents. [package] -edition = "2021" -rust-version = "1.67.0" +edition = "2024" +rust-version = "1.88.0" name = "time-core" -version = "0.1.2" +version = "0.1.8" authors = [ "Jacob Pratt ", "Time contributors", ] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false description = "This crate is an implementation detail and should not be relied upon directly." +readme = false keywords = [ "date", "time", @@ -30,6 +37,123 @@ license = "MIT OR Apache-2.0" repository = "https://github.com/time-rs/time" [package.metadata.docs.rs] +all-features = true +targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] -[dependencies] +[features] +large-dates = [] + +[lib] +name = "time_core" +path = "src/lib.rs" + +[lints.clippy] +alloc-instead-of-core = "deny" +as-underscore = "warn" +dbg-macro = "warn" +decimal-literal-representation = "warn" +explicit-auto-deref = "warn" +get-unwrap = "warn" +manual-let-else = "warn" +missing-docs-in-private-items = "warn" +missing-enforced-import-renames = "warn" +obfuscated-if-else = "warn" +print-stdout = "warn" +semicolon-outside-block = "warn" +std-instead-of-core = "deny" +todo = "warn" +undocumented-unsafe-blocks = "deny" +unimplemented = "warn" +uninlined-format-args = "warn" +unnested-or-patterns = "warn" +unwrap-in-result = "warn" +unwrap-used = "warn" +use-debug = "warn" + +[lints.clippy.all] +level = "warn" +priority = -1 + +[lints.clippy.incompatible-msrv] +level = "allow" +priority = 1 + +[lints.clippy.nursery] +level = "warn" +priority = -1 + +[lints.clippy.option-if-let-else] +level = "allow" +priority = 1 + +[lints.clippy.redundant-pub-crate] +level = "allow" +priority = 1 + +[lints.clippy.uninhabited-references] +level = "allow" +priority = 1 + +[lints.rust] +ambiguous-glob-reexports = "deny" +clashing-extern-declarations = "deny" +const-item-mutation = "deny" +dangling-pointers-from-temporaries = "deny" +deref-nullptr = "deny" +drop-bounds = "deny" +future-incompatible = "deny" +hidden-glob-reexports = "deny" +improper-ctypes = "deny" +improper-ctypes-definitions = "deny" +invalid-from-utf8 = "deny" +invalid-macro-export-arguments = "deny" +invalid-nan-comparisons = "deny" +invalid-reference-casting = "deny" +invalid-value = "deny" +keyword-idents = "warn" +let-underscore = "warn" +macro-use-extern-crate = "warn" +meta-variable-misuse = "warn" +missing-abi = "warn" +missing-copy-implementations = "warn" +missing-debug-implementations = "warn" +missing-docs = "warn" +named-arguments-used-positionally = "deny" +non-ascii-idents = "deny" +noop-method-call = "warn" +opaque-hidden-inferred-bound = "deny" +overlapping-range-endpoints = "deny" +single-use-lifetimes = "warn" +suspicious-double-ref-op = "deny" +trivial-casts = "warn" +trivial-numeric-casts = "warn" +unconditional-recursion = "deny" +unnameable-test-items = "deny" +unreachable-pub = "warn" +unsafe-op-in-unsafe-fn = "deny" +unstable-syntax-pre-expansion = "deny" +unused-import-braces = "warn" +unused-lifetimes = "warn" +unused-qualifications = "warn" +variant-size-differences = "warn" + +[lints.rust.unexpected_cfgs] +level = "deny" +priority = 0 +check-cfg = [ + "cfg(__ui_tests)", + "cfg(bench)", +] + +[lints.rust.unstable-name-collisions] +level = "allow" +priority = 1 + +[lints.rust.unused] +level = "warn" +priority = -1 + +[lints.rustdoc] +private-doc-tests = "warn" +unescaped-backticks = "warn" diff --git a/pkg/installer/vendor/time-core/Cargo.toml.orig b/pkg/installer/vendor/time-core/Cargo.toml.orig index c1159717781..ec4c60ecc69 100644 --- a/pkg/installer/vendor/time-core/Cargo.toml.orig +++ b/pkg/installer/vendor/time-core/Cargo.toml.orig @@ -1,19 +1,22 @@ +lints.workspace = true + [package] name = "time-core" -version = "0.1.2" -authors = ["Jacob Pratt ", "Time contributors"] -edition = "2021" -rust-version = "1.67.0" -repository = "https://github.com/time-rs/time" -keywords = ["date", "time", "calendar", "duration"] +version = "0.1.8" categories = ["date-and-time"] -license = "MIT OR Apache-2.0" description = "This crate is an implementation detail and should not be relied upon directly." +authors.workspace = true +edition.workspace = true +keywords.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + [package.metadata.docs.rs] +all-features = true +targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] -[lints] -workspace = true - -[dependencies] +[features] +large-dates = [] diff --git a/pkg/installer/vendor/time-core/LICENSE-Apache b/pkg/installer/vendor/time-core/LICENSE-Apache index 7646f21e37e..f433b1a53f5 100644 --- a/pkg/installer/vendor/time-core/LICENSE-Apache +++ b/pkg/installer/vendor/time-core/LICENSE-Apache @@ -175,28 +175,3 @@ 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 2022 Jacob Pratt et al. - - 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. diff --git a/pkg/installer/vendor/time-core/LICENSE-MIT b/pkg/installer/vendor/time-core/LICENSE-MIT index a11a755732c..663cb2a10f8 100644 --- a/pkg/installer/vendor/time-core/LICENSE-MIT +++ b/pkg/installer/vendor/time-core/LICENSE-MIT @@ -1,4 +1,4 @@ -Copyright (c) 2022 Jacob Pratt et al. +Copyright (c) Jacob Pratt et al. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/pkg/installer/vendor/time-core/src/convert.rs b/pkg/installer/vendor/time-core/src/convert.rs index 9c28f026386..c5fe82289c5 100644 --- a/pkg/installer/vendor/time-core/src/convert.rs +++ b/pkg/installer/vendor/time-core/src/convert.rs @@ -1,25 +1,57 @@ //! Conversion between units of time. -use self::sealed::Per; +use self::sealed::{DefaultOutput, MultipleOf}; mod sealed { /// A trait for defining the ratio of two units of time. /// /// This trait is used to implement the `per` method on the various structs. - pub trait Per { - /// The smallest unsigned integer type that can represent [`VALUE`](Self::VALUE). - type Output; - + #[diagnostic::on_unimplemented(message = "`{Self}` is not an integer multiple of `{T}`")] + pub trait MultipleOf { /// The number of one unit of time in the other. - const VALUE: Self::Output; + const VALUE: Output; + } + + /// A trait for defining the default output type for the `per` method. + pub trait DefaultOutput { + /// The default output type for the `per` method. + type Output; } } +/// Given the list of types, stringify them as a list. +macro_rules! stringify_outputs { + (@inner $first:ty) => { + concat!("or `", stringify!($first), "`") + }; + (@inner $first:ty, $($t:ty),+) => { + concat!(stringify_outputs!($first), ", ", stringify_outputs!(@inner $($t),+)) + }; + ($first:ty) => { + concat!("`", stringify!($first), "`") + }; + ($($t:ty),+) => { + stringify_outputs!(@inner $($t),+) + }; +} + +// Split this out to a separate function to permit naming `T` while also using `impl Trait` as a +// parameter in the public API.` +const fn multiple_of_value(_: T) -> Output +where + T: MultipleOf + Copy, +{ + T::VALUE +} + /// Declare and implement `Per` for all relevant types. Identity implementations are automatic. macro_rules! impl_per { ($($t:ident ($str:literal) per {$( - $larger:ident : $output:ty = $value:expr - )*})*) => {$( + $larger:ident : [$default_output:ty] + + $($int_output:ty)|+ = $int_value:expr; + $($float_output:ty)|+ = $float_value:expr; + )+})*) => {$( #[doc = concat!("A unit of time representing exactly one ", $str, ".")] #[derive(Debug, Clone, Copy)] pub struct $t; @@ -32,73 +64,102 @@ macro_rules! impl_per { /// /// Valid calls: /// - #[doc = concat!(" - `", stringify!($t), "::per(", stringify!($t), ")` (returns `u8`)")] - $(#[doc = concat!(" - `", stringify!($t), "::per(", stringify!($larger), ")` (returns `", stringify!($output), "`)")])* - pub const fn per(_larger: T) -> >::Output + $(#[doc = concat!( + " - `", stringify!($t), "::per(", stringify!($larger), ")` (returns `", + stringify!($default_output), "`)" + )])+ + #[inline] + pub const fn per(_larger: T) -> >::Output where - Self: Per, - T: Copy, + T: MultipleOf + DefaultOutput + Copy, { - Self::VALUE + T::VALUE } - } - impl Per<$t> for $t { - type Output = u8; - - const VALUE: u8 = 1; + #[doc = concat!("Obtain the number of times `", stringify!($t), "` can fit into `T`.")] + #[doc = concat!("If `T` is smaller than `", stringify!($t), "`, the code will fail to")] + /// compile. The return type is any primitive numeric type that can represent the value. + /// + /// Valid calls: + /// + $(#[doc = concat!( + " - `", stringify!($t), "::per(", stringify!($larger), ")` (returns ", + stringify_outputs!($($int_output),+ , $($float_output),+), ")" + )])+ + #[inline] + pub const fn per_t(larger: impl MultipleOf + Copy) -> Output { + multiple_of_value(larger) + } } - $(impl Per<$larger> for $t { - type Output = $output; + $( + $(impl MultipleOf<$t, $int_output> for $larger { + const VALUE: $int_output = $int_value; + })+ + + $(impl MultipleOf<$t, $float_output> for $larger { + const VALUE: $float_output = $float_value; + })+ - const VALUE: $output = $value; - })* + impl DefaultOutput<$t> for $larger { + type Output = $default_output; + } + )+ )*}; } impl_per! { Nanosecond ("nanosecond") per { - Microsecond: u16 = 1_000 - Millisecond: u32 = 1_000_000 - Second: u32 = 1_000_000_000 - Minute: u64 = 60_000_000_000 - Hour: u64 = 3_600_000_000_000 - Day: u64 = 86_400_000_000_000 - Week: u64 = 604_800_000_000_000 + Nanosecond: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.; + Microsecond: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 1_000; f32|f64 = 1_000.; + Millisecond: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 1_000_000; f32|f64 = 1_000_000.; + Second: + [u32] u32|u64|u128|usize|i32|i64|i128|isize = 1_000_000_000; f32|f64 = 1_000_000_000.; + Minute: [u64] u64|u128|i64|i128 = 60_000_000_000; f32|f64 = 60_000_000_000.; + Hour: [u64] u64|u128|i64|i128 = 3_600_000_000_000; f32|f64 = 3_600_000_000_000.; + Day: [u64] u64|u128|i64|i128 = 86_400_000_000_000; f32|f64 = 86_400_000_000_000.; + Week: [u64] u64|u128|i64|i128 = 604_800_000_000_000; f32|f64 = 604_800_000_000_000.; } Microsecond ("microsecond") per { - Millisecond: u16 = 1_000 - Second: u32 = 1_000_000 - Minute: u32 = 60_000_000 - Hour: u32 = 3_600_000_000 - Day: u64 = 86_400_000_000 - Week: u64 = 604_800_000_000 + Microsecond: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.; + Millisecond: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 1_000; f32|f64 = 1_000.; + Second: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 1_000_000; f32|f64 = 1_000_000.; + Minute: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 60_000_000; f32|f64 = 60_000_000.; + Hour: [u32] u32|u64|u128|i64|i128 = 3_600_000_000; f32|f64 = 3_600_000_000.; + Day: [u64] u64|u128|i64|i128 = 86_400_000_000; f32|f64 = 86_400_000_000.; + Week: [u64] u64|u128|i64|i128 = 604_800_000_000; f32|f64 = 604_800_000_000.; } Millisecond ("millisecond") per { - Second: u16 = 1_000 - Minute: u16 = 60_000 - Hour: u32 = 3_600_000 - Day: u32 = 86_400_000 - Week: u32 = 604_800_000 + Millisecond: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.; + Second: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 1_000; f32|f64 = 1_000.; + Minute: [u16] u16|u32|u64|u128|usize|i32|i64|i128|isize = 60_000; f32|f64 = 60_000.; + Hour: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 3_600_000; f32|f64 = 3_600_000.; + Day: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 86_400_000; f32|f64 = 86_400_000.; + Week: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 604_800_000; f32|f64 = 604_800_000.; } Second ("second") per { - Minute: u8 = 60 - Hour: u16 = 3_600 - Day: u32 = 86_400 - Week: u32 = 604_800 + Second: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.; + Minute: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 60; f32|f64 = 60.; + Hour: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 3_600; f32|f64 = 3_600.; + Day: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 86_400; f32|f64 = 86_400.; + Week: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 604_800; f32|f64 = 604_800.; } Minute ("minute") per { - Hour: u8 = 60 - Day: u16 = 1_440 - Week: u16 = 10_080 + Minute: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.; + Hour: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 60; f32|f64 = 60.; + Day: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 1_440; f32|f64 = 1_440.; + Week: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 10_080; f32|f64 = 10_080.; } Hour ("hour") per { - Day: u8 = 24 - Week: u8 = 168 + Hour: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.; + Day: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 24; f32|f64 = 24.; + Week: [u8] u8|u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 168; f32|f64 = 168.; } Day ("day") per { - Week: u8 = 7 + Day: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.; + Week: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 7; f32|f64 = 7.; + } + Week ("week") per { + Week: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.; } - Week ("week") per {} } diff --git a/pkg/installer/vendor/time-core/src/hint.rs b/pkg/installer/vendor/time-core/src/hint.rs new file mode 100644 index 00000000000..c291de93716 --- /dev/null +++ b/pkg/installer/vendor/time-core/src/hint.rs @@ -0,0 +1,29 @@ +//! Hints to the compiler that affects how code should be emitted or optimized. + +#![expect( + dead_code, + reason = "may be used in the future and has minimal overhead" +)] + +/// Indicate that a given branch is **not** likely to be taken, relatively speaking. +#[inline(always)] +#[cold] +pub(crate) const fn cold_path() {} + +/// Indicate that a given condition is likely to be true. +#[inline(always)] +pub(crate) const fn likely(b: bool) -> bool { + if !b { + cold_path(); + } + b +} + +/// Indicate that a given condition is likely to be false. +#[inline(always)] +pub(crate) const fn unlikely(b: bool) -> bool { + if b { + cold_path(); + } + b +} diff --git a/pkg/installer/vendor/time-core/src/lib.rs b/pkg/installer/vendor/time-core/src/lib.rs index 41c3547869a..3f4008420a8 100644 --- a/pkg/installer/vendor/time-core/src/lib.rs +++ b/pkg/installer/vendor/time-core/src/lib.rs @@ -8,4 +8,5 @@ #![doc(test(attr(deny(warnings))))] pub mod convert; +mod hint; pub mod util; diff --git a/pkg/installer/vendor/time-core/src/util.rs b/pkg/installer/vendor/time-core/src/util.rs index 26ced0638c8..b446b3f2e76 100644 --- a/pkg/installer/vendor/time-core/src/util.rs +++ b/pkg/installer/vendor/time-core/src/util.rs @@ -1,5 +1,71 @@ //! Utility functions. +use crate::hint; + +/// Versions of functions that are optimized for when the year has already been range-validated. +/// +/// The implementations of these functions depend on whether the `large-dates` feature is enabled. +/// +/// Note: This module is not exposed by the `time` crate. It is an implementation detail. +pub mod range_validated { + /// Returns if the provided year is a leap year in the proleptic Gregorian calendar, assuming + /// the year has already been range-validated. + /// + /// Behavior is unspecified for years outside the valid range. + /// + /// Note: This function is not exposed by the `time` crate. It is an implementation detail. + #[inline] + #[track_caller] + pub const fn is_leap_year(year: i32) -> bool { + #[cfg(feature = "large-dates")] + { + super::is_leap_year(year) + } + #[cfg(not(feature = "large-dates"))] + { + debug_assert!(year >= -9999); + debug_assert!(year <= 9999); + year.unsigned_abs().wrapping_mul(0x20003D7) & 0x6007C0F <= 0x7C00 + } + } + + /// Get the number of calendar days in a given year, assuming the year has already been + /// range-validated. + /// + /// Behavior is unspecified for years outside the valid range. + /// + /// Note: This function is not exposed by the `time` crate. It is an implementation detail. + #[inline] + #[track_caller] + pub const fn days_in_year(year: i32) -> u16 { + #[cfg(feature = "large-dates")] + { + super::days_in_year(year) + } + #[cfg(not(feature = "large-dates"))] + { + if is_leap_year(year) { 366 } else { 365 } + } + } + + /// Get the number of days in the month of a given year, assuming the year has already been + /// range-validated. + /// + /// Note: This function is not exposed by the `time` crate. It is an implementation detail. + #[inline] + #[track_caller] + pub const fn days_in_month(month: u8, year: i32) -> u8 { + #[cfg(feature = "large-dates")] + { + super::days_in_month(month, year) + } + #[cfg(not(feature = "large-dates"))] + { + super::days_in_month_leap(month, is_leap_year(year)) + } + } +} + /// Returns if the provided year is a leap year in the proleptic Gregorian calendar. Uses /// [astronomical year numbering](https://en.wikipedia.org/wiki/Astronomical_year_numbering). /// @@ -11,8 +77,14 @@ /// assert!(!is_leap_year(2005)); /// assert!(!is_leap_year(2100)); /// ``` +// https://hueffner.de/falk/blog/a-leap-year-check-in-three-instructions.html +#[inline] pub const fn is_leap_year(year: i32) -> bool { - year % 4 == 0 && (year % 25 != 0 || year % 16 == 0) + (year as i64) + .unsigned_abs() + .wrapping_mul(0x4000_0000_28F5_C28F) + & 0xC000_000F_8000_000F + <= 0xF_8000_0000 } /// Get the number of calendar days in a given year. @@ -27,6 +99,7 @@ pub const fn is_leap_year(year: i32) -> bool { /// assert_eq!(days_in_year(2005), 365); /// assert_eq!(days_in_year(2100), 365); /// ``` +#[inline] pub const fn days_in_year(year: i32) -> u16 { if is_leap_year(year) { 366 } else { 365 } } @@ -40,13 +113,51 @@ pub const fn days_in_year(year: i32) -> u16 { /// assert_eq!(weeks_in_year(2019), 52); /// assert_eq!(weeks_in_year(2020), 53); /// ``` +#[inline] pub const fn weeks_in_year(year: i32) -> u8 { - match year.rem_euclid(400) { - 4 | 9 | 15 | 20 | 26 | 32 | 37 | 43 | 48 | 54 | 60 | 65 | 71 | 76 | 82 | 88 | 93 | 99 - | 105 | 111 | 116 | 122 | 128 | 133 | 139 | 144 | 150 | 156 | 161 | 167 | 172 | 178 - | 184 | 189 | 195 | 201 | 207 | 212 | 218 | 224 | 229 | 235 | 240 | 246 | 252 | 257 - | 263 | 268 | 274 | 280 | 285 | 291 | 296 | 303 | 308 | 314 | 320 | 325 | 331 | 336 - | 342 | 348 | 353 | 359 | 364 | 370 | 376 | 381 | 387 | 392 | 398 => 53, + match year % 400 { + -396 | -391 | -385 | -380 | -374 | -368 | -363 | -357 | -352 | -346 | -340 | -335 + | -329 | -324 | -318 | -312 | -307 | -301 | -295 | -289 | -284 | -278 | -272 | -267 + | -261 | -256 | -250 | -244 | -239 | -233 | -228 | -222 | -216 | -211 | -205 | -199 + | -193 | -188 | -182 | -176 | -171 | -165 | -160 | -154 | -148 | -143 | -137 | -132 + | -126 | -120 | -115 | -109 | -104 | -97 | -92 | -86 | -80 | -75 | -69 | -64 | -58 + | -52 | -47 | -41 | -36 | -30 | -24 | -19 | -13 | -8 | -2 | 4 | 9 | 15 | 20 | 26 | 32 + | 37 | 43 | 48 | 54 | 60 | 65 | 71 | 76 | 82 | 88 | 93 | 99 | 105 | 111 | 116 | 122 + | 128 | 133 | 139 | 144 | 150 | 156 | 161 | 167 | 172 | 178 | 184 | 189 | 195 | 201 + | 207 | 212 | 218 | 224 | 229 | 235 | 240 | 246 | 252 | 257 | 263 | 268 | 274 | 280 + | 285 | 291 | 296 | 303 | 308 | 314 | 320 | 325 | 331 | 336 | 342 | 348 | 353 | 359 + | 364 | 370 | 376 | 381 | 387 | 392 | 398 => 53, _ => 52, } } + +/// Get the number of days in the month of a given year. +/// +/// ```rust +/// # use time_core::util::days_in_month; +/// assert_eq!(days_in_month(2, 2020), 29); +/// ``` +/// +/// Note: This function is not exposed by the `time` crate. It is an implementation detail. +#[inline] +#[track_caller] +pub const fn days_in_month(month: u8, year: i32) -> u8 { + days_in_month_leap(month, is_leap_year(year)) +} + +/// Get the number of days in the month. The year does not need to be known, but whether the +/// year is a leap year does. +/// +/// Note: This function is not exposed by the `time` crate. It is an implementation detail. +#[inline] +#[track_caller] +pub const fn days_in_month_leap(month: u8, is_leap_year: bool) -> u8 { + debug_assert!(month >= 1); + debug_assert!(month <= 12); + + if hint::unlikely(month == 2) { + if is_leap_year { 29 } else { 28 } + } else { + 30 | month ^ (month >> 3) + } +} diff --git a/pkg/installer/vendor/time-macros/.cargo-checksum.json b/pkg/installer/vendor/time-macros/.cargo-checksum.json index 6ced1cd12bb..e74cda19e0b 100644 --- a/pkg/installer/vendor/time-macros/.cargo-checksum.json +++ b/pkg/installer/vendor/time-macros/.cargo-checksum.json @@ -1 +1 @@ -{"files":{".cargo_vcs_info.json":"7b101f3b67ebede561762f33e75c5a2bdae90228fde9d544b3043e77f191a5d2","Cargo.toml":"3330436e81a4de8b20b9a2931f9e857b7974a8423462d928b04cff55ad531cff","Cargo.toml.orig":"4b8d27def522a5c1e28a829da41b0cfe3aa7206bdb9116b5cc854f5cb7a6cb81","LICENSE-Apache":"edd65bdd88957a205c47d53fa499eed8865a70320f0f03f6391668cb304ea376","LICENSE-MIT":"231c837c45eb53f108fb48929e488965bc4fcc14e9ea21d35f50e6b99d98685b","src/date.rs":"be197c8a2ed37e8b3123a798a91697b0e61cf9b60e7b1898a0e1b458fe8e3ef1","src/datetime.rs":"5c7f6e07dc2f0dcfcd86216664df53bc008dbc86f346df57a9ff57f52fe43bc6","src/error.rs":"b3dea92631092068dd73e57e1cbf548f7ae85762826dcdea7fd6454bf357a50a","src/format_description/ast.rs":"697d5ce506b5386092d706bfe5bf4f81f50e1130796cb17c2fc61457fb165307","src/format_description/format_item.rs":"02d12976209c7af83c2aa4a3221a1a65420fae8c8ba12a28933fb738a2872ff9","src/format_description/lexer.rs":"e2c75f3dda5773a0c8301fdfc0d58a0b833923ba59ac04bcc49fd10aee20496c","src/format_description/mod.rs":"2109b77a8198769c6a6732a54233d7e0058bf4a6da724824103d107859795956","src/format_description/public/component.rs":"5d86912e247724957f7183d70745ced20a7408ed90c24bb47da73a0e26550899","src/format_description/public/mod.rs":"8030e767cb94d559dda2dddc72d42654a756362bd165e5c2cccf112f15d49610","src/format_description/public/modifier.rs":"e1d8fdababcaee2e181a7acb3a938baf309f5a0e2d3877585cf678fcc12f212a","src/helpers/mod.rs":"af47d6c053ffd1113788c5d7591d46fa7d879dc0c5cb2c6c02f9c05462499c4f","src/helpers/string.rs":"3af2d0c701ca978c705922a272e76506dbdf0f376d44ed9ae7283086c67852ba","src/lib.rs":"6ed2d4a41d15a1b5d9fef7d437a1520d967acbfbab98a88630062340f701ca54","src/offset.rs":"aed29d0da9fc65a7dc77314e0346dfdc6fdaf663f17adf9edf00933e8f8e605f","src/quote.rs":"d3003dafa3073825f188851a974846099681cc81145070affb033469cbc7bb31","src/serde_format_description.rs":"db5fb2dc94e01c5114cab3484e68334516d53c4642f31dae0d66f1183253a17c","src/time.rs":"299ddb54e44fb88e514592db5335f06352ebdd0dbf064752790657db85f4c13c","src/to_tokens.rs":"afb067f4d95d19c1b7a650cbcf60ae155b5a9619c89825867997f39ce163ac94"},"package":"3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf"} \ No newline at end of file +{"files":{".cargo_vcs_info.json":"4215d5ade0cabc411673f90370cd6a05bfc1710df7045db8121d9e8e243aec79","Cargo.lock":"47ca936da11798fb9de360893bcf1f6541d00139563071568a96d762761654d1","Cargo.toml":"56c605e811dc713730e5f97147d7c7420dcf8241e4b55dcf1fb0a646b4b93176","Cargo.toml.orig":"5a4c9b7e0554ce79e34c2d4efbad7b5cc66a2852ffd5cac38d02267d7f310e24","LICENSE-Apache":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"2537228d9a1b44a5dc595241349cae7090b326c8de165aaf89bfddef4a00d0fc","src/date.rs":"7ea88a25e4c29336f95c53cac77f615d68c76306d219ebb756e4c6d02a5336cb","src/datetime.rs":"9dc0337c8fee40a73b8177e3c7699b9ef939bf8a1eaa098ce022ee25922ece50","src/error.rs":"b3dea92631092068dd73e57e1cbf548f7ae85762826dcdea7fd6454bf357a50a","src/format_description/ast.rs":"f63d50910a463286b0dd6941f61bfe92aea923792051f4f054cc2c62b1612b26","src/format_description/format_item.rs":"a4ca512473d79634e4bd378fa84694fe07a7f30ab9728d90592f87bb38c2d3f6","src/format_description/lexer.rs":"04e9b3901783a99487a34d87f2a1be47ce9a1cfec495b904311de634e372b870","src/format_description/mod.rs":"e11732992ec0eb841679cdfba5e32a9a770447e4b0b4cdd36d3a81dfc9aa7251","src/format_description/public/component.rs":"38eb4330b31296f89d5e9e9ae39defcf8b6e5f8fabcffca45f82859da8441cd9","src/format_description/public/mod.rs":"e8cc43dabdff9dce9189e9fd183e1667d6a67b2eff19fe66b84cb180363bb5af","src/format_description/public/modifier.rs":"60dc8af20e2b984819168533a32d8cc8399e2667405b1619e33ee91c21ba8cf6","src/helpers/mod.rs":"6e068cdfac7dd5481c01a46a0dd45e3eeafcf7b74696a842b3af435bfcc64fed","src/helpers/string.rs":"3af2d0c701ca978c705922a272e76506dbdf0f376d44ed9ae7283086c67852ba","src/lib.rs":"19e13440995d2a5c6bf237e719eeb3b0c8db691ba7d13e0d86ab132fa9bc0cc6","src/offset.rs":"1836560aa9c6e58c9c5583211578ddad6570bdf82cda3d2c3a64944041fd2714","src/quote.rs":"eada69cac078f3efa81bef04fda75935e8a09f1cef7c707cf161f4db75400771","src/serde_format_description.rs":"f640a2c6ae0798412c15beec96f0e232c36bd2fcad331ea75ef2a63284591cc9","src/time.rs":"6f6b5211c33768b710d78fb1b052e46ab1df1f6a310fdc16642202cf05b2b284","src/to_tokens.rs":"360105efdc7a7744da8411e4fb7a3fd8b85bab429ebd06e3c29b9f0e3f6381da","src/utc_datetime.rs":"266d0e8675cf4cd57f262df6db45409640a95b539c325eb564ebecc362517d35"},"package":"2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"} \ No newline at end of file diff --git a/pkg/installer/vendor/time-macros/.cargo_vcs_info.json b/pkg/installer/vendor/time-macros/.cargo_vcs_info.json index d26c6f4ea36..5a1655e577b 100644 --- a/pkg/installer/vendor/time-macros/.cargo_vcs_info.json +++ b/pkg/installer/vendor/time-macros/.cargo_vcs_info.json @@ -1,6 +1,6 @@ { "git": { - "sha1": "131049ea15d9a445fee306f87707d6751637f9fd" + "sha1": "d5144cd2874862d46466c900910cd8577d066019" }, "path_in_vcs": "time-macros" } \ No newline at end of file diff --git a/pkg/installer/vendor/time-macros/Cargo.lock b/pkg/installer/vendor/time-macros/Cargo.lock new file mode 100644 index 00000000000..9f9e040eb38 --- /dev/null +++ b/pkg/installer/vendor/time-macros/Cargo.lock @@ -0,0 +1,23 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "num-conv" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050" + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +dependencies = [ + "num-conv", + "time-core", +] diff --git a/pkg/installer/vendor/time-macros/Cargo.toml b/pkg/installer/vendor/time-macros/Cargo.toml index b8176221545..992808989b4 100644 --- a/pkg/installer/vendor/time-macros/Cargo.toml +++ b/pkg/installer/vendor/time-macros/Cargo.toml @@ -10,18 +10,25 @@ # See Cargo.toml.orig for the original contents. [package] -edition = "2021" -rust-version = "1.67.0" +edition = "2024" +rust-version = "1.88.0" name = "time-macros" -version = "0.2.18" +version = "0.2.27" authors = [ "Jacob Pratt ", "Time contributors", ] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false description = """ Procedural macros for the time crate. This crate is an implementation detail and should not be relied upon directly. """ +readme = false keywords = [ "date", "time", @@ -33,26 +40,30 @@ license = "MIT OR Apache-2.0" repository = "https://github.com/time-rs/time" [package.metadata.docs.rs] +all-features = true +targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] +[features] +formatting = [] +large-dates = [] +parsing = [] +serde = [] + [lib] +name = "time_macros" +path = "src/lib.rs" proc-macro = true [dependencies.num-conv] -version = "0.1.0" +version = "0.2.0" [dependencies.time-core] -version = "=0.1.2" - -[features] -formatting = [] -large-dates = [] -parsing = [] -serde = [] +version = "=0.1.8" [lints.clippy] -all = "warn" alloc-instead-of-core = "deny" +as-underscore = "warn" dbg-macro = "warn" decimal-literal-representation = "warn" explicit-auto-deref = "warn" @@ -60,7 +71,6 @@ get-unwrap = "warn" manual-let-else = "warn" missing-docs-in-private-items = "warn" missing-enforced-import-renames = "warn" -nursery = "warn" obfuscated-if-else = "warn" print-stdout = "warn" semicolon-outside-block = "warn" @@ -74,6 +84,18 @@ unwrap-in-result = "warn" unwrap-used = "warn" use-debug = "warn" +[lints.clippy.all] +level = "warn" +priority = -1 + +[lints.clippy.incompatible-msrv] +level = "allow" +priority = 1 + +[lints.clippy.nursery] +level = "warn" +priority = -1 + [lints.clippy.option-if-let-else] level = "allow" priority = 1 @@ -82,10 +104,15 @@ priority = 1 level = "allow" priority = 1 +[lints.clippy.uninhabited-references] +level = "allow" +priority = 1 + [lints.rust] ambiguous-glob-reexports = "deny" clashing-extern-declarations = "deny" const-item-mutation = "deny" +dangling-pointers-from-temporaries = "deny" deref-nullptr = "deny" drop-bounds = "deny" future-incompatible = "deny" @@ -112,7 +139,6 @@ opaque-hidden-inferred-bound = "deny" overlapping-range-endpoints = "deny" single-use-lifetimes = "warn" suspicious-double-ref-op = "deny" -temporary-cstring-as-ptr = "deny" trivial-casts = "warn" trivial-numeric-casts = "warn" unconditional-recursion = "deny" @@ -120,16 +146,27 @@ unnameable-test-items = "deny" unreachable-pub = "warn" unsafe-op-in-unsafe-fn = "deny" unstable-syntax-pre-expansion = "deny" -unused = "warn" unused-import-braces = "warn" unused-lifetimes = "warn" unused-qualifications = "warn" variant-size-differences = "warn" +[lints.rust.unexpected_cfgs] +level = "deny" +priority = 0 +check-cfg = [ + "cfg(__ui_tests)", + "cfg(bench)", +] + [lints.rust.unstable-name-collisions] -level = "warn" +level = "allow" priority = 1 +[lints.rust.unused] +level = "warn" +priority = -1 + [lints.rustdoc] private-doc-tests = "warn" unescaped-backticks = "warn" diff --git a/pkg/installer/vendor/time-macros/Cargo.toml.orig b/pkg/installer/vendor/time-macros/Cargo.toml.orig index 3451de834ed..2424eb44295 100644 --- a/pkg/installer/vendor/time-macros/Cargo.toml.orig +++ b/pkg/installer/vendor/time-macros/Cargo.toml.orig @@ -1,18 +1,26 @@ +lints.workspace = true + [package] name = "time-macros" -version = "0.2.18" -authors = ["Jacob Pratt ", "Time contributors"] -edition = "2021" -rust-version = "1.67.0" -repository = "https://github.com/time-rs/time" -keywords = ["date", "time", "calendar", "duration"] +version = "0.2.27" categories = ["date-and-time"] -license = "MIT OR Apache-2.0" description = """ Procedural macros for the time crate. This crate is an implementation detail and should not be relied upon directly. """ +authors.workspace = true +edition.workspace = true +keywords.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[package.metadata.docs.rs] +all-features = true +targets = ["x86_64-unknown-linux-gnu"] +rustdoc-args = ["--generate-link-to-definition"] + [features] formatting = [] large-dates = [] @@ -22,12 +30,6 @@ serde = [] [lib] proc-macro = true -[package.metadata.docs.rs] -rustdoc-args = ["--generate-link-to-definition"] - -[lints] -workspace = true - [dependencies] -time-core = { workspace = true } -num-conv = { workspace = true } +time-core.workspace = true +num-conv.workspace = true diff --git a/pkg/installer/vendor/time-macros/LICENSE-Apache b/pkg/installer/vendor/time-macros/LICENSE-Apache index c763a0c9dea..f433b1a53f5 100644 --- a/pkg/installer/vendor/time-macros/LICENSE-Apache +++ b/pkg/installer/vendor/time-macros/LICENSE-Apache @@ -175,28 +175,3 @@ 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 2024 Jacob Pratt et al. - - 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. diff --git a/pkg/installer/vendor/time-macros/LICENSE-MIT b/pkg/installer/vendor/time-macros/LICENSE-MIT index 5cc097f1c02..663cb2a10f8 100644 --- a/pkg/installer/vendor/time-macros/LICENSE-MIT +++ b/pkg/installer/vendor/time-macros/LICENSE-MIT @@ -1,4 +1,4 @@ -Copyright (c) 2024 Jacob Pratt et al. +Copyright (c) Jacob Pratt et al. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/pkg/installer/vendor/time-macros/src/date.rs b/pkg/installer/vendor/time-macros/src/date.rs index 03cbf11ae27..102d23fec9c 100644 --- a/pkg/installer/vendor/time-macros/src/date.rs +++ b/pkg/installer/vendor/time-macros/src/date.rs @@ -1,14 +1,12 @@ use std::iter::Peekable; use num_conv::Truncate; -use proc_macro::{token_stream, TokenTree}; +use proc_macro::token_stream; use time_core::util::{days_in_year, weeks_in_year}; -use crate::helpers::{ - consume_any_ident, consume_number, consume_punct, days_in_year_month, ymd_to_yo, ywd_to_yo, -}; -use crate::to_tokens::ToTokenTree; use crate::Error; +use crate::helpers::{consume_number, consume_punct, days_in_year_month, ymd_to_yo, ywd_to_yo}; +use crate::to_tokens::ToTokenStream; #[cfg(feature = "large-dates")] const MAX_YEAR: i32 = 999_999; @@ -34,40 +32,66 @@ pub(crate) fn parse(chars: &mut Peekable) -> Result= 10_000 { return Err(Error::Custom { message: "years with more than four digits must have an explicit sign".into(), - span_start: Some(year_sign_span.unwrap_or(year_span)), - span_end: Some(year_span), + span_start: Some(year_sign_span.unwrap_or_else(|| year_span.start())), + span_end: Some(year_span.end()), }); } consume_punct('-', chars)?; // year-week-day - if let Ok(w_span) = consume_any_ident(&["W"], chars) { - let (week_span, week) = consume_number::("week", chars)?; - consume_punct('-', chars)?; - let (day_span, day) = consume_number::("day", chars)?; + if let Some(proc_macro::TokenTree::Ident(ident)) = chars.peek() + && let s = ident.to_string() + && s.starts_with('W') + { + let w_span = ident.span(); + drop(chars.next()); // consume 'W' and possibly the week number + + let (week_span, week, day_span, day); + + if s.len() == 1 { + (week_span, week) = consume_number::("week", chars)?; + consume_punct('-', chars)?; + (day_span, day) = consume_number::("day", chars)?; + } else { + let presumptive_week = &s[1..]; + if presumptive_week.bytes().all(|d| d.is_ascii_digit()) + && let Ok(week_number) = presumptive_week.replace('_', "").parse() + { + (week_span, week) = (w_span, week_number); + consume_punct('-', chars)?; + (day_span, day) = consume_number::("day", chars)?; + } else { + return Err(Error::InvalidComponent { + name: "week", + value: presumptive_week.to_string(), + span_start: Some(w_span.start()), + span_end: Some(w_span.end()), + }); + } + }; if week > weeks_in_year(year) { return Err(Error::InvalidComponent { name: "week", value: week.to_string(), - span_start: Some(w_span), - span_end: Some(week_span), + span_start: Some(w_span.start()), + span_end: Some(week_span.end()), }); } if day == 0 || day > 7 { return Err(Error::InvalidComponent { name: "day", value: day.to_string(), - span_start: Some(day_span), - span_end: Some(day_span), + span_start: Some(day_span.start()), + span_end: Some(day_span.end()), }); } @@ -81,7 +105,6 @@ pub(crate) fn parse(chars: &mut Peekable) -> Result("month or ordinal", chars)?; // year-month-day - #[allow(clippy::branches_sharing_code)] // clarity if consume_punct('-', chars).is_ok() { let (month_span, month) = (month_or_ordinal_span, month_or_ordinal); let (day_span, day) = consume_number::("day", chars)?; @@ -90,8 +113,8 @@ pub(crate) fn parse(chars: &mut Peekable) -> Result) -> Result) -> Result) -> Result TokenTree { - quote_group! {{ - const DATE: ::time::Date = unsafe { +impl ToTokenStream for Date { + fn append_to(self, ts: &mut proc_macro::TokenStream) { + quote_append! { ts + unsafe { ::time::Date::__from_ordinal_date_unchecked( #(self.year), #(self.ordinal), ) - }; - DATE - }} + } + } } } diff --git a/pkg/installer/vendor/time-macros/src/datetime.rs b/pkg/installer/vendor/time-macros/src/datetime.rs index 2d41e9a5323..b4800d4d904 100644 --- a/pkg/installer/vendor/time-macros/src/datetime.rs +++ b/pkg/installer/vendor/time-macros/src/datetime.rs @@ -1,12 +1,12 @@ use std::iter::Peekable; -use proc_macro::{token_stream, Ident, Span, TokenTree}; +use proc_macro::{TokenStream, token_stream}; use crate::date::Date; use crate::error::Error; use crate::offset::Offset; use crate::time::Time; -use crate::to_tokens::ToTokenTree; +use crate::to_tokens::ToTokenStream; use crate::{date, offset, time}; pub(crate) struct DateTime { @@ -33,25 +33,18 @@ pub(crate) fn parse(chars: &mut Peekable) -> Result TokenTree { - let (type_name, maybe_offset) = match self.offset { - Some(offset) => ( - Ident::new("OffsetDateTime", Span::mixed_site()), - quote!(.assume_offset(#(offset))), - ), - None => ( - Ident::new("PrimitiveDateTime", Span::mixed_site()), - quote!(), - ), +impl ToTokenStream for DateTime { + fn append_to(self, ts: &mut TokenStream) { + let maybe_offset = match self.offset { + Some(offset) => quote_! { .assume_offset(#S(offset)) }, + None => quote_! {}, }; - quote_group! {{ - const DATE_TIME: ::time::#(type_name) = ::time::PrimitiveDateTime::new( - #(self.date), - #(self.time), - ) #S(maybe_offset); - DATE_TIME - }} + quote_append! { ts + ::time::PrimitiveDateTime::new( + #S(self.date), + #S(self.time), + ) #S(maybe_offset) + } } } diff --git a/pkg/installer/vendor/time-macros/src/format_description/ast.rs b/pkg/installer/vendor/time-macros/src/format_description/ast.rs index 4c3a19e5a61..e30578316a0 100644 --- a/pkg/installer/vendor/time-macros/src/format_description/ast.rs +++ b/pkg/installer/vendor/time-macros/src/format_description/ast.rs @@ -1,6 +1,6 @@ use std::iter; -use super::{lexer, unused, Error, Location, Spanned, SpannedValue, Unused}; +use super::{Error, Location, Spanned, SpannedValue, Unused, lexer, unused}; pub(super) enum Item<'a> { Literal(Spanned<&'a [u8]>), @@ -55,7 +55,7 @@ pub(super) fn parse< const VERSION: u8, >( tokens: &'iter mut lexer::Lexed, -) -> impl Iterator, Error>> + 'iter { +) -> impl Iterator, Error>> + use<'item, 'iter, I, VERSION> { assert!(version!(1..=2)); parse_inner::<_, false, VERSION>(tokens) } @@ -67,7 +67,7 @@ fn parse_inner< const VERSION: u8, >( tokens: &mut lexer::Lexed, -) -> impl Iterator, Error>> + '_ { +) -> impl Iterator, Error>> + use<'_, 'item, I, NESTED, VERSION> { iter::from_fn(move || { if NESTED && tokens.peek_closing_bracket().is_some() { return None; @@ -210,9 +210,9 @@ fn parse_component<'a, I: Iterator, Error>>, cons modifiers.push(Modifier { _leading_whitespace: unused(whitespace), - key: key.spanned(span.shrink_to_before(colon_index as _)), - _colon: unused(span.start.offset(colon_index as _)), - value: value.spanned(span.shrink_to_after(colon_index as _)), + key: key.spanned(span.shrink_to_before(colon_index as u32)), + _colon: unused(span.start.offset(colon_index as u32)), + value: value.spanned(span.shrink_to_after(colon_index as u32)), }); }; diff --git a/pkg/installer/vendor/time-macros/src/format_description/format_item.rs b/pkg/installer/vendor/time-macros/src/format_description/format_item.rs index ea36caee05f..78890f7711e 100644 --- a/pkg/installer/vendor/time-macros/src/format_description/format_item.rs +++ b/pkg/installer/vendor/time-macros/src/format_description/format_item.rs @@ -1,7 +1,7 @@ -use std::num::NonZeroU16; +use std::num::NonZero; use std::str::{self, FromStr}; -use super::{ast, unused, Error, Span, Spanned, Unused}; +use super::{Error, Span, Spanned, Unused, ast, unused}; pub(super) fn parse<'a>( ast_items: impl Iterator, Error>>, @@ -207,14 +207,16 @@ component_definition! { Day = "day" { padding = "padding": Option => padding, }, - End = "end" {}, + End = "end" { + trailing_input = "trailing_input": Option => trailing_input, + }, Hour = "hour" { padding = "padding": Option => padding, base = "repr": Option => is_12_hour_clock, }, Ignore = "ignore" { #[required] - count = "count": Option<#[from_str] NonZeroU16> => count, + count = "count": Option<#[from_str] NonZero> => count, }, Minute = "minute" { padding = "padding": Option => padding, @@ -263,6 +265,7 @@ component_definition! { Year = "year" { padding = "padding": Option => padding, repr = "repr": Option => repr, + range = "range": Option => range, base = "base": Option => iso_week_based, sign_behavior = "sign": Option => sign_is_mandatory, }, @@ -381,6 +384,12 @@ modifier! { OneOrMore = b"1+", } + enum TrailingInput { + #[default] + Prohibit = b"prohibit", + Discard = b"discard", + } + enum UnixTimestampPrecision { #[default] Second = b"second", @@ -425,8 +434,15 @@ modifier! { enum YearRepr { #[default] Full = b"full", + Century = b"century", LastTwo = b"last_two", } + + enum YearRange { + Standard = b"standard", + #[default] + Extended = b"extended", + } } fn parse_from_modifier_value(value: &Spanned<&[u8]>) -> Result, Error> { diff --git a/pkg/installer/vendor/time-macros/src/format_description/lexer.rs b/pkg/installer/vendor/time-macros/src/format_description/lexer.rs index 2ea53af57ab..50f125f0889 100644 --- a/pkg/installer/vendor/time-macros/src/format_description/lexer.rs +++ b/pkg/installer/vendor/time-macros/src/format_description/lexer.rs @@ -102,9 +102,7 @@ pub(super) enum BracketKind { } pub(super) enum ComponentKind { - #[allow(clippy::missing_docs_in_private_items)] Whitespace, - #[allow(clippy::missing_docs_in_private_items)] NotWhitespace, } @@ -124,25 +122,24 @@ fn attach_location<'item>( }) } -#[allow(clippy::unused_peekable)] // false positive pub(super) fn lex( mut input: &[u8], proc_span: proc_macro::Span, ) -> Lexed, Error>>> { assert!(version!(1..=2)); - let mut depth: u8 = 0; + let mut depth: u32 = 0; let mut iter = attach_location(input.iter(), proc_span).peekable(); let mut second_bracket_location = None; let iter = iter::from_fn(move || { - if version!(..=1) { - if let Some(location) = second_bracket_location.take() { - return Some(Ok(Token::Bracket { - kind: BracketKind::Opening, - location, - })); - } + if version!(..=1) + && let Some(location) = second_bracket_location.take() + { + return Some(Ok(Token::Bracket { + kind: BracketKind::Opening, + location, + })); } Some(Ok(match iter.next()? { diff --git a/pkg/installer/vendor/time-macros/src/format_description/mod.rs b/pkg/installer/vendor/time-macros/src/format_description/mod.rs index 676028dec48..d7ab1854676 100644 --- a/pkg/installer/vendor/time-macros/src/format_description/mod.rs +++ b/pkg/installer/vendor/time-macros/src/format_description/mod.rs @@ -67,9 +67,7 @@ impl Location { #[derive(Clone, Copy)] struct Span { - #[allow(clippy::missing_docs_in_private_items)] start: Location, - #[allow(clippy::missing_docs_in_private_items)] end: Location, } @@ -163,7 +161,6 @@ impl From for crate::Error { struct Unused(core::marker::PhantomData); -#[allow(clippy::missing_const_for_fn)] // false positive fn unused(_: T) -> Unused { Unused(core::marker::PhantomData) } diff --git a/pkg/installer/vendor/time-macros/src/format_description/public/component.rs b/pkg/installer/vendor/time-macros/src/format_description/public/component.rs index 94c73f0fb4d..83c0f0df8e5 100644 --- a/pkg/installer/vendor/time-macros/src/format_description/public/component.rs +++ b/pkg/installer/vendor/time-macros/src/format_description/public/component.rs @@ -22,7 +22,7 @@ macro_rules! declare_component { let component = Ident::new(component, Span::mixed_site()); quote_append! { ts - ::time::format_description::Component::#(component)(#S(mts)) + Component::#(component)(#S(mts)) } } } diff --git a/pkg/installer/vendor/time-macros/src/format_description/public/mod.rs b/pkg/installer/vendor/time-macros/src/format_description/public/mod.rs index 9fd8b5ece1f..68e39c9262f 100644 --- a/pkg/installer/vendor/time-macros/src/format_description/public/mod.rs +++ b/pkg/installer/vendor/time-macros/src/format_description/public/mod.rs @@ -1,12 +1,11 @@ mod component; pub(super) mod modifier; -use proc_macro::{Literal, TokenStream}; +use proc_macro::TokenStream; pub(crate) use self::component::Component; use crate::to_tokens::ToTokenStream; -#[allow(variant_size_differences)] pub(crate) enum OwnedFormatItem { Literal(Box<[u8]>), Component(Component), @@ -19,34 +18,32 @@ impl ToTokenStream for OwnedFormatItem { fn append_to(self, ts: &mut TokenStream) { match self { Self::Literal(bytes) => quote_append! { ts - ::time::format_description::BorrowedFormatItem::Literal { - 0: #(Literal::byte_string(bytes.as_ref())) - } + BorrowedFormatItem::Literal(#(Literal::byte_string(bytes.as_ref()))) }, Self::Component(component) => quote_append! { ts - ::time::format_description::BorrowedFormatItem::Component { 0: #S(component) } + BorrowedFormatItem::Component { 0: #S(component) } }, Self::Compound(items) => { let items = items .into_vec() .into_iter() - .map(|item| quote! { #S(item), }) + .map(|item| quote_! { #S(item), }) .collect::(); quote_append! { ts - ::time::format_description::BorrowedFormatItem::Compound { 0: &[#S(items)] } + BorrowedFormatItem::Compound { 0: &[#S(items)] } } } - Self::Optional(item) => quote_append! {ts - ::time::format_description::BorrowedFormatItem::Optional { 0: &#S(*item) } + Self::Optional(item) => quote_append! { ts + BorrowedFormatItem::Optional { 0: &#S(*item) } }, Self::First(items) => { let items = items .into_vec() .into_iter() - .map(|item| quote! { #S(item), }) + .map(|item| quote_! { #S(item), }) .collect::(); quote_append! { ts - ::time::format_description::BorrowedFormatItem::First { 0: &[#S(items)] } + BorrowedFormatItem::First { 0: &[#S(items)] } } } } diff --git a/pkg/installer/vendor/time-macros/src/format_description/public/modifier.rs b/pkg/installer/vendor/time-macros/src/format_description/public/modifier.rs index 63bfaa7065f..b8bfd6e8f8e 100644 --- a/pkg/installer/vendor/time-macros/src/format_description/public/modifier.rs +++ b/pkg/installer/vendor/time-macros/src/format_description/public/modifier.rs @@ -1,6 +1,6 @@ -use std::num::NonZeroU16; +use std::num::NonZero; -use proc_macro::{Ident, Span, TokenStream, TokenTree}; +use proc_macro::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; use crate::to_tokens::{ToTokenStream, ToTokenTree}; @@ -9,7 +9,7 @@ macro_rules! to_tokens { $(#[$struct_attr:meta])* $struct_vis:vis struct $struct_name:ident {$( $(#[$field_attr:meta])* - $field_vis:vis $field_name:ident : $field_ty:ty + $field_vis:vis $field_name:ident : $field_ty:ty = $default:pat ),* $(,)?} ) => { $(#[$struct_attr])* @@ -20,21 +20,29 @@ macro_rules! to_tokens { impl ToTokenTree for $struct_name { fn into_token_tree(self) -> TokenTree { - let mut tokens = TokenStream::new(); let Self {$($field_name),*} = self; - quote_append! { tokens - let mut value = ::time::format_description::modifier::$struct_name::default(); + #[allow(clippy::redundant_pattern_matching)] + if matches!(($(&$field_name,)*), ($($default,)*)) { + return TokenTree::Group(Group::new( + Delimiter::None, + quote_! { $struct_name::default() } + )); + } + + let mut tokens = quote_! { + $struct_name::default() }; $( - quote_append!(tokens value.$field_name =); - $field_name.append_to(&mut tokens); - quote_append!(tokens ;); + #[allow(clippy::redundant_pattern_matching)] + if !matches!($field_name, $default) { + let method_name = Ident::new(concat!("with_", stringify!($field_name)), Span::mixed_site()); + quote_append!(tokens .#(method_name)(#S($field_name))); + } )* - quote_append!(tokens value); - proc_macro::TokenTree::Group(proc_macro::Group::new( - proc_macro::Delimiter::Brace, + TokenTree::Group(Group::new( + Delimiter::Brace, tokens, )) } @@ -57,7 +65,7 @@ macro_rules! to_tokens { impl ToTokenStream for $enum_name { fn append_to(self, ts: &mut TokenStream) { quote_append! { ts - ::time::format_description::modifier::$enum_name:: + $enum_name:: }; let name = match self { $(Self::$variant_name => stringify!($variant_name)),+ @@ -70,7 +78,7 @@ macro_rules! to_tokens { to_tokens! { pub(crate) struct Day { - pub(crate) padding: Padding, + pub(crate) padding: Padding = Padding::Zero, } } @@ -84,15 +92,15 @@ to_tokens! { to_tokens! { pub(crate) struct Month { - pub(crate) padding: Padding, - pub(crate) repr: MonthRepr, - pub(crate) case_sensitive: bool, + pub(crate) padding: Padding = Padding::Zero, + pub(crate) repr: MonthRepr = MonthRepr::Numerical, + pub(crate) case_sensitive: bool = true, } } to_tokens! { pub(crate) struct Ordinal { - pub(crate) padding: Padding, + pub(crate) padding: Padding = Padding::Zero, } } @@ -107,9 +115,9 @@ to_tokens! { to_tokens! { pub(crate) struct Weekday { - pub(crate) repr: WeekdayRepr, - pub(crate) one_indexed: bool, - pub(crate) case_sensitive: bool, + pub(crate) repr: WeekdayRepr = WeekdayRepr::Long, + pub(crate) one_indexed: bool = true, + pub(crate) case_sensitive: bool = true, } } @@ -123,50 +131,59 @@ to_tokens! { to_tokens! { pub(crate) struct WeekNumber { - pub(crate) padding: Padding, - pub(crate) repr: WeekNumberRepr, + pub(crate) padding: Padding = Padding::Zero, + pub(crate) repr: WeekNumberRepr = WeekNumberRepr::Iso, } } to_tokens! { pub(crate) enum YearRepr { Full, + Century, LastTwo, } } +to_tokens! { + pub(crate) enum YearRange { + Standard, + Extended, + } +} + to_tokens! { pub(crate) struct Year { - pub(crate) padding: Padding, - pub(crate) repr: YearRepr, - pub(crate) iso_week_based: bool, - pub(crate) sign_is_mandatory: bool, + pub(crate) padding: Padding = Padding::Zero, + pub(crate) repr: YearRepr = YearRepr::Full, + pub(crate) range: YearRange = YearRange::Extended, + pub(crate) iso_week_based: bool = false, + pub(crate) sign_is_mandatory: bool = false, } } to_tokens! { pub(crate) struct Hour { - pub(crate) padding: Padding, - pub(crate) is_12_hour_clock: bool, + pub(crate) padding: Padding = Padding::Zero, + pub(crate) is_12_hour_clock: bool = false, } } to_tokens! { pub(crate) struct Minute { - pub(crate) padding: Padding, + pub(crate) padding: Padding = Padding::Zero, } } to_tokens! { pub(crate) struct Period { - pub(crate) is_uppercase: bool, - pub(crate) case_sensitive: bool, + pub(crate) is_uppercase: bool = true, + pub(crate) case_sensitive: bool = true, } } to_tokens! { pub(crate) struct Second { - pub(crate) padding: Padding, + pub(crate) padding: Padding = Padding::Zero, } } @@ -187,26 +204,26 @@ to_tokens! { to_tokens! { pub(crate) struct Subsecond { - pub(crate) digits: SubsecondDigits, + pub(crate) digits: SubsecondDigits = SubsecondDigits::OneOrMore, } } to_tokens! { pub(crate) struct OffsetHour { - pub(crate) sign_is_mandatory: bool, - pub(crate) padding: Padding, + pub(crate) sign_is_mandatory: bool = false, + pub(crate) padding: Padding = Padding::Zero, } } to_tokens! { pub(crate) struct OffsetMinute { - pub(crate) padding: Padding, + pub(crate) padding: Padding = Padding::Zero, } } to_tokens! { pub(crate) struct OffsetSecond { - pub(crate) padding: Padding, + pub(crate) padding: Padding = Padding::Zero, } } @@ -219,13 +236,13 @@ to_tokens! { } pub(crate) struct Ignore { - pub(crate) count: NonZeroU16, + pub(crate) count: NonZero, } impl ToTokenTree for Ignore { fn into_token_tree(self) -> TokenTree { quote_group! {{ - ::time::format_description::modifier::Ignore::count(#(self.count)) + Ignore::count(#(self.count)) }} } } @@ -241,11 +258,20 @@ to_tokens! { to_tokens! { pub(crate) struct UnixTimestamp { - pub(crate) precision: UnixTimestampPrecision, - pub(crate) sign_is_mandatory: bool, + pub(crate) precision: UnixTimestampPrecision = UnixTimestampPrecision::Second, + pub(crate) sign_is_mandatory: bool = false, } } to_tokens! { - pub(crate) struct End {} + pub(crate) enum TrailingInput { + Prohibit, + Discard, + } +} + +to_tokens! { + pub(crate) struct End { + pub(crate) trailing_input: TrailingInput = TrailingInput::Prohibit, + } } diff --git a/pkg/installer/vendor/time-macros/src/helpers/mod.rs b/pkg/installer/vendor/time-macros/src/helpers/mod.rs index 0cca2002def..532c8ae9411 100644 --- a/pkg/installer/vendor/time-macros/src/helpers/mod.rs +++ b/pkg/installer/vendor/time-macros/src/helpers/mod.rs @@ -5,7 +5,7 @@ use std::iter::Peekable; use std::str::FromStr; use num_conv::prelude::*; -use proc_macro::{token_stream, Span, TokenTree}; +use proc_macro::{Span, TokenTree, token_stream}; use time_core::util::{days_in_year, is_leap_year}; use crate::Error; diff --git a/pkg/installer/vendor/time-macros/src/lib.rs b/pkg/installer/vendor/time-macros/src/lib.rs index 65e24d7d3b0..d514d8caf02 100644 --- a/pkg/installer/vendor/time-macros/src/lib.rs +++ b/pkg/installer/vendor/time-macros/src/lib.rs @@ -1,13 +1,20 @@ #![allow( - clippy::missing_const_for_fn, // irrelevant for proc macros - clippy::missing_docs_in_private_items, // TODO remove - clippy::std_instead_of_core, // irrelevant for proc macros - clippy::std_instead_of_alloc, // irrelevant for proc macros - clippy::alloc_instead_of_core, // irrelevant for proc macros - missing_docs, // TODO remove + clippy::missing_const_for_fn, + clippy::std_instead_of_core, + clippy::std_instead_of_alloc, + clippy::alloc_instead_of_core, + reason = "irrelevant for proc macros" +)] +#![allow( + clippy::missing_docs_in_private_items, + missing_docs, + reason = "may be removed eventually" )] -#[allow(unused_macros)] +#[allow( + unused_macros, + reason = "may not be used for all feature flag combinations" +)] macro_rules! bug { () => { compile_error!("provide an error message to help fix a possible bug") }; ($descr:literal $($rest:tt)?) => { @@ -29,13 +36,16 @@ mod offset; mod serde_format_description; mod time; mod to_tokens; +mod utc_datetime; #[cfg(any(feature = "formatting", feature = "parsing"))] use std::iter::Peekable; +#[cfg(all(feature = "serde", any(feature = "formatting", feature = "parsing")))] +use proc_macro::Delimiter; use proc_macro::TokenStream; #[cfg(any(feature = "formatting", feature = "parsing"))] -use proc_macro::{Ident, TokenTree}; +use proc_macro::TokenTree; use self::error::Error; @@ -43,13 +53,13 @@ macro_rules! impl_macros { ($($name:ident)*) => {$( #[proc_macro] pub fn $name(input: TokenStream) -> TokenStream { - use crate::to_tokens::ToTokenTree; + use crate::to_tokens::ToTokenStream; let mut iter = input.into_iter().peekable(); match $name::parse(&mut iter) { Ok(value) => match iter.peek() { Some(tree) => Error::UnexpectedToken { tree: tree.clone() }.to_compile_error(), - None => TokenStream::from(value.into_token_tree()), + None => quote_! { const { #S(value.into_token_stream()) } }, }, Err(err) => err.to_compile_error(), } @@ -57,7 +67,10 @@ macro_rules! impl_macros { )*}; } -impl_macros![date datetime offset time]; +impl_macros![date datetime utc_datetime offset time]; + +#[cfg(any(feature = "formatting", feature = "parsing"))] +type PeekableTokenStreamIter = Peekable; #[cfg(any(feature = "formatting", feature = "parsing"))] enum FormatDescriptionVersion { @@ -65,28 +78,39 @@ enum FormatDescriptionVersion { V2, } -#[cfg(any(feature = "formatting", feature = "parsing"))] -enum VersionOrModuleName { - Version(FormatDescriptionVersion), - #[cfg_attr(not(feature = "serde"), allow(dead_code))] - ModuleName(Ident), -} - #[cfg(any(feature = "formatting", feature = "parsing"))] fn parse_format_description_version( - iter: &mut Peekable, -) -> Result, Error> { - let version_ident = match iter.peek() { - Some(TokenTree::Ident(ident)) if ident.to_string() == "version" => match iter.next() { - Some(TokenTree::Ident(ident)) => ident, - _ => unreachable!(), - }, + iter: &mut PeekableTokenStreamIter, +) -> Result, Error> { + let end_of_input_err = || { + if NO_EQUALS_IS_MOD_NAME { + Error::UnexpectedEndOfInput + } else { + Error::ExpectedString { + span_start: None, + span_end: None, + } + } + }; + let version_ident = match iter.peek().ok_or_else(end_of_input_err)? { + version @ TokenTree::Ident(ident) if ident.to_string() == "version" => { + let version_ident = version.clone(); + iter.next(); // consume `version` + version_ident + } _ => return Ok(None), }; + match iter.peek() { Some(TokenTree::Punct(punct)) if punct.as_char() == '=' => iter.next(), _ if NO_EQUALS_IS_MOD_NAME => { - return Ok(Some(VersionOrModuleName::ModuleName(version_ident))); + // Push the `version` ident to the front of the iterator. + *iter = std::iter::once(version_ident) + .chain(iter.clone()) + .collect::() + .into_iter() + .peekable(); + return Ok(None); } Some(token) => { return Err(Error::Custom { @@ -133,7 +157,29 @@ fn parse_format_description_version( }; helpers::consume_punct(',', iter)?; - Ok(Some(VersionOrModuleName::Version(version))) + Ok(Some(version)) +} + +#[cfg(all(feature = "serde", any(feature = "formatting", feature = "parsing")))] +fn parse_visibility(iter: &mut PeekableTokenStreamIter) -> Result { + let mut visibility = match iter.peek().ok_or(Error::UnexpectedEndOfInput)? { + pub_ident @ TokenTree::Ident(ident) if ident.to_string() == "pub" => { + let visibility = quote_! { #(pub_ident.clone()) }; + iter.next(); // consume `pub` + visibility + } + _ => return Ok(quote_! {}), + }; + + match iter.peek().ok_or(Error::UnexpectedEndOfInput)? { + group @ TokenTree::Group(path) if path.delimiter() == Delimiter::Parenthesis => { + visibility.extend(std::iter::once(group.clone())); + iter.next(); // consume parentheses and path + } + _ => {} + } + + Ok(visibility) } #[cfg(any(feature = "formatting", feature = "parsing"))] @@ -141,24 +187,21 @@ fn parse_format_description_version( pub fn format_description(input: TokenStream) -> TokenStream { (|| { let mut input = input.into_iter().peekable(); - let version = match parse_format_description_version::(&mut input)? { - Some(VersionOrModuleName::Version(version)) => Some(version), - None => None, - // This branch should never occur here, as `false` is the provided as a const parameter. - Some(VersionOrModuleName::ModuleName(_)) => bug!("branch should never occur"), - }; + let version = parse_format_description_version::(&mut input)?; let (span, string) = helpers::get_string_literal(input)?; let items = format_description::parse_with_version(version, &string, span)?; - Ok(quote! {{ - const DESCRIPTION: &[::time::format_description::BorrowedFormatItem<'_>] = &[#S( - items - .into_iter() - .map(|item| quote! { #S(item), }) - .collect::() - )]; - DESCRIPTION - }}) + Ok(quote_! { + const { + use ::time::format_description::{*, modifier::*}; + &[#S( + items + .into_iter() + .map(|item| quote_! { #S(item), }) + .collect::() + )] as StaticFormatDescription + } + }) })() .unwrap_or_else(|err: Error| err.to_compile_error()) } @@ -171,22 +214,16 @@ pub fn serde_format_description(input: TokenStream) -> TokenStream { // First, the optional format description version. let version = parse_format_description_version::(&mut tokens)?; - let (version, mod_name) = match version { - Some(VersionOrModuleName::ModuleName(module_name)) => (None, Some(module_name)), - Some(VersionOrModuleName::Version(version)) => (Some(version), None), - None => (None, None), - }; + + // Then, the visibility of the module. + let visibility = parse_visibility(&mut tokens)?; // Next, an identifier (the desired module name) - // Only parse this if it wasn't parsed when attempting to get the version. - let mod_name = match mod_name { - Some(mod_name) => mod_name, - None => match tokens.next() { - Some(TokenTree::Ident(ident)) => Ok(ident), - Some(tree) => Err(Error::UnexpectedToken { tree }), - None => Err(Error::UnexpectedEndOfInput), - }?, - }; + let mod_name = match tokens.next() { + Some(TokenTree::Ident(ident)) => Ok(ident), + Some(tree) => Err(Error::UnexpectedToken { tree }), + None => Err(Error::UnexpectedEndOfInput), + }?; // Followed by a comma helpers::consume_punct(',', &mut tokens)?; @@ -209,12 +246,15 @@ pub fn serde_format_description(input: TokenStream) -> TokenStream { Some(TokenTree::Literal(_)) => { let (span, format_string) = helpers::get_string_literal(tokens)?; let items = format_description::parse_with_version(version, &format_string, span)?; - let items: TokenStream = - items.into_iter().map(|item| quote! { #S(item), }).collect(); - let items = quote! { - const ITEMS: &[::time::format_description::BorrowedFormatItem<'_>] - = &[#S(items)]; - ITEMS + let items: TokenStream = items + .into_iter() + .map(|item| quote_! { #S(item), }) + .collect(); + let items = quote_! { + const { + use ::time::format_description::{*, modifier::*}; + &[#S(items)] as StaticFormatDescription + } }; (items, String::from_utf8_lossy(&format_string).into_owned()) @@ -223,27 +263,13 @@ pub fn serde_format_description(input: TokenStream) -> TokenStream { Some(_) => { let tokens = tokens.collect::(); let tokens_string = tokens.to_string(); - ( - quote! {{ - // We can't just do `super::path` because the path could be an absolute - // path. In that case, we'd be generating `super::::path`, which is invalid. - // Even if we took that into account, it's not possible to know if it's an - // external crate, which would just require emitting `path` directly. By - // taking this approach, we can leave it to the compiler to do the actual - // resolution. - mod __path_hack { - pub(super) use super::super::*; - pub(super) use #S(tokens) as FORMAT; - } - __path_hack::FORMAT - }}, - tokens_string, - ) + (tokens, tokens_string) } None => return Err(Error::UnexpectedEndOfInput), }; Ok(serde_format_description::build( + visibility, mod_name, formattable, format, diff --git a/pkg/installer/vendor/time-macros/src/offset.rs b/pkg/installer/vendor/time-macros/src/offset.rs index 04dd37f1310..902d413f59e 100644 --- a/pkg/installer/vendor/time-macros/src/offset.rs +++ b/pkg/installer/vendor/time-macros/src/offset.rs @@ -1,12 +1,11 @@ use std::iter::Peekable; -use num_conv::prelude::*; -use proc_macro::{token_stream, Span, TokenTree}; +use proc_macro::{Span, TokenStream, token_stream}; use time_core::convert::*; -use crate::helpers::{consume_any_ident, consume_number, consume_punct}; -use crate::to_tokens::ToTokenTree; use crate::Error; +use crate::helpers::{consume_any_ident, consume_number, consume_punct}; +use crate::to_tokens::ToTokenStream; pub(crate) struct Offset { pub(crate) hours: i8, @@ -57,22 +56,22 @@ pub(crate) fn parse(chars: &mut Peekable) -> Result= Minute::per(Hour).cast_signed() { + } else if minutes >= Minute::per_t(Hour) { Err(Error::InvalidComponent { name: "minute", value: minutes.to_string(), - span_start: Some(minutes_span), - span_end: Some(minutes_span), + span_start: Some(minutes_span.start()), + span_end: Some(minutes_span.end()), }) - } else if seconds >= Second::per(Minute).cast_signed() { + } else if seconds >= Second::per_t(Minute) { Err(Error::InvalidComponent { name: "second", value: seconds.to_string(), - span_start: Some(seconds_span), - span_end: Some(seconds_span), + span_start: Some(seconds_span.start()), + span_end: Some(seconds_span.end()), }) } else { Ok(Offset { @@ -83,17 +82,16 @@ pub(crate) fn parse(chars: &mut Peekable) -> Result TokenTree { - quote_group! {{ - const OFFSET: ::time::UtcOffset = unsafe { +impl ToTokenStream for Offset { + fn append_to(self, ts: &mut TokenStream) { + quote_append! { ts + unsafe { ::time::UtcOffset::__from_hms_unchecked( #(self.hours), #(self.minutes), #(self.seconds), ) - }; - OFFSET - }} + } + } } } diff --git a/pkg/installer/vendor/time-macros/src/quote.rs b/pkg/installer/vendor/time-macros/src/quote.rs index 8603f4fa466..d7c9c1f5b40 100644 --- a/pkg/installer/vendor/time-macros/src/quote.rs +++ b/pkg/installer/vendor/time-macros/src/quote.rs @@ -1,47 +1,40 @@ -macro_rules! quote { - () => (::proc_macro::TokenStream::new()); +macro_rules! quote_ { + () => (proc_macro::TokenStream::new()); ($($x:tt)*) => {{ - let mut ts = ::proc_macro::TokenStream::new(); + use proc_macro::*; + let mut ts = TokenStream::new(); let ts_mut = &mut ts; quote_inner!(ts_mut $($x)*); ts }}; } -#[cfg(any(feature = "formatting", feature = "parsing"))] macro_rules! quote_append { ($ts:ident $($x:tt)*) => {{ + use proc_macro::*; quote_inner!($ts $($x)*); }}; } macro_rules! quote_group { - ({ $($x:tt)* }) => { - ::proc_macro::TokenTree::Group(::proc_macro::Group::new( - ::proc_macro::Delimiter::Brace, - quote!($($x)*) + ({ $($x:tt)* }) => {{ + use proc_macro::*; + TokenTree::Group(Group::new( + Delimiter::Brace, + quote_!($($x)*) )) - }; + }}; } macro_rules! sym { ($ts:ident $x:tt $y:tt) => { $ts.extend([ - ::proc_macro::TokenTree::from(::proc_macro::Punct::new( - $x, - ::proc_macro::Spacing::Joint, - )), - ::proc_macro::TokenTree::from(::proc_macro::Punct::new( - $y, - ::proc_macro::Spacing::Alone, - )), + TokenTree::from(Punct::new($x, Spacing::Joint)), + TokenTree::from(Punct::new($y, Spacing::Alone)), ]); }; ($ts:ident $x:tt) => { - $ts.extend([::proc_macro::TokenTree::from(::proc_macro::Punct::new( - $x, - ::proc_macro::Spacing::Alone, - ))]); + $ts.extend([TokenTree::from(Punct::new($x, Spacing::Alone))]); }; } @@ -70,32 +63,46 @@ macro_rules! quote_inner { // Identifier ($ts:ident $i:ident $($tail:tt)*) => { - $ts.extend([::proc_macro::TokenTree::from(::proc_macro::Ident::new( + $ts.extend([TokenTree::from(Ident::new( &stringify!($i), - ::proc_macro::Span::mixed_site(), + Span::mixed_site(), ))]); quote_inner!($ts $($tail)*); }; // Literal ($ts:ident 0 $($tail:tt)*) => { - $ts.extend([::proc_macro::TokenTree::from(::proc_macro::Literal::usize_unsuffixed(0))]); + $ts.extend([TokenTree::from(Literal::usize_unsuffixed(0))]); quote_inner!($ts $($tail)*); }; ($ts:ident $l:literal $($tail:tt)*) => { - $ts.extend([::proc_macro::TokenTree::from(::proc_macro::Literal::string(&$l))]); + $ts.extend([TokenTree::from(Literal::string(&$l))]); quote_inner!($ts $($tail)*); }; // Lifetime ($ts:ident $l:lifetime $($tail:tt)*) => { $ts.extend([ - ::proc_macro::TokenTree::from( - ::proc_macro::Punct::new('\'', ::proc_macro::Spacing::Joint) + TokenTree::from( + Punct::new('\'', Spacing::Joint) ), - ::proc_macro::TokenTree::from(::proc_macro::Ident::new( + TokenTree::from(Ident::new( stringify!($l).trim_start_matches(|c| c == '\''), - ::proc_macro::Span::mixed_site(), + Span::mixed_site(), + )), + ]); + quote_inner!($ts $($tail)*); + }; + + // Attribute + ($ts:ident #[$($inner:tt)*] $($tail:tt)*) => { + $ts.extend([ + TokenTree::from( + Punct::new('#', Spacing::Alone) + ), + TokenTree::Group(Group::new( + Delimiter::Bracket, + quote_!($($inner)*) )), ]); quote_inner!($ts $($tail)*); @@ -103,23 +110,23 @@ macro_rules! quote_inner { // Groups ($ts:ident ($($inner:tt)*) $($tail:tt)*) => { - $ts.extend([::proc_macro::TokenTree::Group(::proc_macro::Group::new( - ::proc_macro::Delimiter::Parenthesis, - quote!($($inner)*) + $ts.extend([TokenTree::Group(Group::new( + Delimiter::Parenthesis, + quote_!($($inner)*) ))]); quote_inner!($ts $($tail)*); }; ($ts:ident [$($inner:tt)*] $($tail:tt)*) => { - $ts.extend([::proc_macro::TokenTree::Group(::proc_macro::Group::new( - ::proc_macro::Delimiter::Bracket, - quote!($($inner)*) + $ts.extend([TokenTree::Group(Group::new( + Delimiter::Bracket, + quote_!($($inner)*) ))]); quote_inner!($ts $($tail)*); }; ($ts:ident {$($inner:tt)*} $($tail:tt)*) => { - $ts.extend([::proc_macro::TokenTree::Group(::proc_macro::Group::new( - ::proc_macro::Delimiter::Brace, - quote!($($inner)*) + $ts.extend([TokenTree::Group(Group::new( + Delimiter::Brace, + quote_!($($inner)*) ))]); quote_inner!($ts $($tail)*); }; diff --git a/pkg/installer/vendor/time-macros/src/serde_format_description.rs b/pkg/installer/vendor/time-macros/src/serde_format_description.rs index 34b99f67908..669e13ade05 100644 --- a/pkg/installer/vendor/time-macros/src/serde_format_description.rs +++ b/pkg/installer/vendor/time-macros/src/serde_format_description.rs @@ -1,6 +1,7 @@ use proc_macro::{Ident, TokenStream, TokenTree}; pub(crate) fn build( + visibility: TokenStream, mod_name: Ident, ty: TokenTree, format: TokenStream, @@ -9,9 +10,9 @@ pub(crate) fn build( let ty_s = &*ty.to_string(); let visitor = if cfg!(feature = "parsing") { - quote! { - struct Visitor; - struct OptionVisitor; + quote_! { + pub(super) struct Visitor; + pub(super) struct OptionVisitor; impl<'a> ::serde::de::Visitor<'a> for Visitor { type Value = __TimeSerdeType; @@ -68,11 +69,11 @@ pub(crate) fn build( } } } else { - quote!() + quote_!() }; let serialize_primary = if cfg!(feature = "formatting") { - quote! { + quote_! { pub fn serialize( datetime: &__TimeSerdeType, serializer: S, @@ -85,11 +86,11 @@ pub(crate) fn build( } } } else { - quote!() + quote_!() }; let deserialize_primary = if cfg!(feature = "parsing") { - quote! { + quote_! { pub fn deserialize<'a, D: ::serde::Deserializer<'a>>( deserializer: D ) -> Result<__TimeSerdeType, D::Error> { @@ -98,11 +99,12 @@ pub(crate) fn build( } } } else { - quote!() + quote_!() }; let serialize_option = if cfg!(feature = "formatting") { - quote! { + quote_! { + #[expect(clippy::ref_option)] pub fn serialize( option: &Option<__TimeSerdeType>, serializer: S, @@ -115,11 +117,11 @@ pub(crate) fn build( } } } else { - quote!() + quote_!() }; let deserialize_option = if cfg!(feature = "parsing") { - quote! { + quote_! { pub fn deserialize<'a, D: ::serde::Deserializer<'a>>( deserializer: D ) -> Result, D::Error> { @@ -128,39 +130,50 @@ pub(crate) fn build( } } } else { - quote!() + quote_!() }; let deserialize_option_imports = if cfg!(feature = "parsing") { - quote! { - use super::{OptionVisitor, Visitor}; + quote_! { + use super::__hygiene::{OptionVisitor, Visitor}; } } else { - quote!() + quote_!() }; let fd_traits = match (cfg!(feature = "formatting"), cfg!(feature = "parsing")) { (false, false) => { bug!("serde_format_description::build called without formatting or parsing enabled") } - (false, true) => quote! { ::time::parsing::Parsable }, - (true, false) => quote! { ::time::formatting::Formattable }, - (true, true) => quote! { ::time::formatting::Formattable + ::time::parsing::Parsable }, + (false, true) => quote_! { ::time::parsing::Parsable }, + (true, false) => quote_! { ::time::formatting::Formattable }, + (true, true) => quote_! { ::time::formatting::Formattable + ::time::parsing::Parsable }, }; - quote! { - mod #(mod_name) { + quote_! { + #S(visibility) mod #(mod_name) { + use super::*; + // TODO Remove the prefix, forcing the user to import the type themself. This must be + // done in a breaking change. use ::time::#(ty) as __TimeSerdeType; + #[expect(clippy::pub_use)] + pub use self::__hygiene::*; const fn description() -> impl #S(fd_traits) { #S(format) } - #S(visitor) - #S(serialize_primary) - #S(deserialize_primary) + mod __hygiene { + use super::{description, __TimeSerdeType}; + + #S(visitor) + #S(serialize_primary) + #S(deserialize_primary) + } - pub(super) mod option { + // While technically public, this is effectively the same visibility as the enclosing + // module, which has its visibility controlled by the user. + pub mod option { use super::{description, __TimeSerdeType}; #S(deserialize_option_imports) diff --git a/pkg/installer/vendor/time-macros/src/time.rs b/pkg/installer/vendor/time-macros/src/time.rs index 4e565c1ded1..1163ab2a1a2 100644 --- a/pkg/installer/vendor/time-macros/src/time.rs +++ b/pkg/installer/vendor/time-macros/src/time.rs @@ -1,11 +1,11 @@ use std::iter::Peekable; -use proc_macro::{token_stream, Span, TokenTree}; +use proc_macro::{Span, TokenStream, token_stream}; use time_core::convert::*; -use crate::helpers::{consume_any_ident, consume_number, consume_punct}; -use crate::to_tokens::ToTokenTree; use crate::Error; +use crate::helpers::{consume_any_ident, consume_number, consume_punct}; +use crate::to_tokens::ToTokenStream; enum Period { Am, @@ -63,8 +63,8 @@ pub(crate) fn parse(chars: &mut Peekable) -> Result