diff options
author | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2021-06-23 02:35:00 +0000 |
---|---|---|
committer | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2021-06-23 02:35:00 +0000 |
commit | 7b7be61998ba3f906c18bb94fe73fc8b98fb1151 (patch) | |
tree | a9f5b49c1bcd5d7f11000a655eb7da788ef16208 | |
parent | 83d3986cfea93b8928487b3c5967c4f72c8d5111 (diff) | |
parent | 4b53745041c30d69b075a501e74cfb3a5ec6de1f (diff) | |
download | syn-7b7be61998ba3f906c18bb94fe73fc8b98fb1151.tar.gz |
Snap for 7483611 from 4b53745041c30d69b075a501e74cfb3a5ec6de1f to mainline-neuralnetworks-releaseandroid-mainline-12.0.0_r92android-mainline-12.0.0_r78android-mainline-12.0.0_r50android-mainline-12.0.0_r33android-mainline-12.0.0_r3android12-mainline-neuralnetworks-release
Change-Id: I75ddc367e830010b97cc33ebeed5d3e72fbb7b21
-rw-r--r-- | .cargo_vcs_info.json | 2 | ||||
-rw-r--r-- | 0.15.42/.cargo_vcs_info.json | 5 | ||||
-rw-r--r-- | 0.15.42/Android.bp | 31 | ||||
-rw-r--r-- | 0.15.42/Cargo.toml | 82 | ||||
-rw-r--r-- | 0.15.42/Cargo.toml.orig | 69 | ||||
-rw-r--r-- | 0.15.42/README.md | 270 | ||||
-rw-r--r-- | 0.15.42/benches/file.rs | 23 | ||||
-rw-r--r-- | 0.15.42/build.rs | 76 | ||||
-rw-r--r-- | 0.15.42/src/attr.rs | 680 | ||||
-rw-r--r-- | 0.15.42/src/buffer.rs | 370 | ||||
-rw-r--r-- | 0.15.42/src/custom_keyword.rs | 252 | ||||
-rw-r--r-- | 0.15.42/src/custom_punctuation.rs | 309 | ||||
-rw-r--r-- | 0.15.42/src/data.rs | 387 | ||||
-rw-r--r-- | 0.15.42/src/derive.rs | 258 | ||||
-rw-r--r-- | 0.15.42/src/discouraged.rs | 171 | ||||
-rw-r--r-- | 0.15.42/src/error.rs | 223 | ||||
-rw-r--r-- | 0.15.42/src/export.rs | 35 | ||||
-rw-r--r-- | 0.15.42/src/expr.rs | 3821 | ||||
-rw-r--r-- | 0.15.42/src/ext.rs | 145 | ||||
-rw-r--r-- | 0.15.42/src/file.rs | 113 | ||||
-rw-r--r-- | 0.15.42/src/gen/fold.rs | 2958 | ||||
-rw-r--r-- | 0.15.42/src/gen/visit.rs | 3372 | ||||
-rw-r--r-- | 0.15.42/src/gen/visit_mut.rs | 3279 | ||||
-rw-r--r-- | 0.15.42/src/gen_helper.rs | 154 | ||||
-rw-r--r-- | 0.15.42/src/generics.rs | 1132 | ||||
-rw-r--r-- | 0.15.42/src/group.rs | 286 | ||||
-rw-r--r-- | 0.15.42/src/ident.rs | 100 | ||||
-rw-r--r-- | 0.15.42/src/item.rs | 2771 | ||||
-rw-r--r-- | 0.15.42/src/lib.rs | 740 | ||||
-rw-r--r-- | 0.15.42/src/lifetime.rs | 155 | ||||
-rw-r--r-- | 0.15.42/src/lit.rs | 1106 | ||||
-rw-r--r-- | 0.15.42/src/lookahead.rs | 168 | ||||
-rw-r--r-- | 0.15.42/src/mac.rs | 239 | ||||
-rw-r--r-- | 0.15.42/src/macros.rs | 165 | ||||
-rw-r--r-- | 0.15.42/src/op.rs | 231 | ||||
-rw-r--r-- | 0.15.42/src/parse.rs | 1147 | ||||
-rw-r--r-- | 0.15.42/src/parse_macro_input.rs | 106 | ||||
-rw-r--r-- | 0.15.42/src/parse_quote.rs | 146 | ||||
-rw-r--r-- | 0.15.42/src/path.rs | 704 | ||||
-rw-r--r-- | 0.15.42/src/print.rs | 16 | ||||
-rw-r--r-- | 0.15.42/src/punctuated.rs | 836 | ||||
-rw-r--r-- | 0.15.42/src/spanned.rs | 144 | ||||
-rw-r--r-- | 0.15.42/src/thread.rs | 83 | ||||
-rw-r--r-- | 0.15.42/src/token.rs | 961 | ||||
-rw-r--r-- | 0.15.42/src/tt.rs | 110 | ||||
-rw-r--r-- | 0.15.42/src/ty.rs | 997 | ||||
-rwxr-xr-x | 0.15.42/tests/clone.sh | 16 | ||||
-rw-r--r-- | 0.15.42/tests/common/eq.rs | 458 | ||||
-rw-r--r-- | 0.15.42/tests/common/mod.rs | 14 | ||||
-rw-r--r-- | 0.15.42/tests/common/parse.rs | 49 | ||||
-rw-r--r-- | 0.15.42/tests/debug/gen.rs | 5934 | ||||
-rw-r--r-- | 0.15.42/tests/debug/mod.rs | 113 | ||||
-rw-r--r-- | 0.15.42/tests/features/error.rs | 1 | ||||
-rw-r--r-- | 0.15.42/tests/features/mod.rs | 22 | ||||
-rw-r--r-- | 0.15.42/tests/macros/mod.rs | 78 | ||||
-rw-r--r-- | 0.15.42/tests/repo/mod.rs | 54 | ||||
-rw-r--r-- | 0.15.42/tests/test_asyncness.rs | 41 | ||||
-rw-r--r-- | 0.15.42/tests/test_attribute.rs | 279 | ||||
-rw-r--r-- | 0.15.42/tests/test_derive_input.rs | 849 | ||||
-rw-r--r-- | 0.15.42/tests/test_expr.rs | 16 | ||||
-rw-r--r-- | 0.15.42/tests/test_generics.rs | 288 | ||||
-rw-r--r-- | 0.15.42/tests/test_grouping.rs | 58 | ||||
-rw-r--r-- | 0.15.42/tests/test_ident.rs | 90 | ||||
-rw-r--r-- | 0.15.42/tests/test_lit.rs | 190 | ||||
-rw-r--r-- | 0.15.42/tests/test_meta.rs | 180 | ||||
-rw-r--r-- | 0.15.42/tests/test_pat.rs | 23 | ||||
-rw-r--r-- | 0.15.42/tests/test_precedence.rs | 387 | ||||
-rw-r--r-- | 0.15.42/tests/test_round_trip.rs | 153 | ||||
-rw-r--r-- | 0.15.42/tests/test_should_parse.rs | 49 | ||||
-rw-r--r-- | 0.15.42/tests/test_token_trees.rs | 32 | ||||
-rw-r--r-- | 0.15.42/tests/zzz_stable.rs | 35 | ||||
-rw-r--r-- | 1.0.7/.cargo_vcs_info.json | 5 | ||||
-rw-r--r-- | 1.0.7/Android.bp | 29 | ||||
-rw-r--r-- | 1.0.7/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | 1.0.7/LICENSE-MIT | 23 | ||||
-rw-r--r-- | 1.0.7/benches/rust.rs | 147 | ||||
-rw-r--r-- | 1.0.7/src/keyword.rs | 0 | ||||
-rw-r--r-- | 1.0.7/src/sealed.rs | 4 | ||||
-rw-r--r-- | 1.0.7/src/span.rs | 67 | ||||
-rwxr-xr-x | 1.0.7/tests/clone.sh | 16 | ||||
-rw-r--r-- | 1.0.7/tests/common/eq.rs | 458 | ||||
-rw-r--r-- | 1.0.7/tests/common/mod.rs | 14 | ||||
-rw-r--r-- | 1.0.7/tests/features/error.rs | 1 | ||||
-rw-r--r-- | 1.0.7/tests/features/mod.rs | 22 | ||||
-rw-r--r-- | 1.0.7/tests/repo/mod.rs | 60 | ||||
-rw-r--r-- | 1.0.7/tests/test_expr.rs | 37 | ||||
-rw-r--r-- | 1.0.7/tests/test_parse_buffer.rs | 53 | ||||
-rw-r--r-- | 1.0.7/tests/test_pat.rs | 20 | ||||
-rw-r--r-- | 1.0.7/tests/test_round_trip.rs | 150 | ||||
-rw-r--r-- | Android.bp | 72 | ||||
-rw-r--r-- | Cargo.toml (renamed from 1.0.7/Cargo.toml) | 31 | ||||
-rw-r--r-- | Cargo.toml.orig (renamed from 1.0.7/Cargo.toml.orig) | 23 | ||||
l--------- | LICENSE | 1 | ||||
-rw-r--r-- | LICENSE-APACHE (renamed from 0.15.42/LICENSE-APACHE) | 0 | ||||
-rw-r--r-- | LICENSE-MIT (renamed from 0.15.42/LICENSE-MIT) | 0 | ||||
-rw-r--r-- | METADATA | 19 | ||||
-rw-r--r-- | MODULE_LICENSE_APACHE2 (renamed from 0.15.42/src/keyword.rs) | 0 | ||||
-rw-r--r-- | OWNERS | 1 | ||||
-rw-r--r-- | README.md (renamed from 1.0.7/README.md) | 16 | ||||
-rw-r--r-- | TEST_MAPPING | 221 | ||||
-rw-r--r-- | benches/file.rs (renamed from 1.0.7/benches/file.rs) | 7 | ||||
-rw-r--r-- | benches/rust.rs (renamed from 0.15.42/benches/rust.rs) | 45 | ||||
-rw-r--r-- | build.rs (renamed from 1.0.7/build.rs) | 42 | ||||
-rw-r--r-- | src/attr.rs (renamed from 1.0.7/src/attr.rs) | 161 | ||||
-rw-r--r-- | src/await.rs (renamed from 1.0.7/src/await.rs) | 2 | ||||
-rw-r--r-- | src/bigint.rs (renamed from 1.0.7/src/bigint.rs) | 0 | ||||
-rw-r--r-- | src/buffer.rs (renamed from 1.0.7/src/buffer.rs) | 60 | ||||
-rw-r--r-- | src/custom_keyword.rs (renamed from 1.0.7/src/custom_keyword.rs) | 63 | ||||
-rw-r--r-- | src/custom_punctuation.rs (renamed from 1.0.7/src/custom_punctuation.rs) | 87 | ||||
-rw-r--r-- | src/data.rs (renamed from 1.0.7/src/data.rs) | 115 | ||||
-rw-r--r-- | src/derive.rs (renamed from 1.0.7/src/derive.rs) | 29 | ||||
-rw-r--r-- | src/discouraged.rs (renamed from 1.0.7/src/discouraged.rs) | 27 | ||||
-rw-r--r-- | src/error.rs (renamed from 1.0.7/src/error.rs) | 97 | ||||
-rw-r--r-- | src/export.rs (renamed from 1.0.7/src/export.rs) | 2 | ||||
-rw-r--r-- | src/expr.rs (renamed from 1.0.7/src/expr.rs) | 1348 | ||||
-rw-r--r-- | src/ext.rs (renamed from 1.0.7/src/ext.rs) | 18 | ||||
-rw-r--r-- | src/file.rs (renamed from 1.0.7/src/file.rs) | 42 | ||||
-rw-r--r-- | src/gen/clone.rs | 2234 | ||||
-rw-r--r-- | src/gen/debug.rs | 3035 | ||||
-rw-r--r-- | src/gen/eq.rs | 2288 | ||||
-rw-r--r-- | src/gen/fold.rs (renamed from 1.0.7/src/gen/fold.rs) | 287 | ||||
-rw-r--r-- | src/gen/hash.rs | 2867 | ||||
-rw-r--r-- | src/gen/visit.rs (renamed from 1.0.7/src/gen/visit.rs) | 19 | ||||
-rw-r--r-- | src/gen/visit_mut.rs (renamed from 1.0.7/src/gen/visit_mut.rs) | 19 | ||||
-rw-r--r-- | src/gen_helper.rs (renamed from 1.0.7/src/gen_helper.rs) | 0 | ||||
-rw-r--r-- | src/generics.rs (renamed from 1.0.7/src/generics.rs) | 341 | ||||
-rw-r--r-- | src/group.rs (renamed from 1.0.7/src/group.rs) | 24 | ||||
-rw-r--r-- | src/ident.rs (renamed from 1.0.7/src/ident.rs) | 1 | ||||
-rw-r--r-- | src/item.rs (renamed from 1.0.7/src/item.rs) | 1729 | ||||
-rw-r--r-- | src/lib.rs (renamed from 1.0.7/src/lib.rs) | 140 | ||||
-rw-r--r-- | src/lifetime.rs (renamed from 1.0.7/src/lifetime.rs) | 32 | ||||
-rw-r--r-- | src/lit.rs (renamed from 1.0.7/src/lit.rs) | 772 | ||||
-rw-r--r-- | src/lookahead.rs (renamed from 1.0.7/src/lookahead.rs) | 6 | ||||
-rw-r--r-- | src/mac.rs (renamed from 1.0.7/src/mac.rs) | 62 | ||||
-rw-r--r-- | src/macros.rs (renamed from 1.0.7/src/macros.rs) | 53 | ||||
-rw-r--r-- | src/op.rs (renamed from 1.0.7/src/op.rs) | 13 | ||||
-rw-r--r-- | src/parse.rs (renamed from 1.0.7/src/parse.rs) | 246 | ||||
-rw-r--r-- | src/parse_macro_input.rs (renamed from 1.0.7/src/parse_macro_input.rs) | 83 | ||||
-rw-r--r-- | src/parse_quote.rs (renamed from 1.0.7/src/parse_quote.rs) | 24 | ||||
-rw-r--r-- | src/pat.rs (renamed from 1.0.7/src/pat.rs) | 409 | ||||
-rw-r--r-- | src/path.rs (renamed from 1.0.7/src/path.rs) | 214 | ||||
-rw-r--r-- | src/print.rs (renamed from 1.0.7/src/print.rs) | 0 | ||||
-rw-r--r-- | src/punctuated.rs (renamed from 1.0.7/src/punctuated.rs) | 172 | ||||
-rw-r--r-- | src/reserved.rs | 44 | ||||
-rw-r--r-- | src/sealed.rs (renamed from 0.15.42/src/sealed.rs) | 0 | ||||
-rw-r--r-- | src/span.rs (renamed from 0.15.42/src/span.rs) | 0 | ||||
-rw-r--r-- | src/spanned.rs (renamed from 1.0.7/src/spanned.rs) | 8 | ||||
-rw-r--r-- | src/stmt.rs (renamed from 1.0.7/src/stmt.rs) | 152 | ||||
-rw-r--r-- | src/thread.rs (renamed from 1.0.7/src/thread.rs) | 0 | ||||
-rw-r--r-- | src/token.rs (renamed from 1.0.7/src/token.rs) | 372 | ||||
-rw-r--r-- | src/tt.rs (renamed from 1.0.7/src/tt.rs) | 3 | ||||
-rw-r--r-- | src/ty.rs (renamed from 1.0.7/src/ty.rs) | 516 | ||||
-rw-r--r-- | src/verbatim.rs | 15 | ||||
-rw-r--r-- | src/whitespace.rs | 65 | ||||
-rw-r--r-- | tests/.gitignore | 1 | ||||
-rw-r--r-- | tests/common/eq.rs | 623 | ||||
-rw-r--r-- | tests/common/mod.rs | 27 | ||||
-rw-r--r-- | tests/common/parse.rs (renamed from 1.0.7/tests/common/parse.rs) | 24 | ||||
-rw-r--r-- | tests/debug/gen.rs (renamed from 1.0.7/tests/debug/gen.rs) | 74 | ||||
-rw-r--r-- | tests/debug/mod.rs (renamed from 1.0.7/tests/debug/mod.rs) | 10 | ||||
-rw-r--r-- | tests/macros/mod.rs (renamed from 1.0.7/tests/macros/mod.rs) | 1 | ||||
-rw-r--r-- | tests/repo/mod.rs | 130 | ||||
-rw-r--r-- | tests/repo/progress.rs | 37 | ||||
-rw-r--r-- | tests/test_asyncness.rs (renamed from 1.0.7/tests/test_asyncness.rs) | 2 | ||||
-rw-r--r-- | tests/test_attribute.rs (renamed from 1.0.7/tests/test_attribute.rs) | 44 | ||||
-rw-r--r-- | tests/test_derive_input.rs (renamed from 1.0.7/tests/test_derive_input.rs) | 14 | ||||
-rw-r--r-- | tests/test_expr.rs | 302 | ||||
-rw-r--r-- | tests/test_generics.rs (renamed from 1.0.7/tests/test_generics.rs) | 6 | ||||
-rw-r--r-- | tests/test_grouping.rs (renamed from 1.0.7/tests/test_grouping.rs) | 7 | ||||
-rw-r--r-- | tests/test_ident.rs (renamed from 1.0.7/tests/test_ident.rs) | 2 | ||||
-rw-r--r-- | tests/test_item.rs | 268 | ||||
-rw-r--r-- | tests/test_iterators.rs (renamed from 1.0.7/tests/test_iterators.rs) | 2 | ||||
-rw-r--r-- | tests/test_lit.rs (renamed from 1.0.7/tests/test_lit.rs) | 93 | ||||
-rw-r--r-- | tests/test_meta.rs (renamed from 1.0.7/tests/test_meta.rs) | 39 | ||||
-rw-r--r-- | tests/test_parse_buffer.rs (renamed from 0.15.42/tests/test_parse_buffer.rs) | 41 | ||||
-rw-r--r-- | tests/test_parse_stream.rs | 12 | ||||
-rw-r--r-- | tests/test_pat.rs | 67 | ||||
-rw-r--r-- | tests/test_path.rs | 104 | ||||
-rw-r--r-- | tests/test_precedence.rs (renamed from 1.0.7/tests/test_precedence.rs) | 213 | ||||
-rw-r--r-- | tests/test_receiver.rs (renamed from 1.0.7/tests/test_receiver.rs) | 44 | ||||
-rw-r--r-- | tests/test_round_trip.rs | 200 | ||||
-rw-r--r-- | tests/test_shebang.rs | 59 | ||||
-rw-r--r-- | tests/test_should_parse.rs (renamed from 1.0.7/tests/test_should_parse.rs) | 2 | ||||
-rw-r--r-- | tests/test_size.rs (renamed from 1.0.7/tests/test_size.rs) | 2 | ||||
-rw-r--r-- | tests/test_stmt.rs | 74 | ||||
-rw-r--r-- | tests/test_token_trees.rs (renamed from 1.0.7/tests/test_token_trees.rs) | 8 | ||||
-rw-r--r-- | tests/test_ty.rs | 219 | ||||
-rw-r--r-- | tests/test_visibility.rs | 148 | ||||
-rw-r--r-- | tests/zzz_stable.rs (renamed from 1.0.7/tests/zzz_stable.rs) | 2 |
189 files changed, 18344 insertions, 43475 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json index 86ad91ef..36a487f8 100644 --- a/.cargo_vcs_info.json +++ b/.cargo_vcs_info.json @@ -1,5 +1,5 @@ { "git": { - "sha1": "b48a2b922e19968c3335fa8fd5a27eadbfa4414f" + "sha1": "c80b47159a47340d20f5774d2fe1c09bd0994a13" } } diff --git a/0.15.42/.cargo_vcs_info.json b/0.15.42/.cargo_vcs_info.json deleted file mode 100644 index 86ad91ef..00000000 --- a/0.15.42/.cargo_vcs_info.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "git": { - "sha1": "b48a2b922e19968c3335fa8fd5a27eadbfa4414f" - } -} diff --git a/0.15.42/Android.bp b/0.15.42/Android.bp deleted file mode 100644 index ce244262..00000000 --- a/0.15.42/Android.bp +++ /dev/null @@ -1,31 +0,0 @@ -// This file is generated by cargo2android.py. - -rust_library_host_rlib { - name: "libsyn", - crate_name: "syn", - srcs: ["src/lib.rs"], - edition: "2015", - features: [ - "clone-impls", - "default", - "derive", - "full", - "parsing", - "printing", - "proc-macro", - "quote", - "visit-mut", - ], - flags: [ - "--cfg syn_can_call_macro_by_path", - "--cfg syn_can_match_trailing_dollar", - "--cfg syn_can_use_associated_constants", - "--cfg syn_can_use_thread_id", - "--cfg syn_disable_nightly_tests", - ], - rlibs: [ - "libproc_macro2", - "libquote", - "libunicode_xid", - ], -} diff --git a/0.15.42/Cargo.toml b/0.15.42/Cargo.toml deleted file mode 100644 index 4d756199..00000000 --- a/0.15.42/Cargo.toml +++ /dev/null @@ -1,82 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "syn" -version = "0.15.42" -authors = ["David Tolnay <dtolnay@gmail.com>"] -include = ["/benches/**", "/build.rs", "/Cargo.toml", "/LICENSE-APACHE", "/LICENSE-MIT", "/README.md", "/src/**", "/tests/**"] -description = "Parser for Rust source code" -documentation = "https://docs.rs/syn" -readme = "README.md" -categories = ["development-tools::procedural-macro-helpers"] -license = "MIT OR Apache-2.0" -repository = "https://github.com/dtolnay/syn" -[package.metadata.docs.rs] -all-features = true - -[package.metadata.playground] -all-features = true - -[[bench]] -name = "rust" -harness = false -required-features = ["full", "parsing"] -edition = "2018" - -[[bench]] -name = "file" -required-features = ["full", "parsing"] -edition = "2018" -[dependencies.proc-macro2] -version = "0.4.4" -default-features = false - -[dependencies.quote] -version = "0.6" -optional = true -default-features = false - -[dependencies.unicode-xid] -version = "0.1" -[dev-dependencies.insta] -version = "0.8" - -[dev-dependencies.rayon] -version = "1.0" - -[dev-dependencies.ref-cast] -version = "0.2" - -[dev-dependencies.regex] -version = "1.0" - -[dev-dependencies.termcolor] -version = "1.0" - -[dev-dependencies.walkdir] -version = "2.1" - -[features] -clone-impls = [] -default = ["derive", "parsing", "printing", "clone-impls", "proc-macro"] -derive = [] -extra-traits = [] -fold = [] -full = [] -parsing = [] -printing = ["quote"] -proc-macro = ["proc-macro2/proc-macro", "quote/proc-macro"] -visit = [] -visit-mut = [] -[badges.travis-ci] -repository = "dtolnay/syn" diff --git a/0.15.42/Cargo.toml.orig b/0.15.42/Cargo.toml.orig deleted file mode 100644 index b518df96..00000000 --- a/0.15.42/Cargo.toml.orig +++ /dev/null @@ -1,69 +0,0 @@ -[package] -name = "syn" -version = "0.15.42" # don't forget to update html_root_url and syn.json -authors = ["David Tolnay <dtolnay@gmail.com>"] -license = "MIT OR Apache-2.0" -description = "Parser for Rust source code" -repository = "https://github.com/dtolnay/syn" -documentation = "https://docs.rs/syn" -categories = ["development-tools::procedural-macro-helpers"] -readme = "README.md" -include = [ - "/benches/**", - "/build.rs", - "/Cargo.toml", - "/LICENSE-APACHE", - "/LICENSE-MIT", - "/README.md", - "/src/**", - "/tests/**", -] - -[features] -default = ["derive", "parsing", "printing", "clone-impls", "proc-macro"] -derive = [] -full = [] -parsing = [] -printing = ["quote"] -visit = [] -visit-mut = [] -fold = [] -clone-impls = [] -extra-traits = [] -proc-macro = ["proc-macro2/proc-macro", "quote/proc-macro"] - -[dependencies] -proc-macro2 = { version = "0.4.4", default-features = false } -quote = { version = "0.6", optional = true, default-features = false } -unicode-xid = "0.1" - -[dev-dependencies] -insta = "0.8" -rayon = "1.0" -ref-cast = "0.2" -regex = "1.0" -termcolor = "1.0" -walkdir = "2.1" - -[[bench]] -name = "rust" -edition = "2018" -harness = false -required-features = ["full", "parsing"] - -[[bench]] -name = "file" -edition = "2018" -required-features = ["full", "parsing"] - -[package.metadata.docs.rs] -all-features = true - -[package.metadata.playground] -all-features = true - -[badges] -travis-ci = { repository = "dtolnay/syn" } - -[workspace] -members = ["dev", "json"] diff --git a/0.15.42/README.md b/0.15.42/README.md deleted file mode 100644 index c71e5ee7..00000000 --- a/0.15.42/README.md +++ /dev/null @@ -1,270 +0,0 @@ -Parser for Rust source code -=========================== - -[![Build Status](https://api.travis-ci.org/dtolnay/syn.svg?branch=master)](https://travis-ci.org/dtolnay/syn) -[![Latest Version](https://img.shields.io/crates/v/syn.svg)](https://crates.io/crates/syn) -[![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/syn/0.15/syn/) -[![Rustc Version 1.15+](https://img.shields.io/badge/rustc-1.15+-lightgray.svg)](https://blog.rust-lang.org/2017/02/02/Rust-1.15.html) - -Syn is a parsing library for parsing a stream of Rust tokens into a syntax tree -of Rust source code. - -Currently this library is geared toward use in Rust procedural macros, but -contains some APIs that may be useful more generally. - -[custom derive]: https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md - -- **Data structures** — Syn provides a complete syntax tree that can represent - any valid Rust source code. The syntax tree is rooted at [`syn::File`] which - represents a full source file, but there are other entry points that may be - useful to procedural macros including [`syn::Item`], [`syn::Expr`] and - [`syn::Type`]. - -- **Custom derives** — Of particular interest to custom derives is - [`syn::DeriveInput`] which is any of the three legal input items to a derive - macro. An example below shows using this type in a library that can derive - implementations of a trait of your own. - -- **Parsing** — Parsing in Syn is built around [parser functions] with the - signature `fn(ParseStream) -> Result<T>`. Every syntax tree node defined by - Syn is individually parsable and may be used as a building block for custom - syntaxes, or you may dream up your own brand new syntax without involving any - of our syntax tree types. - -- **Location information** — Every token parsed by Syn is associated with a - `Span` that tracks line and column information back to the source of that - token. These spans allow a procedural macro to display detailed error messages - pointing to all the right places in the user's code. There is an example of - this below. - -- **Feature flags** — Functionality is aggressively feature gated so your - procedural macros enable only what they need, and do not pay in compile time - for all the rest. - -[`syn::File`]: https://docs.rs/syn/0.15/syn/struct.File.html -[`syn::Item`]: https://docs.rs/syn/0.15/syn/enum.Item.html -[`syn::Expr`]: https://docs.rs/syn/0.15/syn/enum.Expr.html -[`syn::Type`]: https://docs.rs/syn/0.15/syn/enum.Type.html -[`syn::DeriveInput`]: https://docs.rs/syn/0.15/syn/struct.DeriveInput.html -[parser functions]: https://docs.rs/syn/0.15/syn/parse/index.html - -If you get stuck with anything involving procedural macros in Rust I am happy to -provide help even if the issue is not related to Syn. Please file a ticket in -this repo. - -*Version requirement: Syn supports any compiler version back to Rust's very -first support for procedural macros in Rust 1.15.0. Some features especially -around error reporting are only available in newer compilers or on the nightly -channel.* - -[*Release notes*](https://github.com/dtolnay/syn/releases) - -## Example of a custom derive - -The canonical custom derive using Syn looks like this. We write an ordinary Rust -function tagged with a `proc_macro_derive` attribute and the name of the trait -we are deriving. Any time that derive appears in the user's code, the Rust -compiler passes their data structure as tokens into our macro. We get to execute -arbitrary Rust code to figure out what to do with those tokens, then hand some -tokens back to the compiler to compile into the user's crate. - -[`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html - -```toml -[dependencies] -syn = "0.15" -quote = "0.6" - -[lib] -proc-macro = true -``` - -```rust -extern crate proc_macro; - -use proc_macro::TokenStream; -use quote::quote; -use syn::{parse_macro_input, DeriveInput}; - -#[proc_macro_derive(MyMacro)] -pub fn my_macro(input: TokenStream) -> TokenStream { - // Parse the input tokens into a syntax tree - let input = parse_macro_input!(input as DeriveInput); - - // Build the output, possibly using quasi-quotation - let expanded = quote! { - // ... - }; - - // Hand the output tokens back to the compiler - TokenStream::from(expanded) -} -``` - -The [`heapsize`] example directory shows a complete working Macros 1.1 -implementation of a custom derive. It works on any Rust compiler 1.15+. The -example derives a `HeapSize` trait which computes an estimate of the amount of -heap memory owned by a value. - -[`heapsize`]: examples/heapsize - -```rust -pub trait HeapSize { - /// Total number of bytes of heap memory owned by `self`. - fn heap_size_of_children(&self) -> usize; -} -``` - -The custom derive allows users to write `#[derive(HeapSize)]` on data structures -in their program. - -```rust -#[derive(HeapSize)] -struct Demo<'a, T: ?Sized> { - a: Box<T>, - b: u8, - c: &'a str, - d: String, -} -``` - -## Spans and error reporting - -The token-based procedural macro API provides great control over where the -compiler's error messages are displayed in user code. Consider the error the -user sees if one of their field types does not implement `HeapSize`. - -```rust -#[derive(HeapSize)] -struct Broken { - ok: String, - bad: std::thread::Thread, -} -``` - -By tracking span information all the way through the expansion of a procedural -macro as shown in the `heapsize` example, token-based macros in Syn are able to -trigger errors that directly pinpoint the source of the problem. - -``` -error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied - --> src/main.rs:7:5 - | -7 | bad: std::thread::Thread, - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `std::thread::Thread` -``` - -## Parsing a custom syntax - -The [`lazy-static`] example directory shows the implementation of a -`functionlike!(...)` procedural macro in which the input tokens are parsed using -Syn's parsing API. - -[`lazy-static`]: examples/lazy-static - -The example reimplements the popular `lazy_static` crate from crates.io as a -procedural macro. - -``` -lazy_static! { - static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap(); -} -``` - -The implementation shows how to trigger custom warnings and error messages on -the macro input. - -``` -warning: come on, pick a more creative name - --> src/main.rs:10:16 - | -10 | static ref FOO: String = "lazy_static".to_owned(); - | ^^^ -``` - -## Testing - -When testing macros, we often care not just that the macro can be used -successfully but also that when the macro is provided with invalid input it -produces maximally helpful error messages. Consider using the [`trybuild`] crate -to write tests for errors that are emitted by your macro or errors detected by -the Rust compiler in the expanded code following misuse of the macro. Such tests -help avoid regressions from later refactors that mistakenly make an error no -longer trigger or be less helpful than it used to be. - -[`trybuild`]: https://github.com/dtolnay/trybuild - -## Debugging - -When developing a procedural macro it can be helpful to look at what the -generated code looks like. Use `cargo rustc -- -Zunstable-options ---pretty=expanded` or the [`cargo expand`] subcommand. - -[`cargo expand`]: https://github.com/dtolnay/cargo-expand - -To show the expanded code for some crate that uses your procedural macro, run -`cargo expand` from that crate. To show the expanded code for one of your own -test cases, run `cargo expand --test the_test_case` where the last argument is -the name of the test file without the `.rs` extension. - -This write-up by Brandon W Maister discusses debugging in more detail: -[Debugging Rust's new Custom Derive system][debugging]. - -[debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/ - -## Optional features - -Syn puts a lot of functionality behind optional features in order to optimize -compile time for the most common use cases. The following features are -available. - -- **`derive`** *(enabled by default)* — Data structures for representing the - possible input to a custom derive, including structs and enums and types. -- **`full`** — Data structures for representing the syntax tree of all valid - Rust source code, including items and expressions. -- **`parsing`** *(enabled by default)* — Ability to parse input tokens into a - syntax tree node of a chosen type. -- **`printing`** *(enabled by default)* — Ability to print a syntax tree node as - tokens of Rust source code. -- **`visit`** — Trait for traversing a syntax tree. -- **`visit-mut`** — Trait for traversing and mutating in place a syntax tree. -- **`fold`** — Trait for transforming an owned syntax tree. -- **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree - types. -- **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree - types. -- **`proc-macro`** *(enabled by default)* — Runtime dependency on the dynamic - library libproc_macro from rustc toolchain. - -## Proc macro shim - -Syn uses the [proc-macro2] crate to emulate the compiler's procedural macro API -in a stable way that works all the way back to Rust 1.15.0. This shim makes it -possible to write code without regard for whether the current compiler version -supports the features we use. - -In general all of your code should be written against proc-macro2 rather than -proc-macro. The one exception is in the signatures of procedural macro entry -points, which are required by the language to use `proc_macro::TokenStream`. - -The proc-macro2 crate will automatically detect and use the compiler's data -structures on sufficiently new compilers. - -[proc-macro2]: https://github.com/alexcrichton/proc-macro2 - -<br> - -#### License - -<sup> -Licensed under either of <a href="LICENSE-APACHE">Apache License, Version -2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option. -</sup> - -<br> - -<sub> -Unless you explicitly state otherwise, any contribution intentionally submitted -for inclusion in this crate by you, as defined in the Apache-2.0 license, shall -be dual licensed as above, without any additional terms or conditions. -</sub> diff --git a/0.15.42/benches/file.rs b/0.15.42/benches/file.rs deleted file mode 100644 index 08ecd909..00000000 --- a/0.15.42/benches/file.rs +++ /dev/null @@ -1,23 +0,0 @@ -// $ cargo bench --features full --bench file - -#![feature(rustc_private, test)] - -extern crate test; - -#[path = "../tests/repo/mod.rs"] -pub mod repo; - -use proc_macro2::TokenStream; -use std::fs; -use std::str::FromStr; -use test::Bencher; - -const FILE: &str = "tests/rust/src/libcore/str/mod.rs"; - -#[bench] -fn parse_file(b: &mut Bencher) { - repo::clone_rust(); - let content = fs::read_to_string(FILE).unwrap(); - let tokens = TokenStream::from_str(&content).unwrap(); - b.iter(|| syn::parse2::<syn::File>(tokens.clone())); -} diff --git a/0.15.42/build.rs b/0.15.42/build.rs deleted file mode 100644 index bbdb97e4..00000000 --- a/0.15.42/build.rs +++ /dev/null @@ -1,76 +0,0 @@ -use std::env; -use std::process::Command; -use std::str::{self, FromStr}; - -// 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() { - let compiler = match rustc_version() { - Some(compiler) => compiler, - None => return, - }; - - if compiler.minor >= 17 { - println!("cargo:rustc-cfg=syn_can_match_trailing_dollar"); - } - - if compiler.minor >= 19 { - println!("cargo:rustc-cfg=syn_can_use_thread_id"); - } - - if compiler.minor >= 20 { - println!("cargo:rustc-cfg=syn_can_use_associated_constants"); - } - - // Macro modularization allows re-exporting the `quote!` macro in 1.30+. - if compiler.minor >= 30 { - println!("cargo:rustc-cfg=syn_can_call_macro_by_path"); - } - - if !compiler.nightly { - println!("cargo:rustc-cfg=syn_disable_nightly_tests"); - } -} - -struct Compiler { - minor: u32, - nightly: bool, -} - -fn rustc_version() -> Option<Compiler> { - 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 mut pieces = version.split('.'); - if pieces.next() != Some("rustc 1") { - return None; - } - - let next = match pieces.next() { - Some(next) => next, - None => return None, - }; - - let minor = match u32::from_str(next) { - Ok(minor) => minor, - Err(_) => return None, - }; - - Some(Compiler { - minor: minor, - nightly: version.contains("nightly"), - }) -} diff --git a/0.15.42/src/attr.rs b/0.15.42/src/attr.rs deleted file mode 100644 index e0efb57c..00000000 --- a/0.15.42/src/attr.rs +++ /dev/null @@ -1,680 +0,0 @@ -use super::*; -use punctuated::Punctuated; - -use std::iter; - -use proc_macro2::TokenStream; -#[cfg(not(feature = "parsing"))] -use proc_macro2::{Delimiter, Spacing, TokenTree}; - -#[cfg(feature = "parsing")] -use parse::{ParseStream, Result}; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; -#[cfg(feature = "extra-traits")] -use tt::TokenStreamHelper; - -ast_struct! { - /// An attribute like `#[repr(transparent)]`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// # Syntax - /// - /// Rust has six types of attributes. - /// - /// - Outer attributes like `#[repr(transparent)]`. These appear outside or - /// in front of the item they describe. - /// - Inner attributes like `#![feature(proc_macro)]`. These appear inside - /// of the item they describe, usually a module. - /// - Outer doc comments like `/// # Example`. - /// - Inner doc comments like `//! Please file an issue`. - /// - Outer block comments `/** # Example */`. - /// - Inner block comments `/*! Please file an issue */`. - /// - /// The `style` field of type `AttrStyle` distinguishes whether an attribute - /// is outer or inner. Doc comments and block comments are promoted to - /// attributes, as this is how they are processed by the compiler and by - /// `macro_rules!` macros. - /// - /// The `path` field gives the possibly colon-delimited path against which - /// the attribute is resolved. It is equal to `"doc"` for desugared doc - /// comments. The `tts` field contains the rest of the attribute body as - /// tokens. - /// - /// ```text - /// #[derive(Copy)] #[crate::precondition x < 5] - /// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~ - /// path tts path tts - /// ``` - /// - /// Use the [`parse_meta`] method to try parsing the tokens of an attribute - /// into the structured representation that is used by convention across - /// most Rust libraries. - /// - /// [`parse_meta`]: Attribute::parse_meta - /// - /// # Parsing - /// - /// This type does not implement the [`Parse`] trait and thus cannot be - /// parsed directly by [`ParseStream::parse`]. Instead use - /// [`ParseStream::call`] with one of the two parser functions - /// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on - /// which you intend to parse. - /// - /// [`Parse`]: parse::Parse - /// [`ParseStream::parse`]: parse::ParseBuffer::parse - /// [`ParseStream::call`]: parse::ParseBuffer::call - /// - /// ```edition2018 - /// use syn::{Attribute, Ident, Result, Token}; - /// use syn::parse::{Parse, ParseStream}; - /// - /// // Parses a unit struct with attributes. - /// // - /// // #[path = "s.tmpl"] - /// // struct S; - /// struct UnitStruct { - /// attrs: Vec<Attribute>, - /// struct_token: Token![struct], - /// name: Ident, - /// semi_token: Token![;], - /// } - /// - /// impl Parse for UnitStruct { - /// fn parse(input: ParseStream) -> Result<Self> { - /// Ok(UnitStruct { - /// attrs: input.call(Attribute::parse_outer)?, - /// struct_token: input.parse()?, - /// name: input.parse()?, - /// semi_token: input.parse()?, - /// }) - /// } - /// } - /// ``` - pub struct Attribute #manual_extra_traits { - pub pound_token: Token![#], - pub style: AttrStyle, - pub bracket_token: token::Bracket, - pub path: Path, - pub tts: TokenStream, - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for Attribute {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Attribute { - fn eq(&self, other: &Self) -> bool { - self.style == other.style - && self.pound_token == other.pound_token - && self.bracket_token == other.bracket_token - && self.path == other.path - && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Attribute { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - self.style.hash(state); - self.pound_token.hash(state); - self.bracket_token.hash(state); - self.path.hash(state); - TokenStreamHelper(&self.tts).hash(state); - } -} - -impl Attribute { - /// Parses the content of the attribute, consisting of the path and tts, as - /// a [`Meta`] if possible. - /// - /// Deprecated; use `parse_meta` instead. - #[doc(hidden)] - pub fn interpret_meta(&self) -> Option<Meta> { - #[cfg(feature = "parsing")] - { - self.parse_meta().ok() - } - - #[cfg(not(feature = "parsing"))] - { - let name = if self.path.segments.len() == 1 { - &self.path.segments.first().unwrap().value().ident - } else { - return None; - }; - - if self.tts.is_empty() { - return Some(Meta::Word(name.clone())); - } - - let tts = self.tts.clone().into_iter().collect::<Vec<_>>(); - - if tts.len() == 1 { - if let Some(meta) = Attribute::extract_meta_list(name.clone(), &tts[0]) { - return Some(meta); - } - } - - if tts.len() == 2 { - if let Some(meta) = Attribute::extract_name_value(name.clone(), &tts[0], &tts[1]) { - return Some(meta); - } - } - - None - } - } - - /// Parses the content of the attribute, consisting of the path and tts, as - /// a [`Meta`] if possible. - #[cfg(feature = "parsing")] - pub fn parse_meta(&self) -> Result<Meta> { - if let Some(ref colon) = self.path.leading_colon { - return Err(Error::new(colon.spans[0], "expected meta identifier")); - } - - let first_segment = self - .path - .segments - .first() - .expect("paths have at least one segment"); - if let Some(colon) = first_segment.punct() { - return Err(Error::new(colon.spans[0], "expected meta value")); - } - let ident = first_segment.value().ident.clone(); - - let parser = |input: ParseStream| parsing::parse_meta_after_ident(ident, input); - parse::Parser::parse2(parser, self.tts.clone()) - } - - /// Parses zero or more outer attributes from the stream. - /// - /// *This function is available if Syn is built with the `"parsing"` - /// feature.* - #[cfg(feature = "parsing")] - pub fn parse_outer(input: ParseStream) -> Result<Vec<Self>> { - let mut attrs = Vec::new(); - while input.peek(Token![#]) { - attrs.push(input.call(parsing::single_parse_outer)?); - } - Ok(attrs) - } - - /// Parses zero or more inner attributes from the stream. - /// - /// *This function is available if Syn is built with the `"parsing"` - /// feature.* - #[cfg(feature = "parsing")] - pub fn parse_inner(input: ParseStream) -> Result<Vec<Self>> { - let mut attrs = Vec::new(); - while input.peek(Token![#]) && input.peek2(Token![!]) { - attrs.push(input.call(parsing::single_parse_inner)?); - } - Ok(attrs) - } - - #[cfg(not(feature = "parsing"))] - fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> { - let g = match *tt { - TokenTree::Group(ref g) => g, - _ => return None, - }; - if g.delimiter() != Delimiter::Parenthesis { - return None; - } - let tokens = g.stream().clone().into_iter().collect::<Vec<_>>(); - let nested = match list_of_nested_meta_items_from_tokens(&tokens) { - Some(n) => n, - None => return None, - }; - Some(Meta::List(MetaList { - paren_token: token::Paren(g.span()), - ident: ident, - nested: nested, - })) - } - - #[cfg(not(feature = "parsing"))] - fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> { - let a = match *a { - TokenTree::Punct(ref o) => o, - _ => return None, - }; - if a.spacing() != Spacing::Alone { - return None; - } - if a.as_char() != '=' { - return None; - } - - match *b { - TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => { - Some(Meta::NameValue(MetaNameValue { - ident: ident, - eq_token: Token![=]([a.span()]), - lit: Lit::new(l.clone()), - })) - } - TokenTree::Ident(ref v) => match &v.to_string()[..] { - v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue { - ident: ident, - eq_token: Token![=]([a.span()]), - lit: Lit::Bool(LitBool { - value: v == "true", - span: b.span(), - }), - })), - _ => None, - }, - _ => None, - } - } -} - -#[cfg(not(feature = "parsing"))] -fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> { - assert!(!tts.is_empty()); - - match tts[0] { - TokenTree::Literal(ref lit) => { - if lit.to_string().starts_with('/') { - None - } else { - let lit = Lit::new(lit.clone()); - Some((NestedMeta::Literal(lit), &tts[1..])) - } - } - - TokenTree::Ident(ref ident) => { - if tts.len() >= 3 { - if let Some(meta) = Attribute::extract_name_value(ident.clone(), &tts[1], &tts[2]) { - return Some((NestedMeta::Meta(meta), &tts[3..])); - } - } - - if tts.len() >= 2 { - if let Some(meta) = Attribute::extract_meta_list(ident.clone(), &tts[1]) { - return Some((NestedMeta::Meta(meta), &tts[2..])); - } - } - - let nested_meta = if ident == "true" || ident == "false" { - NestedMeta::Literal(Lit::Bool(LitBool { - value: ident == "true", - span: ident.span(), - })) - } else { - NestedMeta::Meta(Meta::Word(ident.clone())) - }; - Some((nested_meta, &tts[1..])) - } - - _ => None, - } -} - -#[cfg(not(feature = "parsing"))] -fn list_of_nested_meta_items_from_tokens( - mut tts: &[TokenTree], -) -> Option<Punctuated<NestedMeta, Token![,]>> { - let mut nested_meta_items = Punctuated::new(); - let mut first = true; - - while !tts.is_empty() { - let prev_comma = if first { - first = false; - None - } else if let TokenTree::Punct(ref op) = tts[0] { - if op.spacing() != Spacing::Alone { - return None; - } - if op.as_char() != ',' { - return None; - } - let tok = Token![,]([op.span()]); - tts = &tts[1..]; - if tts.is_empty() { - break; - } - Some(tok) - } else { - return None; - }; - let (nested, rest) = match nested_meta_item_from_tokens(tts) { - Some(pair) => pair, - None => return None, - }; - if let Some(comma) = prev_comma { - nested_meta_items.push_punct(comma); - } - nested_meta_items.push_value(nested); - tts = rest; - } - - Some(nested_meta_items) -} - -ast_enum! { - /// Distinguishes between attributes that decorate an item and attributes - /// that are contained within an item. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// # Outer attributes - /// - /// - `#[repr(transparent)]` - /// - `/// # Example` - /// - `/** Please file an issue */` - /// - /// # Inner attributes - /// - /// - `#![feature(proc_macro)]` - /// - `//! # Example` - /// - `/*! Please file an issue */` - #[cfg_attr(feature = "clone-impls", derive(Copy))] - pub enum AttrStyle { - Outer, - Inner(Token![!]), - } -} - -ast_enum_of_structs! { - /// Content of a compile-time structured attribute. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// ## Word - /// - /// A meta word is like the `test` in `#[test]`. - /// - /// ## List - /// - /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`. - /// - /// ## NameValue - /// - /// A name-value meta is like the `path = "..."` in `#[path = - /// "sys/windows.rs"]`. - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Meta { - pub Word(Ident), - /// A structured list within an attribute, like `derive(Copy, Clone)`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub List(MetaList { - pub ident: Ident, - pub paren_token: token::Paren, - pub nested: Punctuated<NestedMeta, Token![,]>, - }), - /// A name-value pair within an attribute, like `feature = "nightly"`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub NameValue(MetaNameValue { - pub ident: Ident, - pub eq_token: Token![=], - pub lit: Lit, - }), - } -} - -impl Meta { - /// Returns the identifier that begins this structured meta item. - /// - /// For example this would return the `test` in `#[test]`, the `derive` in - /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`. - pub fn name(&self) -> Ident { - match *self { - Meta::Word(ref meta) => meta.clone(), - Meta::List(ref meta) => meta.ident.clone(), - Meta::NameValue(ref meta) => meta.ident.clone(), - } - } -} - -ast_enum_of_structs! { - /// Element of a compile-time attribute list. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum NestedMeta { - /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which - /// would be a nested `Meta::Word`. - pub Meta(Meta), - - /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`. - pub Literal(Lit), - } -} - -/// Conventional argument type associated with an invocation of an attribute -/// macro. -/// -/// For example if we are developing an attribute macro that is intended to be -/// invoked on function items as follows: -/// -/// ```edition2018 -/// # const IGNORE: &str = stringify! { -/// #[my_attribute(path = "/v1/refresh")] -/// # }; -/// pub fn refresh() { -/// /* ... */ -/// } -/// ``` -/// -/// The implementation of this macro would want to parse its attribute arguments -/// as type `AttributeArgs`. -/// -/// ```edition2018 -/// extern crate proc_macro; -/// -/// use proc_macro::TokenStream; -/// use syn::{parse_macro_input, AttributeArgs, ItemFn}; -/// -/// # const IGNORE: &str = stringify! { -/// #[proc_macro_attribute] -/// # }; -/// pub fn my_attribute(args: TokenStream, input: TokenStream) -> TokenStream { -/// let args = parse_macro_input!(args as AttributeArgs); -/// let input = parse_macro_input!(input as ItemFn); -/// -/// /* ... */ -/// # "".parse().unwrap() -/// } -/// ``` -pub type AttributeArgs = Vec<NestedMeta>; - -pub trait FilterAttrs<'a> { - type Ret: Iterator<Item = &'a Attribute>; - - fn outer(self) -> Self::Ret; - fn inner(self) -> Self::Ret; -} - -impl<'a, T> FilterAttrs<'a> for T -where - T: IntoIterator<Item = &'a Attribute>, -{ - type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>; - - fn outer(self) -> Self::Ret { - #[cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))] - fn is_outer(attr: &&Attribute) -> bool { - match attr.style { - AttrStyle::Outer => true, - _ => false, - } - } - self.into_iter().filter(is_outer) - } - - fn inner(self) -> Self::Ret { - #[cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))] - fn is_inner(attr: &&Attribute) -> bool { - match attr.style { - AttrStyle::Inner(_) => true, - _ => false, - } - } - self.into_iter().filter(is_inner) - } -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use ext::IdentExt; - use parse::{Parse, ParseStream, Result}; - #[cfg(feature = "full")] - use private; - - pub fn single_parse_inner(input: ParseStream) -> Result<Attribute> { - let content; - Ok(Attribute { - pound_token: input.parse()?, - style: AttrStyle::Inner(input.parse()?), - bracket_token: bracketed!(content in input), - path: content.call(Path::parse_mod_style)?, - tts: content.parse()?, - }) - } - - pub fn single_parse_outer(input: ParseStream) -> Result<Attribute> { - let content; - Ok(Attribute { - pound_token: input.parse()?, - style: AttrStyle::Outer, - bracket_token: bracketed!(content in input), - path: content.call(Path::parse_mod_style)?, - tts: content.parse()?, - }) - } - - #[cfg(feature = "full")] - impl private { - pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> { - let mut attrs = outer; - attrs.extend(inner); - attrs - } - } - - impl Parse for Meta { - fn parse(input: ParseStream) -> Result<Self> { - let ident = input.call(Ident::parse_any)?; - parse_meta_after_ident(ident, input) - } - } - - impl Parse for MetaList { - fn parse(input: ParseStream) -> Result<Self> { - let ident = input.call(Ident::parse_any)?; - parse_meta_list_after_ident(ident, input) - } - } - - impl Parse for MetaNameValue { - fn parse(input: ParseStream) -> Result<Self> { - let ident = input.call(Ident::parse_any)?; - parse_meta_name_value_after_ident(ident, input) - } - } - - impl Parse for NestedMeta { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Lit) && !(input.peek(LitBool) && input.peek2(Token![=])) { - input.parse().map(NestedMeta::Literal) - } else if private::peek_any_ident(input) { - input.parse().map(NestedMeta::Meta) - } else { - Err(input.error("expected identifier or literal")) - } - } - } - - pub fn parse_meta_after_ident(ident: Ident, input: ParseStream) -> Result<Meta> { - if input.peek(token::Paren) { - parse_meta_list_after_ident(ident, input).map(Meta::List) - } else if input.peek(Token![=]) { - parse_meta_name_value_after_ident(ident, input).map(Meta::NameValue) - } else { - Ok(Meta::Word(ident)) - } - } - - fn parse_meta_list_after_ident(ident: Ident, input: ParseStream) -> Result<MetaList> { - let content; - Ok(MetaList { - ident: ident, - paren_token: parenthesized!(content in input), - nested: content.parse_terminated(NestedMeta::parse)?, - }) - } - - fn parse_meta_name_value_after_ident( - ident: Ident, - input: ParseStream, - ) -> Result<MetaNameValue> { - Ok(MetaNameValue { - ident: ident, - eq_token: input.parse()?, - lit: input.parse()?, - }) - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - use proc_macro2::TokenStream; - use quote::ToTokens; - - impl ToTokens for Attribute { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.pound_token.to_tokens(tokens); - if let AttrStyle::Inner(ref b) = self.style { - b.to_tokens(tokens); - } - self.bracket_token.surround(tokens, |tokens| { - self.path.to_tokens(tokens); - self.tts.to_tokens(tokens); - }); - } - } - - impl ToTokens for MetaList { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.ident.to_tokens(tokens); - self.paren_token.surround(tokens, |tokens| { - self.nested.to_tokens(tokens); - }) - } - } - - impl ToTokens for MetaNameValue { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.ident.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.lit.to_tokens(tokens); - } - } -} diff --git a/0.15.42/src/buffer.rs b/0.15.42/src/buffer.rs deleted file mode 100644 index a13d683a..00000000 --- a/0.15.42/src/buffer.rs +++ /dev/null @@ -1,370 +0,0 @@ -//! A stably addressed token buffer supporting efficient traversal based on a -//! cheaply copyable cursor. -//! -//! *This module is available if Syn is built with the `"parsing"` feature.* - -// This module is heavily commented as it contains most of the unsafe code in -// Syn, and caution should be used when editing it. The public-facing interface -// is 100% safe but the implementation is fragile internally. - -#[cfg(all( - not(all(target_arch = "wasm32", target_os = "unknown")), - feature = "proc-macro" -))] -use proc_macro as pm; -use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; - -use std::marker::PhantomData; -use std::ptr; - -use private; -use Lifetime; - -/// Internal type which is used instead of `TokenTree` to represent a token tree -/// within a `TokenBuffer`. -enum Entry { - // Mimicking types from proc-macro. - Group(Group, TokenBuffer), - Ident(Ident), - Punct(Punct), - Literal(Literal), - // End entries contain a raw pointer to the entry from the containing - // token tree, or null if this is the outermost level. - End(*const Entry), -} - -/// A buffer that can be efficiently traversed multiple times, unlike -/// `TokenStream` which requires a deep copy in order to traverse more than -/// once. -/// -/// *This type is available if Syn is built with the `"parsing"` feature.* -pub struct TokenBuffer { - // NOTE: Do not derive clone on this - there are raw pointers inside which - // will be messed up. Moving the `TokenBuffer` itself is safe as the actual - // backing slices won't be moved. - data: Box<[Entry]>, -} - -impl TokenBuffer { - // NOTE: DO NOT MUTATE THE `Vec` RETURNED FROM THIS FUNCTION ONCE IT - // RETURNS, THE ADDRESS OF ITS BACKING MEMORY MUST REMAIN STABLE. - fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer { - // Build up the entries list, recording the locations of any Groups - // in the list to be processed later. - let mut entries = Vec::new(); - let mut seqs = Vec::new(); - for tt in stream { - match tt { - TokenTree::Ident(sym) => { - entries.push(Entry::Ident(sym)); - } - TokenTree::Punct(op) => { - entries.push(Entry::Punct(op)); - } - TokenTree::Literal(l) => { - entries.push(Entry::Literal(l)); - } - TokenTree::Group(g) => { - // Record the index of the interesting entry, and store an - // `End(null)` there temporarially. - seqs.push((entries.len(), g)); - entries.push(Entry::End(ptr::null())); - } - } - } - // Add an `End` entry to the end with a reference to the enclosing token - // stream which was passed in. - entries.push(Entry::End(up)); - - // NOTE: This is done to ensure that we don't accidentally modify the - // length of the backing buffer. The backing buffer must remain at a - // constant address after this point, as we are going to store a raw - // pointer into it. - let mut entries = entries.into_boxed_slice(); - for (idx, group) in seqs { - // We know that this index refers to one of the temporary - // `End(null)` entries, and we know that the last entry is - // `End(up)`, so the next index is also valid. - let seq_up = &entries[idx + 1] as *const Entry; - - // The end entry stored at the end of this Entry::Group should - // point to the Entry which follows the Group in the list. - let inner = Self::inner_new(group.stream(), seq_up); - entries[idx] = Entry::Group(group, inner); - } - - TokenBuffer { data: entries } - } - - /// Creates a `TokenBuffer` containing all the tokens from the input - /// `TokenStream`. - /// - /// *This method is available if Syn is built with both the `"parsing"` and - /// `"proc-macro"` features.* - #[cfg(all( - not(all(target_arch = "wasm32", target_os = "unknown")), - feature = "proc-macro" - ))] - pub fn new(stream: pm::TokenStream) -> TokenBuffer { - Self::new2(stream.into()) - } - - /// Creates a `TokenBuffer` containing all the tokens from the input - /// `TokenStream`. - pub fn new2(stream: TokenStream) -> TokenBuffer { - Self::inner_new(stream, ptr::null()) - } - - /// Creates a cursor referencing the first token in the buffer and able to - /// traverse until the end of the buffer. - pub fn begin(&self) -> Cursor { - unsafe { Cursor::create(&self.data[0], &self.data[self.data.len() - 1]) } - } -} - -/// A cheaply copyable cursor into a `TokenBuffer`. -/// -/// This cursor holds a shared reference into the immutable data which is used -/// internally to represent a `TokenStream`, and can be efficiently manipulated -/// and copied around. -/// -/// An empty `Cursor` can be created directly, or one may create a `TokenBuffer` -/// object and get a cursor to its first token with `begin()`. -/// -/// Two cursors are equal if they have the same location in the same input -/// stream, and have the same scope. -/// -/// *This type is available if Syn is built with the `"parsing"` feature.* -#[derive(Copy, Clone, Eq, PartialEq)] -pub struct Cursor<'a> { - // The current entry which the `Cursor` is pointing at. - ptr: *const Entry, - // This is the only `Entry::End(..)` object which this cursor is allowed to - // point at. All other `End` objects are skipped over in `Cursor::create`. - scope: *const Entry, - // Cursor is covariant in 'a. This field ensures that our pointers are still - // valid. - marker: PhantomData<&'a Entry>, -} - -impl<'a> Cursor<'a> { - /// Creates a cursor referencing a static empty TokenStream. - pub fn empty() -> Self { - // It's safe in this situation for us to put an `Entry` object in global - // storage, despite it not actually being safe to send across threads - // (`Ident` is a reference into a thread-local table). This is because - // this entry never includes a `Ident` object. - // - // This wrapper struct allows us to break the rules and put a `Sync` - // object in global storage. - struct UnsafeSyncEntry(Entry); - unsafe impl Sync for UnsafeSyncEntry {} - static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry)); - - Cursor { - ptr: &EMPTY_ENTRY.0, - scope: &EMPTY_ENTRY.0, - marker: PhantomData, - } - } - - /// This create method intelligently exits non-explicitly-entered - /// `None`-delimited scopes when the cursor reaches the end of them, - /// allowing for them to be treated transparently. - unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self { - // NOTE: If we're looking at a `End(..)`, we want to advance the cursor - // past it, unless `ptr == scope`, which means that we're at the edge of - // our cursor's scope. We should only have `ptr != scope` at the exit - // from None-delimited groups entered with `ignore_none`. - while let Entry::End(exit) = *ptr { - if ptr == scope { - break; - } - ptr = exit; - } - - Cursor { - ptr: ptr, - scope: scope, - marker: PhantomData, - } - } - - /// Get the current entry. - fn entry(self) -> &'a Entry { - unsafe { &*self.ptr } - } - - /// Bump the cursor to point at the next token after the current one. This - /// is undefined behavior if the cursor is currently looking at an - /// `Entry::End`. - unsafe fn bump(self) -> Cursor<'a> { - Cursor::create(self.ptr.offset(1), self.scope) - } - - /// If the cursor is looking at a `None`-delimited group, move it to look at - /// the first token inside instead. If the group is empty, this will move - /// the cursor past the `None`-delimited group. - /// - /// WARNING: This mutates its argument. - fn ignore_none(&mut self) { - if let Entry::Group(ref group, ref buf) = *self.entry() { - if group.delimiter() == Delimiter::None { - // NOTE: We call `Cursor::create` here to make sure that - // situations where we should immediately exit the span after - // entering it are handled correctly. - unsafe { - *self = Cursor::create(&buf.data[0], self.scope); - } - } - } - } - - /// Checks whether the cursor is currently pointing at the end of its valid - /// scope. - #[inline] - pub fn eof(self) -> bool { - // We're at eof if we're at the end of our scope. - 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>, Span, 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(ref group, ref buf) = *self.entry() { - if group.delimiter() == delim { - return Some((buf.begin(), group.span(), unsafe { self.bump() })); - } - } - - 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>)> { - self.ignore_none(); - match *self.entry() { - Entry::Ident(ref ident) => Some((ident.clone(), unsafe { self.bump() })), - _ => None, - } - } - - /// If the cursor is pointing at an `Punct`, returns it along with a cursor - /// pointing at the next `TokenTree`. - pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> { - self.ignore_none(); - match *self.entry() { - Entry::Punct(ref op) if op.as_char() != '\'' => { - Some((op.clone(), unsafe { self.bump() })) - } - _ => None, - } - } - - /// If the cursor is pointing at a `Literal`, return it along with a cursor - /// pointing at the next `TokenTree`. - pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> { - self.ignore_none(); - match *self.entry() { - Entry::Literal(ref lit) => Some((lit.clone(), unsafe { self.bump() })), - _ => None, - } - } - - /// If the cursor is pointing at a `Lifetime`, returns it along with a - /// cursor pointing at the next `TokenTree`. - pub fn lifetime(mut self) -> Option<(Lifetime, Cursor<'a>)> { - self.ignore_none(); - match *self.entry() { - Entry::Punct(ref op) if op.as_char() == '\'' && op.spacing() == Spacing::Joint => { - let next = unsafe { self.bump() }; - match next.ident() { - Some((ident, rest)) => { - let lifetime = Lifetime { - apostrophe: op.span(), - ident: ident, - }; - Some((lifetime, rest)) - } - None => None, - } - } - _ => None, - } - } - - /// Copies all remaining tokens visible from this cursor into a - /// `TokenStream`. - pub fn token_stream(self) -> TokenStream { - let mut tts = Vec::new(); - let mut cursor = self; - while let Some((tt, rest)) = cursor.token_tree() { - tts.push(tt); - cursor = rest; - } - tts.into_iter().collect() - } - - /// If the cursor is pointing at a `TokenTree`, returns it along with a - /// cursor pointing at the next `TokenTree`. - /// - /// Returns `None` if the cursor has reached the end of its stream. - /// - /// This method does not treat `None`-delimited groups as transparent, and - /// will return a `Group(None, ..)` if the cursor is looking at one. - pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> { - let tree = match *self.entry() { - Entry::Group(ref group, _) => group.clone().into(), - Entry::Literal(ref lit) => lit.clone().into(), - Entry::Ident(ref ident) => ident.clone().into(), - Entry::Punct(ref op) => op.clone().into(), - Entry::End(..) => { - return None; - } - }; - - Some((tree, unsafe { self.bump() })) - } - - /// Returns the `Span` of the current token, or `Span::call_site()` if this - /// cursor points to eof. - pub fn span(self) -> Span { - match *self.entry() { - Entry::Group(ref group, _) => group.span(), - Entry::Literal(ref l) => l.span(), - Entry::Ident(ref t) => t.span(), - Entry::Punct(ref o) => o.span(), - Entry::End(..) => Span::call_site(), - } - } -} - -impl private { - pub fn same_scope(a: Cursor, b: Cursor) -> bool { - a.scope == b.scope - } - - #[cfg(procmacro2_semver_exempt)] - pub fn open_span_of_group(cursor: Cursor) -> Span { - match *cursor.entry() { - Entry::Group(ref group, _) => group.span_open(), - _ => cursor.span(), - } - } - - #[cfg(procmacro2_semver_exempt)] - pub fn close_span_of_group(cursor: Cursor) -> Span { - match *cursor.entry() { - Entry::Group(ref group, _) => group.span_close(), - _ => cursor.span(), - } - } -} diff --git a/0.15.42/src/custom_keyword.rs b/0.15.42/src/custom_keyword.rs deleted file mode 100644 index f4515c68..00000000 --- a/0.15.42/src/custom_keyword.rs +++ /dev/null @@ -1,252 +0,0 @@ -/// Define a type that supports parsing and printing a given identifier as if it -/// were a keyword. -/// -/// # Usage -/// -/// As a convention, it is recommended that this macro be invoked within a -/// module called `kw` or `keyword` and that the resulting parser be invoked -/// with a `kw::` or `keyword::` prefix. -/// -/// ```edition2018 -/// mod kw { -/// syn::custom_keyword!(whatever); -/// } -/// ``` -/// -/// The generated syntax tree node supports the following operations just like -/// any built-in keyword token. -/// -/// - [Peeking] — `input.peek(kw::whatever)` -/// -/// - [Parsing] — `input.parse::<kw::whatever>()?` -/// -/// - [Printing] — `quote!( ... #whatever_token ... )` -/// -/// - Construction from a [`Span`] — `let whatever_token = kw::whatever(sp)` -/// -/// - Field access to its span — `let sp = whatever_token.span` -/// -/// [Peeking]: parse::ParseBuffer::peek -/// [Parsing]: parse::ParseBuffer::parse -/// [Printing]: quote::ToTokens -/// [`Span`]: proc_macro2::Span -/// -/// # Example -/// -/// This example parses input that looks like `bool = true` or `str = "value"`. -/// The key must be either the identifier `bool` or the identifier `str`. If -/// `bool`, the value may be either `true` or `false`. If `str`, the value may -/// be any string literal. -/// -/// The symbols `bool` and `str` are not reserved keywords in Rust so these are -/// not considered keywords in the `syn::token` module. Like any other -/// identifier that is not a keyword, these can be declared as custom keywords -/// by crates that need to use them as such. -/// -/// ```edition2018 -/// use syn::{LitBool, LitStr, Result, Token}; -/// use syn::parse::{Parse, ParseStream}; -/// -/// mod kw { -/// syn::custom_keyword!(bool); -/// syn::custom_keyword!(str); -/// } -/// -/// enum Argument { -/// Bool { -/// bool_token: kw::bool, -/// eq_token: Token![=], -/// value: LitBool, -/// }, -/// Str { -/// str_token: kw::str, -/// eq_token: Token![=], -/// value: LitStr, -/// }, -/// } -/// -/// impl Parse for Argument { -/// fn parse(input: ParseStream) -> Result<Self> { -/// let lookahead = input.lookahead1(); -/// if lookahead.peek(kw::bool) { -/// Ok(Argument::Bool { -/// bool_token: input.parse::<kw::bool>()?, -/// eq_token: input.parse()?, -/// value: input.parse()?, -/// }) -/// } else if lookahead.peek(kw::str) { -/// Ok(Argument::Str { -/// str_token: input.parse::<kw::str>()?, -/// eq_token: input.parse()?, -/// value: input.parse()?, -/// }) -/// } else { -/// Err(lookahead.error()) -/// } -/// } -/// } -/// ``` -#[macro_export(local_inner_macros)] -macro_rules! custom_keyword { - ($ident:ident) => { - #[allow(non_camel_case_types)] - pub struct $ident { - pub span: $crate::export::Span, - } - - #[doc(hidden)] - #[allow(non_snake_case)] - pub fn $ident<__S: $crate::export::IntoSpans<[$crate::export::Span; 1]>>( - span: __S, - ) -> $ident { - $ident { - span: $crate::export::IntoSpans::into_spans(span)[0], - } - } - - impl $crate::export::Default for $ident { - fn default() -> Self { - $ident { - span: $crate::export::Span::call_site(), - } - } - } - - impl_parse_for_custom_keyword!($ident); - impl_to_tokens_for_custom_keyword!($ident); - impl_clone_for_custom_keyword!($ident); - impl_extra_traits_for_custom_keyword!($ident); - }; -} - -// Not public API. -#[cfg(feature = "parsing")] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_parse_for_custom_keyword { - ($ident:ident) => { - // For peek. - impl $crate::token::CustomToken for $ident { - fn peek(cursor: $crate::buffer::Cursor) -> $crate::export::bool { - if let Some((ident, _rest)) = cursor.ident() { - ident == stringify!($ident) - } else { - false - } - } - - fn display() -> &'static $crate::export::str { - concat!("`", stringify!($ident), "`") - } - } - - impl $crate::parse::Parse for $ident { - fn parse(input: $crate::parse::ParseStream) -> $crate::parse::Result<$ident> { - input.step(|cursor| { - if let $crate::export::Some((ident, rest)) = cursor.ident() { - if ident == stringify!($ident) { - return $crate::export::Ok(($ident { span: ident.span() }, rest)); - } - } - $crate::export::Err(cursor.error(concat!( - "expected `", - stringify!($ident), - "`" - ))) - }) - } - } - }; -} - -// Not public API. -#[cfg(not(feature = "parsing"))] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_parse_for_custom_keyword { - ($ident:ident) => {}; -} - -// Not public API. -#[cfg(feature = "printing")] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_to_tokens_for_custom_keyword { - ($ident:ident) => { - impl $crate::export::ToTokens for $ident { - fn to_tokens(&self, tokens: &mut $crate::export::TokenStream2) { - let ident = $crate::Ident::new(stringify!($ident), self.span); - $crate::export::TokenStreamExt::append(tokens, ident); - } - } - }; -} - -// Not public API. -#[cfg(not(feature = "printing"))] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_to_tokens_for_custom_keyword { - ($ident:ident) => {}; -} - -// Not public API. -#[cfg(feature = "clone-impls")] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_clone_for_custom_keyword { - ($ident:ident) => { - impl $crate::export::Copy for $ident {} - - impl $crate::export::Clone for $ident { - fn clone(&self) -> Self { - *self - } - } - }; -} - -// Not public API. -#[cfg(not(feature = "clone-impls"))] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_clone_for_custom_keyword { - ($ident:ident) => {}; -} - -// Not public API. -#[cfg(feature = "extra-traits")] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_extra_traits_for_custom_keyword { - ($ident:ident) => { - impl $crate::export::Debug for $ident { - fn fmt(&self, f: &mut $crate::export::Formatter) -> $crate::export::fmt::Result { - $crate::export::Formatter::write_str( - f, - concat!("Keyword [", stringify!($ident), "]"), - ) - } - } - - impl $crate::export::Eq for $ident {} - - impl $crate::export::PartialEq for $ident { - fn eq(&self, _other: &Self) -> $crate::export::bool { - true - } - } - - impl $crate::export::Hash for $ident { - fn hash<__H: $crate::export::Hasher>(&self, _state: &mut __H) {} - } - }; -} - -// Not public API. -#[cfg(not(feature = "extra-traits"))] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_extra_traits_for_custom_keyword { - ($ident:ident) => {}; -} diff --git a/0.15.42/src/custom_punctuation.rs b/0.15.42/src/custom_punctuation.rs deleted file mode 100644 index 62aa2ff8..00000000 --- a/0.15.42/src/custom_punctuation.rs +++ /dev/null @@ -1,309 +0,0 @@ -/// Define a type that supports parsing and printing a multi-character symbol -/// as if it were a punctuation token. -/// -/// # Usage -/// -/// ```edition2018 -/// syn::custom_punctuation!(LeftRightArrow, <=>); -/// ``` -/// -/// The generated syntax tree node supports the following operations just like -/// any built-in punctuation token. -/// -/// - [Peeking] — `input.peek(LeftRightArrow)` -/// -/// - [Parsing] — `input.parse::<LeftRightArrow>()?` -/// -/// - [Printing] — `quote!( ... #lrarrow ... )` -/// -/// - Construction from a [`Span`] — `let lrarrow = LeftRightArrow(sp)` -/// -/// - Construction from multiple [`Span`] — `let lrarrow = LeftRightArrow([sp, sp, sp])` -/// -/// - Field access to its spans — `let spans = lrarrow.spans` -/// -/// [Peeking]: parse::ParseBuffer::peek -/// [Parsing]: parse::ParseBuffer::parse -/// [Printing]: quote::ToTokens -/// [`Span`]: proc_macro2::Span -/// -/// # Example -/// -/// ```edition2018 -/// use proc_macro2::{TokenStream, TokenTree}; -/// use syn::parse::{Parse, ParseStream, Peek, Result}; -/// use syn::punctuated::Punctuated; -/// use syn::Expr; -/// -/// syn::custom_punctuation!(PathSeparator, </>); -/// -/// // expr </> expr </> expr ... -/// struct PathSegments { -/// segments: Punctuated<Expr, PathSeparator>, -/// } -/// -/// impl Parse for PathSegments { -/// fn parse(input: ParseStream) -> Result<Self> { -/// let mut segments = Punctuated::new(); -/// -/// let first = parse_until(input, PathSeparator)?; -/// segments.push_value(syn::parse2(first)?); -/// -/// while input.peek(PathSeparator) { -/// segments.push_punct(input.parse()?); -/// -/// let next = parse_until(input, PathSeparator)?; -/// segments.push_value(syn::parse2(next)?); -/// } -/// -/// Ok(PathSegments { segments }) -/// } -/// } -/// -/// fn parse_until<E: Peek>(input: ParseStream, end: E) -> Result<TokenStream> { -/// let mut tokens = TokenStream::new(); -/// while !input.is_empty() && !input.peek(end) { -/// let next: TokenTree = input.parse()?; -/// tokens.extend(Some(next)); -/// } -/// Ok(tokens) -/// } -/// -/// fn main() { -/// let input = r#" a::b </> c::d::e "#; -/// let _: PathSegments = syn::parse_str(input).unwrap(); -/// } -/// ``` -#[macro_export(local_inner_macros)] -macro_rules! custom_punctuation { - ($ident:ident, $($tt:tt)+) => { - pub struct $ident { - pub spans: custom_punctuation_repr!($($tt)+), - } - - #[doc(hidden)] - #[allow(non_snake_case)] - pub fn $ident<__S: $crate::export::IntoSpans<custom_punctuation_repr!($($tt)+)>>( - spans: __S, - ) -> $ident { - let _validate_len = 0 $(+ custom_punctuation_len!(strict, $tt))*; - $ident { - spans: $crate::export::IntoSpans::into_spans(spans) - } - } - - impl $crate::export::Default for $ident { - fn default() -> Self { - $ident($crate::export::Span::call_site()) - } - } - - impl_parse_for_custom_punctuation!($ident, $($tt)+); - impl_to_tokens_for_custom_punctuation!($ident, $($tt)+); - impl_clone_for_custom_punctuation!($ident, $($tt)+); - impl_extra_traits_for_custom_punctuation!($ident, $($tt)+); - }; -} - -// Not public API. -#[cfg(feature = "parsing")] -#[doc(hidden)] -#[macro_export(local_inner_macros)] -macro_rules! impl_parse_for_custom_punctuation { - ($ident:ident, $($tt:tt)+) => { - impl $crate::token::CustomToken for $ident { - fn peek(cursor: $crate::buffer::Cursor) -> bool { - $crate::token::parsing::peek_punct(cursor, stringify_punct!($($tt)+)) - } - - fn display() -> &'static $crate::export::str { - custom_punctuation_concat!("`", stringify_punct!($($tt)+), "`") - } - } - - impl $crate::parse::Parse for $ident { - fn parse(input: $crate::parse::ParseStream) -> $crate::parse::Result<$ident> { - let spans: custom_punctuation_repr!($($tt)+) = - $crate::token::parsing::punct(input, stringify_punct!($($tt)+))?; - Ok($ident(spans)) - } - } - }; -} - -// Not public API. -#[cfg(not(feature = "parsing"))] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_parse_for_custom_punctuation { - ($ident:ident, $($tt:tt)+) => {}; -} - -// Not public API. -#[cfg(feature = "printing")] -#[doc(hidden)] -#[macro_export(local_inner_macros)] -macro_rules! impl_to_tokens_for_custom_punctuation { - ($ident:ident, $($tt:tt)+) => { - impl $crate::export::ToTokens for $ident { - fn to_tokens(&self, tokens: &mut $crate::export::TokenStream2) { - $crate::token::printing::punct(stringify_punct!($($tt)+), &self.spans, tokens) - } - } - }; -} - -// Not public API. -#[cfg(not(feature = "printing"))] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_to_tokens_for_custom_punctuation { - ($ident:ident, $($tt:tt)+) => {}; -} - -// Not public API. -#[cfg(feature = "clone-impls")] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_clone_for_custom_punctuation { - ($ident:ident, $($tt:tt)+) => { - impl $crate::export::Copy for $ident {} - - impl $crate::export::Clone for $ident { - fn clone(&self) -> Self { - *self - } - } - }; -} - -// Not public API. -#[cfg(not(feature = "clone-impls"))] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_clone_for_custom_punctuation { - ($ident:ident, $($tt:tt)+) => {}; -} - -// Not public API. -#[cfg(feature = "extra-traits")] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_extra_traits_for_custom_punctuation { - ($ident:ident, $($tt:tt)+) => { - impl $crate::export::Debug for $ident { - fn fmt(&self, f: &mut $crate::export::Formatter) -> $crate::export::fmt::Result { - $crate::export::Formatter::write_str(f, stringify!($ident)) - } - } - - impl $crate::export::Eq for $ident {} - - impl $crate::export::PartialEq for $ident { - fn eq(&self, _other: &Self) -> $crate::export::bool { - true - } - } - - impl $crate::export::Hash for $ident { - fn hash<__H: $crate::export::Hasher>(&self, _state: &mut __H) {} - } - }; -} - -// Not public API. -#[cfg(not(feature = "extra-traits"))] -#[doc(hidden)] -#[macro_export] -macro_rules! impl_extra_traits_for_custom_punctuation { - ($ident:ident, $($tt:tt)+) => {}; -} - -// Not public API. -#[doc(hidden)] -#[macro_export(local_inner_macros)] -macro_rules! custom_punctuation_repr { - ($($tt:tt)+) => { - [$crate::export::Span; 0 $(+ custom_punctuation_len!(lenient, $tt))+] - }; -} - -// Not public API. -#[doc(hidden)] -#[macro_export(local_inner_macros)] -#[cfg_attr(rustfmt, rustfmt_skip)] -macro_rules! custom_punctuation_len { - ($mode:ident, +) => { 1 }; - ($mode:ident, +=) => { 2 }; - ($mode:ident, &) => { 1 }; - ($mode:ident, &&) => { 2 }; - ($mode:ident, &=) => { 2 }; - ($mode:ident, @) => { 1 }; - ($mode:ident, !) => { 1 }; - ($mode:ident, ^) => { 1 }; - ($mode:ident, ^=) => { 2 }; - ($mode:ident, :) => { 1 }; - ($mode:ident, ::) => { 2 }; - ($mode:ident, ,) => { 1 }; - ($mode:ident, /) => { 1 }; - ($mode:ident, /=) => { 2 }; - ($mode:ident, .) => { 1 }; - ($mode:ident, ..) => { 2 }; - ($mode:ident, ...) => { 3 }; - ($mode:ident, ..=) => { 3 }; - ($mode:ident, =) => { 1 }; - ($mode:ident, ==) => { 2 }; - ($mode:ident, >=) => { 2 }; - ($mode:ident, >) => { 1 }; - ($mode:ident, <=) => { 2 }; - ($mode:ident, <) => { 1 }; - ($mode:ident, *=) => { 2 }; - ($mode:ident, !=) => { 2 }; - ($mode:ident, |) => { 1 }; - ($mode:ident, |=) => { 2 }; - ($mode:ident, ||) => { 2 }; - ($mode:ident, #) => { 1 }; - ($mode:ident, ?) => { 1 }; - ($mode:ident, ->) => { 2 }; - ($mode:ident, <-) => { 2 }; - ($mode:ident, %) => { 1 }; - ($mode:ident, %=) => { 2 }; - ($mode:ident, =>) => { 2 }; - ($mode:ident, ;) => { 1 }; - ($mode:ident, <<) => { 2 }; - ($mode:ident, <<=) => { 3 }; - ($mode:ident, >>) => { 2 }; - ($mode:ident, >>=) => { 3 }; - ($mode:ident, *) => { 1 }; - ($mode:ident, -) => { 1 }; - ($mode:ident, -=) => { 2 }; - ($mode:ident, ~) => { 1 }; - (lenient, $tt:tt) => { 0 }; - (strict, $tt:tt) => {{ custom_punctuation_unexpected!($tt); 0 }}; -} - -// Not public API. -#[doc(hidden)] -#[macro_export] -macro_rules! custom_punctuation_unexpected { - () => {}; -} - -// Not public API. -#[doc(hidden)] -#[macro_export] -macro_rules! stringify_punct { - ($($tt:tt)+) => { - concat!($(stringify!($tt)),+) - }; -} - -// Not public API. -// Without this, local_inner_macros breaks when looking for concat! -#[doc(hidden)] -#[macro_export] -macro_rules! custom_punctuation_concat { - ($($tt:tt)*) => { - concat!($($tt)*) - }; -} diff --git a/0.15.42/src/data.rs b/0.15.42/src/data.rs deleted file mode 100644 index ba749b86..00000000 --- a/0.15.42/src/data.rs +++ /dev/null @@ -1,387 +0,0 @@ -use super::*; -use punctuated::Punctuated; - -ast_struct! { - /// An enum variant. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct Variant { - /// Attributes tagged on the variant. - pub attrs: Vec<Attribute>, - - /// Name of the variant. - pub ident: Ident, - - /// Content stored in the variant. - pub fields: Fields, - - /// Explicit discriminant: `Variant = 1` - pub discriminant: Option<(Token![=], Expr)>, - } -} - -ast_enum_of_structs! { - /// Data stored within an enum variant or struct. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Fields { - /// Named fields of a struct or struct variant such as `Point { x: f64, - /// y: f64 }`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Named(FieldsNamed { - pub brace_token: token::Brace, - pub named: Punctuated<Field, Token![,]>, - }), - - /// Unnamed fields of a tuple struct or tuple variant such as `Some(T)`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Unnamed(FieldsUnnamed { - pub paren_token: token::Paren, - pub unnamed: Punctuated<Field, Token![,]>, - }), - - /// Unit struct or unit variant such as `None`. - pub Unit, - } -} - -impl Fields { - /// Get an iterator over the borrowed [`Field`] items in this object. This - /// iterator can be used to iterate over a named or unnamed struct or - /// variant's fields uniformly. - pub fn iter(&self) -> punctuated::Iter<Field> { - match *self { - Fields::Unit => private::empty_punctuated_iter(), - Fields::Named(ref f) => f.named.iter(), - Fields::Unnamed(ref f) => f.unnamed.iter(), - } - } - - /// Get an iterator over the mutably borrowed [`Field`] items in this - /// object. This iterator can be used to iterate over a named or unnamed - /// struct or variant's fields uniformly. - pub fn iter_mut(&mut self) -> punctuated::IterMut<Field> { - match *self { - Fields::Unit => private::empty_punctuated_iter_mut(), - Fields::Named(ref mut f) => f.named.iter_mut(), - Fields::Unnamed(ref mut f) => f.unnamed.iter_mut(), - } - } -} - -impl<'a> IntoIterator for &'a Fields { - type Item = &'a Field; - type IntoIter = punctuated::Iter<'a, Field>; - - fn into_iter(self) -> Self::IntoIter { - self.iter() - } -} - -impl<'a> IntoIterator for &'a mut Fields { - type Item = &'a mut Field; - type IntoIter = punctuated::IterMut<'a, Field>; - - fn into_iter(self) -> Self::IntoIter { - self.iter_mut() - } -} - -ast_struct! { - /// A field of a struct or enum variant. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct Field { - /// Attributes tagged on the field. - pub attrs: Vec<Attribute>, - - /// Visibility of the field. - pub vis: Visibility, - - /// Name of the field, if any. - /// - /// Fields of tuple structs have no names. - pub ident: Option<Ident>, - - pub colon_token: Option<Token![:]>, - - /// Type of the field. - pub ty: Type, - } -} - -ast_enum_of_structs! { - /// The visibility level of an item: inherited or `pub` or - /// `pub(restricted)`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Visibility { - /// A public visibility level: `pub`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Public(VisPublic { - pub pub_token: Token![pub], - }), - - /// A crate-level visibility: `crate`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Crate(VisCrate { - pub crate_token: Token![crate], - }), - - /// A visibility level restricted to some path: `pub(self)` or - /// `pub(super)` or `pub(crate)` or `pub(in some::module)`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Restricted(VisRestricted { - pub pub_token: Token![pub], - pub paren_token: token::Paren, - pub in_token: Option<Token![in]>, - pub path: Box<Path>, - }), - - /// An inherited visibility, which usually means private. - pub Inherited, - } -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use ext::IdentExt; - use parse::{Parse, ParseStream, Result}; - - impl Parse for Variant { - fn parse(input: ParseStream) -> Result<Self> { - Ok(Variant { - attrs: input.call(Attribute::parse_outer)?, - ident: input.parse()?, - fields: { - if input.peek(token::Brace) { - Fields::Named(input.parse()?) - } else if input.peek(token::Paren) { - Fields::Unnamed(input.parse()?) - } else { - Fields::Unit - } - }, - discriminant: { - if input.peek(Token![=]) { - let eq_token: Token![=] = input.parse()?; - let discriminant: Expr = input.parse()?; - Some((eq_token, discriminant)) - } else { - None - } - }, - }) - } - } - - impl Parse for FieldsNamed { - fn parse(input: ParseStream) -> Result<Self> { - let content; - Ok(FieldsNamed { - brace_token: braced!(content in input), - named: content.parse_terminated(Field::parse_named)?, - }) - } - } - - impl Parse for FieldsUnnamed { - fn parse(input: ParseStream) -> Result<Self> { - let content; - Ok(FieldsUnnamed { - paren_token: parenthesized!(content in input), - unnamed: content.parse_terminated(Field::parse_unnamed)?, - }) - } - } - - impl Field { - /// Parses a named (braced struct) field. - pub fn parse_named(input: ParseStream) -> Result<Self> { - Ok(Field { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - ident: Some(input.parse()?), - colon_token: Some(input.parse()?), - ty: input.parse()?, - }) - } - - /// Parses an unnamed (tuple struct) field. - pub fn parse_unnamed(input: ParseStream) -> Result<Self> { - Ok(Field { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - ident: None, - colon_token: None, - ty: input.parse()?, - }) - } - } - - impl Parse for Visibility { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Token![pub]) { - Self::parse_pub(input) - } else if input.peek(Token![crate]) { - Self::parse_crate(input) - } else { - Ok(Visibility::Inherited) - } - } - } - - impl Visibility { - fn parse_pub(input: ParseStream) -> Result<Self> { - let pub_token = input.parse::<Token![pub]>()?; - - if input.peek(token::Paren) { - // TODO: optimize using advance_to - let ahead = input.fork(); - let mut content; - parenthesized!(content in ahead); - - if content.peek(Token![crate]) - || content.peek(Token![self]) - || content.peek(Token![super]) - { - return Ok(Visibility::Restricted(VisRestricted { - pub_token: pub_token, - paren_token: parenthesized!(content in input), - in_token: None, - path: Box::new(Path::from(content.call(Ident::parse_any)?)), - })); - } else if content.peek(Token![in]) { - return Ok(Visibility::Restricted(VisRestricted { - pub_token: pub_token, - paren_token: parenthesized!(content in input), - in_token: Some(content.parse()?), - path: Box::new(content.call(Path::parse_mod_style)?), - })); - } - } - - Ok(Visibility::Public(VisPublic { - pub_token: pub_token, - })) - } - - fn parse_crate(input: ParseStream) -> Result<Self> { - if input.peek2(Token![::]) { - Ok(Visibility::Inherited) - } else { - Ok(Visibility::Crate(VisCrate { - crate_token: input.parse()?, - })) - } - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - - use proc_macro2::TokenStream; - use quote::{ToTokens, TokenStreamExt}; - - use print::TokensOrDefault; - - impl ToTokens for Variant { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(&self.attrs); - self.ident.to_tokens(tokens); - self.fields.to_tokens(tokens); - if let Some((ref eq_token, ref disc)) = self.discriminant { - eq_token.to_tokens(tokens); - disc.to_tokens(tokens); - } - } - } - - impl ToTokens for FieldsNamed { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.brace_token.surround(tokens, |tokens| { - self.named.to_tokens(tokens); - }); - } - } - - impl ToTokens for FieldsUnnamed { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.paren_token.surround(tokens, |tokens| { - self.unnamed.to_tokens(tokens); - }); - } - } - - impl ToTokens for Field { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(&self.attrs); - self.vis.to_tokens(tokens); - if let Some(ref ident) = self.ident { - ident.to_tokens(tokens); - TokensOrDefault(&self.colon_token).to_tokens(tokens); - } - self.ty.to_tokens(tokens); - } - } - - impl ToTokens for VisPublic { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.pub_token.to_tokens(tokens) - } - } - - impl ToTokens for VisCrate { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.crate_token.to_tokens(tokens); - } - } - - impl ToTokens for VisRestricted { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.pub_token.to_tokens(tokens); - self.paren_token.surround(tokens, |tokens| { - // 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); - }); - } - } -} diff --git a/0.15.42/src/derive.rs b/0.15.42/src/derive.rs deleted file mode 100644 index 401d6b01..00000000 --- a/0.15.42/src/derive.rs +++ /dev/null @@ -1,258 +0,0 @@ -use super::*; -use punctuated::Punctuated; - -ast_struct! { - /// Data structure sent to a `proc_macro_derive` macro. - /// - /// *This type is available if Syn is built with the `"derive"` feature.* - pub struct DeriveInput { - /// Attributes tagged on the whole struct or enum. - pub attrs: Vec<Attribute>, - - /// Visibility of the struct or enum. - pub vis: Visibility, - - /// Name of the struct or enum. - pub ident: Ident, - - /// Generics required to complete the definition. - pub generics: Generics, - - /// Data within the struct or enum. - pub data: Data, - } -} - -ast_enum_of_structs! { - /// The storage of a struct, enum or union data structure. - /// - /// *This type is available if Syn is built with the `"derive"` feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Data { - /// A struct input to a `proc_macro_derive` macro. - /// - /// *This type is available if Syn is built with the `"derive"` - /// feature.* - pub Struct(DataStruct { - pub struct_token: Token![struct], - pub fields: Fields, - pub semi_token: Option<Token![;]>, - }), - - /// An enum input to a `proc_macro_derive` macro. - /// - /// *This type is available if Syn is built with the `"derive"` - /// feature.* - pub Enum(DataEnum { - pub enum_token: Token![enum], - pub brace_token: token::Brace, - pub variants: Punctuated<Variant, Token![,]>, - }), - - /// A tagged union input to a `proc_macro_derive` macro. - /// - /// *This type is available if Syn is built with the `"derive"` - /// feature.* - pub Union(DataUnion { - pub union_token: Token![union], - pub fields: FieldsNamed, - }), - } - - do_not_generate_to_tokens -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use parse::{Parse, ParseStream, Result}; - - impl Parse for DeriveInput { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let vis = input.parse::<Visibility>()?; - - let lookahead = input.lookahead1(); - if lookahead.peek(Token![struct]) { - let struct_token = input.parse::<Token![struct]>()?; - let ident = input.parse::<Ident>()?; - let generics = input.parse::<Generics>()?; - let (where_clause, fields, semi) = data_struct(input)?; - Ok(DeriveInput { - attrs: attrs, - vis: vis, - ident: ident, - generics: Generics { - where_clause: where_clause, - ..generics - }, - data: Data::Struct(DataStruct { - struct_token: struct_token, - fields: fields, - semi_token: semi, - }), - }) - } else if lookahead.peek(Token![enum]) { - let enum_token = input.parse::<Token![enum]>()?; - let ident = input.parse::<Ident>()?; - let generics = input.parse::<Generics>()?; - let (where_clause, brace, variants) = data_enum(input)?; - Ok(DeriveInput { - attrs: attrs, - vis: vis, - ident: ident, - generics: Generics { - where_clause: where_clause, - ..generics - }, - data: Data::Enum(DataEnum { - enum_token: enum_token, - brace_token: brace, - variants: variants, - }), - }) - } else if lookahead.peek(Token![union]) { - let union_token = input.parse::<Token![union]>()?; - let ident = input.parse::<Ident>()?; - let generics = input.parse::<Generics>()?; - let (where_clause, fields) = data_union(input)?; - Ok(DeriveInput { - attrs: attrs, - vis: vis, - ident: ident, - generics: Generics { - where_clause: where_clause, - ..generics - }, - data: Data::Union(DataUnion { - union_token: union_token, - fields: fields, - }), - }) - } else { - Err(lookahead.error()) - } - } - } - - pub fn data_struct( - input: ParseStream, - ) -> Result<(Option<WhereClause>, Fields, Option<Token![;]>)> { - let mut lookahead = input.lookahead1(); - let mut where_clause = None; - if lookahead.peek(Token![where]) { - where_clause = Some(input.parse()?); - lookahead = input.lookahead1(); - } - - if where_clause.is_none() && lookahead.peek(token::Paren) { - let fields = input.parse()?; - - lookahead = input.lookahead1(); - if lookahead.peek(Token![where]) { - where_clause = Some(input.parse()?); - lookahead = input.lookahead1(); - } - - if lookahead.peek(Token![;]) { - let semi = input.parse()?; - Ok((where_clause, Fields::Unnamed(fields), Some(semi))) - } else { - Err(lookahead.error()) - } - } else if lookahead.peek(token::Brace) { - let fields = input.parse()?; - Ok((where_clause, Fields::Named(fields), None)) - } else if lookahead.peek(Token![;]) { - let semi = input.parse()?; - Ok((where_clause, Fields::Unit, Some(semi))) - } else { - Err(lookahead.error()) - } - } - - pub fn data_enum( - input: ParseStream, - ) -> Result<( - Option<WhereClause>, - token::Brace, - Punctuated<Variant, Token![,]>, - )> { - let where_clause = input.parse()?; - - let content; - let brace = braced!(content in input); - let variants = content.parse_terminated(Variant::parse)?; - - Ok((where_clause, brace, variants)) - } - - pub fn data_union(input: ParseStream) -> Result<(Option<WhereClause>, FieldsNamed)> { - let where_clause = input.parse()?; - let fields = input.parse()?; - Ok((where_clause, fields)) - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - - use proc_macro2::TokenStream; - use quote::ToTokens; - - use attr::FilterAttrs; - use print::TokensOrDefault; - - impl ToTokens for DeriveInput { - fn to_tokens(&self, tokens: &mut TokenStream) { - for attr in self.attrs.outer() { - attr.to_tokens(tokens); - } - self.vis.to_tokens(tokens); - match self.data { - Data::Struct(ref d) => d.struct_token.to_tokens(tokens), - Data::Enum(ref d) => d.enum_token.to_tokens(tokens), - Data::Union(ref d) => d.union_token.to_tokens(tokens), - } - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - match self.data { - Data::Struct(ref data) => match data.fields { - Fields::Named(ref fields) => { - self.generics.where_clause.to_tokens(tokens); - fields.to_tokens(tokens); - } - Fields::Unnamed(ref fields) => { - fields.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - TokensOrDefault(&data.semi_token).to_tokens(tokens); - } - Fields::Unit => { - self.generics.where_clause.to_tokens(tokens); - TokensOrDefault(&data.semi_token).to_tokens(tokens); - } - }, - Data::Enum(ref data) => { - self.generics.where_clause.to_tokens(tokens); - data.brace_token.surround(tokens, |tokens| { - data.variants.to_tokens(tokens); - }); - } - Data::Union(ref data) => { - self.generics.where_clause.to_tokens(tokens); - data.fields.to_tokens(tokens); - } - } - } - } -} diff --git a/0.15.42/src/discouraged.rs b/0.15.42/src/discouraged.rs deleted file mode 100644 index 07bb82a1..00000000 --- a/0.15.42/src/discouraged.rs +++ /dev/null @@ -1,171 +0,0 @@ -//! Extensions to the parsing API with niche applicability. - -use super::*; - -/// Extensions to the `ParseStream` API to support speculative parsing. -pub trait Speculative { - /// Advance this parse stream to the position of a forked parse stream. - /// - /// This is the opposite operation to [`ParseStream::fork`]. You can fork a - /// parse stream, perform some speculative parsing, then join the original - /// stream to the fork to "commit" the parsing from the fork to the main - /// stream. - /// - /// If you can avoid doing this, you should, as it limits the ability to - /// generate useful errors. That said, it is often the only way to parse - /// syntax of the form `A* B*` for arbitrary syntax `A` and `B`. The problem - /// is that when the fork fails to parse an `A`, it's impossible to tell - /// whether that was because of a syntax error and the user meant to provide - /// an `A`, or that the `A`s are finished and its time to start parsing - /// `B`s. Use with care. - /// - /// Also note that if `A` is a subset of `B`, `A* B*` can be parsed by - /// parsing `B*` and removing the leading members of `A` from the - /// repetition, bypassing the need to involve the downsides associated with - /// speculative parsing. - /// - /// [`ParseStream::fork`]: ParseBuffer::fork - /// - /// # Example - /// - /// There has been chatter about the possibility of making the colons in the - /// turbofish syntax like `path::to::<T>` no longer required by accepting - /// `path::to<T>` in expression position. Specifically, according to [RFC - /// 2544], [`PathSegment`] parsing should always try to consume a following - /// `<` token as the start of generic arguments, and reset to the `<` if - /// that fails (e.g. the token is acting as a less-than operator). - /// - /// This is the exact kind of parsing behavior which requires the "fork, - /// try, commit" behavior that [`ParseStream::fork`] discourages. With - /// `advance_to`, we can avoid having to parse the speculatively parsed - /// content a second time. - /// - /// This change in behavior can be implemented in syn by replacing just the - /// `Parse` implementation for `PathSegment`: - /// - /// ```edition2018 - /// # use syn::ext::IdentExt; - /// use syn::parse::discouraged::Speculative; - /// # use syn::parse::{Parse, ParseStream}; - /// # use syn::{Ident, PathArguments, Result, Token}; - /// - /// pub struct PathSegment { - /// pub ident: Ident, - /// pub arguments: PathArguments, - /// } - /// # - /// # impl<T> From<T> for PathSegment - /// # where - /// # T: Into<Ident>, - /// # { - /// # fn from(ident: T) -> Self { - /// # PathSegment { - /// # ident: ident.into(), - /// # arguments: PathArguments::None, - /// # } - /// # } - /// # } - /// - /// impl Parse for PathSegment { - /// fn parse(input: ParseStream) -> Result<Self> { - /// if input.peek(Token![super]) - /// || input.peek(Token![self]) - /// || input.peek(Token![Self]) - /// || input.peek(Token![crate]) - /// || input.peek(Token![extern]) - /// { - /// let ident = input.call(Ident::parse_any)?; - /// return Ok(PathSegment::from(ident)); - /// } - /// - /// let ident = input.parse()?; - /// if input.peek(Token![::]) && input.peek3(Token![<]) { - /// return Ok(PathSegment { - /// ident: ident, - /// arguments: PathArguments::AngleBracketed(input.parse()?), - /// }); - /// } - /// if input.peek(Token![<]) && !input.peek(Token![<=]) { - /// let fork = input.fork(); - /// if let Ok(arguments) = fork.parse() { - /// input.advance_to(&fork); - /// return Ok(PathSegment { - /// ident: ident, - /// arguments: PathArguments::AngleBracketed(arguments), - /// }); - /// } - /// } - /// Ok(PathSegment::from(ident)) - /// } - /// } - /// - /// # syn::parse_str::<PathSegment>("a<b,c>").unwrap(); - /// ``` - /// - /// # Drawbacks - /// - /// The main drawback of this style of speculative parsing is in error - /// presentation. Even if the lookahead is the "correct" parse, the error - /// that is shown is that of the "fallback" parse. To use the same example - /// as the turbofish above, take the following unfinished "turbofish": - /// - /// ```text - /// let _ = f<&'a fn(), for<'a> serde::>(); - /// ``` - /// - /// If this is parsed as generic arguments, we can provide the error message - /// - /// ```text - /// error: expected identifier - /// --> src.rs:L:C - /// | - /// L | let _ = f<&'a fn(), for<'a> serde::>(); - /// | ^ - /// ``` - /// - /// but if parsed using the above speculative parsing, it falls back to - /// assuming that the `<` is a less-than when it fails to parse the generic - /// arguments, and tries to interpret the `&'a` as the start of a labelled - /// loop, resulting in the much less helpful error - /// - /// ```text - /// error: expected `:` - /// --> src.rs:L:C - /// | - /// L | let _ = f<&'a fn(), for<'a> serde::>(); - /// | ^^ - /// ``` - /// - /// This can be mitigated with various heuristics (two examples: show both - /// forks' parse errors, or show the one that consumed more tokens), but - /// when you can control the grammar, sticking to something that can be - /// parsed LL(3) and without the LL(*) speculative parsing this makes - /// possible, displaying reasonable errors becomes much more simple. - /// - /// [RFC 2544]: https://github.com/rust-lang/rfcs/pull/2544 - /// [`PathSegment`]: crate::PathSegment - /// - /// # Performance - /// - /// This method performs a cheap fixed amount of work that does not depend - /// on how far apart the two streams are positioned. - /// - /// # Panics - /// - /// The forked stream in the argument of `advance_to` must have been - /// obtained by forking `self`. Attempting to advance to any other stream - /// will cause a panic. - fn advance_to(&self, fork: &Self); -} - -impl<'a> Speculative for ParseBuffer<'a> { - fn advance_to(&self, fork: &Self) { - if !private::same_scope(self.cursor(), fork.cursor()) { - panic!("Fork was not derived from the advancing parse stream"); - } - - // See comment on `cell` in the struct definition. - self.cell - .set(unsafe { mem::transmute::<Cursor, Cursor<'static>>(fork.cursor()) }) - } -} diff --git a/0.15.42/src/error.rs b/0.15.42/src/error.rs deleted file mode 100644 index 0b155894..00000000 --- a/0.15.42/src/error.rs +++ /dev/null @@ -1,223 +0,0 @@ -use std; -use std::fmt::{self, Debug, Display}; -use std::iter::FromIterator; - -use proc_macro2::{ - Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree, -}; -#[cfg(feature = "printing")] -use quote::ToTokens; - -#[cfg(feature = "parsing")] -use buffer::Cursor; -#[cfg(all(procmacro2_semver_exempt, feature = "parsing"))] -use private; -use thread::ThreadBound; - -/// The result of a Syn parser. -pub type Result<T> = std::result::Result<T, Error>; - -/// Error returned when a Syn parser cannot parse the input tokens. -/// -/// Refer to the [module documentation] for details about parsing in Syn. -/// -/// [module documentation]: index.html -/// -/// *This type is available if Syn is built with the `"parsing"` feature.* -// -// TODO: change the parse module link to an intra rustdoc link, currently -// blocked on https://github.com/rust-lang/rust/issues/62830 -pub struct Error { - // Span is implemented as an index into a thread-local interner to keep the - // size small. It is not safe to access from a different thread. We want - // errors to be Send and Sync to play nicely with the Failure crate, so pin - // the span we're given to its original thread and assume it is - // Span::call_site if accessed from any other thread. - start_span: ThreadBound<Span>, - end_span: ThreadBound<Span>, - message: String, -} - -#[cfg(test)] -struct _Test -where - Error: Send + Sync; - -impl Error { - /// Usually the [`ParseStream::error`] method will be used instead, which - /// automatically uses the correct span from the current position of the - /// parse stream. - /// - /// Use `Error::new` when the error needs to be triggered on some span other - /// than where the parse stream is currently positioned. - /// - /// [`ParseStream::error`]: crate::parse::ParseBuffer::error - /// - /// # Example - /// - /// ```edition2018 - /// use syn::{Error, Ident, LitStr, Result, Token}; - /// use syn::parse::ParseStream; - /// - /// // Parses input that looks like `name = "string"` where the key must be - /// // the identifier `name` and the value may be any string literal. - /// // Returns the string literal. - /// fn parse_name(input: ParseStream) -> Result<LitStr> { - /// let name_token: Ident = input.parse()?; - /// if name_token != "name" { - /// // Trigger an error not on the current position of the stream, - /// // but on the position of the unexpected identifier. - /// return Err(Error::new(name_token.span(), "expected `name`")); - /// } - /// input.parse::<Token![=]>()?; - /// let s: LitStr = input.parse()?; - /// Ok(s) - /// } - /// ``` - pub fn new<T: Display>(span: Span, message: T) -> Self { - Error { - start_span: ThreadBound::new(span), - end_span: ThreadBound::new(span), - message: message.to_string(), - } - } - - /// Creates an error with the specified message spanning the given syntax - /// tree node. - /// - /// Unlike the `Error::new` constructor, this constructor takes an argument - /// `tokens` which is a syntax tree node. This allows the resulting `Error` - /// to attempt to span all tokens inside of `tokens`. While you would - /// typically be able to use the `Spanned` trait with the above `Error::new` - /// constructor, implementation limitations today mean that - /// `Error::new_spanned` may provide a higher-quality error message on - /// stable Rust. - /// - /// When in doubt it's recommended to stick to `Error::new` (or - /// `ParseStream::error`)! - #[cfg(feature = "printing")] - pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self { - let mut iter = tokens.into_token_stream().into_iter(); - let start = iter.next().map_or_else(Span::call_site, |t| t.span()); - let end = iter.last().map_or(start, |t| t.span()); - Error { - start_span: ThreadBound::new(start), - end_span: ThreadBound::new(end), - message: message.to_string(), - } - } - - /// The source location of the error. - /// - /// Spans are not thread-safe so this function returns `Span::call_site()` - /// if called from a different thread than the one on which the `Error` was - /// originally created. - pub fn span(&self) -> Span { - let start = match self.start_span.get() { - Some(span) => *span, - None => return Span::call_site(), - }; - - #[cfg(procmacro2_semver_exempt)] - { - let end = match self.end_span.get() { - Some(span) => *span, - None => return Span::call_site(), - }; - start.join(end).unwrap_or(start) - } - #[cfg(not(procmacro2_semver_exempt))] - { - start - } - } - - /// Render the error as an invocation of [`compile_error!`]. - /// - /// The [`parse_macro_input!`] macro provides a convenient way to invoke - /// this method correctly in a procedural macro. - /// - /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html - pub fn to_compile_error(&self) -> TokenStream { - let start = self - .start_span - .get() - .cloned() - .unwrap_or_else(Span::call_site); - let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site); - - // compile_error!($message) - TokenStream::from_iter(vec![ - TokenTree::Ident(Ident::new("compile_error", start)), - TokenTree::Punct({ - let mut punct = Punct::new('!', Spacing::Alone); - punct.set_span(start); - punct - }), - TokenTree::Group({ - let mut group = Group::new(Delimiter::Brace, { - TokenStream::from_iter(vec![TokenTree::Literal({ - let mut string = Literal::string(&self.message); - string.set_span(end); - string - })]) - }); - group.set_span(end); - group - }), - ]) - } -} - -#[cfg(feature = "parsing")] -pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error { - if cursor.eof() { - Error::new(scope, format!("unexpected end of input, {}", message)) - } else { - #[cfg(procmacro2_semver_exempt)] - let span = private::open_span_of_group(cursor); - #[cfg(not(procmacro2_semver_exempt))] - let span = cursor.span(); - Error::new(span, message) - } -} - -impl Debug for Error { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.debug_tuple("Error").field(&self.message).finish() - } -} - -impl Display for Error { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(&self.message) - } -} - -impl Clone for Error { - fn clone(&self) -> Self { - let start = self - .start_span - .get() - .cloned() - .unwrap_or_else(Span::call_site); - let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site); - Error { - start_span: ThreadBound::new(start), - end_span: ThreadBound::new(end), - message: self.message.clone(), - } - } -} - -impl std::error::Error for Error { - fn description(&self) -> &str { - "parse error" - } -} - -impl From<LexError> for Error { - fn from(err: LexError) -> Self { - Error::new(Span::call_site(), format!("{:?}", err)) - } -} diff --git a/0.15.42/src/export.rs b/0.15.42/src/export.rs deleted file mode 100644 index 8e270bd0..00000000 --- a/0.15.42/src/export.rs +++ /dev/null @@ -1,35 +0,0 @@ -pub use std::clone::Clone; -pub use std::cmp::{Eq, PartialEq}; -pub use std::convert::From; -pub use std::default::Default; -pub use std::fmt::{self, Debug, Formatter}; -pub use std::hash::{Hash, Hasher}; -pub use std::marker::Copy; -pub use std::option::Option::{None, Some}; -pub use std::result::Result::{Err, Ok}; - -#[cfg(feature = "printing")] -pub extern crate quote; - -pub use proc_macro2::{Span, TokenStream as TokenStream2}; - -pub use span::IntoSpans; - -#[cfg(all( - not(all(target_arch = "wasm32", target_os = "unknown")), - feature = "proc-macro" -))] -pub use proc_macro::TokenStream; - -#[cfg(feature = "printing")] -pub use quote::{ToTokens, TokenStreamExt}; - -#[allow(non_camel_case_types)] -pub type bool = help::Bool; -#[allow(non_camel_case_types)] -pub type str = help::Str; - -mod help { - pub type Bool = bool; - pub type Str = str; -} diff --git a/0.15.42/src/expr.rs b/0.15.42/src/expr.rs deleted file mode 100644 index 3d0b70a3..00000000 --- a/0.15.42/src/expr.rs +++ /dev/null @@ -1,3821 +0,0 @@ -use super::*; -use proc_macro2::{Span, TokenStream}; -use punctuated::Punctuated; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; -#[cfg(all(feature = "parsing", feature = "full"))] -use std::mem; -#[cfg(feature = "extra-traits")] -use tt::TokenStreamHelper; - -ast_enum_of_structs! { - /// A Rust expression. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// # Syntax tree enums - /// - /// This type is a syntax tree enum. In Syn this and other syntax tree enums - /// are designed to be traversed using the following rebinding idiom. - /// - /// ```edition2018 - /// # use syn::Expr; - /// # - /// # fn example(expr: Expr) { - /// # const IGNORE: &str = stringify! { - /// let expr: Expr = /* ... */; - /// # }; - /// match expr { - /// Expr::MethodCall(expr) => { - /// /* ... */ - /// } - /// Expr::Cast(expr) => { - /// /* ... */ - /// } - /// Expr::If(expr) => { - /// /* ... */ - /// } - /// - /// /* ... */ - /// # _ => {} - /// # } - /// # } - /// ``` - /// - /// We begin with a variable `expr` of type `Expr` that has no fields - /// (because it is an enum), and by matching on it and rebinding a variable - /// with the same name `expr` we effectively imbue our variable with all of - /// the data fields provided by the variant that it turned out to be. So for - /// example above if we ended up in the `MethodCall` case then we get to use - /// `expr.receiver`, `expr.args` etc; if we ended up in the `If` case we get - /// to use `expr.cond`, `expr.then_branch`, `expr.else_branch`. - /// - /// This approach avoids repeating the variant names twice on every line. - /// - /// ```edition2018 - /// # use syn::{Expr, ExprMethodCall}; - /// # - /// # fn example(expr: Expr) { - /// // Repetitive; recommend not doing this. - /// match expr { - /// Expr::MethodCall(ExprMethodCall { method, args, .. }) => { - /// # } - /// # _ => {} - /// # } - /// # } - /// ``` - /// - /// In general, the name to which a syntax tree enum variant is bound should - /// be a suitable name for the complete syntax tree enum type. - /// - /// ```edition2018 - /// # use syn::{Expr, ExprField}; - /// # - /// # fn example(discriminant: ExprField) { - /// // Binding is called `base` which is the name I would use if I were - /// // assigning `*discriminant.base` without an `if let`. - /// if let Expr::Tuple(base) = *discriminant.base { - /// # } - /// # } - /// ``` - /// - /// A sign that you may not be choosing the right variable names is if you - /// see names getting repeated in your code, like accessing - /// `receiver.receiver` or `pat.pat` or `cond.cond`. - pub enum Expr { - /// A box expression: `box f`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Box(ExprBox #full { - pub attrs: Vec<Attribute>, - pub box_token: Token![box], - pub expr: Box<Expr>, - }), - - /// A placement expression: `place <- value`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub InPlace(ExprInPlace #full { - pub attrs: Vec<Attribute>, - pub place: Box<Expr>, - pub arrow_token: Token![<-], - pub value: Box<Expr>, - }), - - /// A slice literal expression: `[a, b, c, d]`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Array(ExprArray #full { - pub attrs: Vec<Attribute>, - pub bracket_token: token::Bracket, - pub elems: Punctuated<Expr, Token![,]>, - }), - - /// A function call expression: `invoke(a, b)`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Call(ExprCall { - pub attrs: Vec<Attribute>, - pub func: Box<Expr>, - pub paren_token: token::Paren, - pub args: Punctuated<Expr, Token![,]>, - }), - - /// A method call expression: `x.foo::<T>(a, b)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub MethodCall(ExprMethodCall #full { - pub attrs: Vec<Attribute>, - pub receiver: Box<Expr>, - pub dot_token: Token![.], - pub method: Ident, - pub turbofish: Option<MethodTurbofish>, - pub paren_token: token::Paren, - pub args: Punctuated<Expr, Token![,]>, - }), - - /// A tuple expression: `(a, b, c, d)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Tuple(ExprTuple #full { - pub attrs: Vec<Attribute>, - pub paren_token: token::Paren, - pub elems: Punctuated<Expr, Token![,]>, - }), - - /// A binary operation: `a + b`, `a * b`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Binary(ExprBinary { - pub attrs: Vec<Attribute>, - pub left: Box<Expr>, - pub op: BinOp, - pub right: Box<Expr>, - }), - - /// A unary operation: `!x`, `*x`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Unary(ExprUnary { - pub attrs: Vec<Attribute>, - pub op: UnOp, - pub expr: Box<Expr>, - }), - - /// A literal in place of an expression: `1`, `"foo"`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Lit(ExprLit { - pub attrs: Vec<Attribute>, - pub lit: Lit, - }), - - /// A cast expression: `foo as f64`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Cast(ExprCast { - pub attrs: Vec<Attribute>, - pub expr: Box<Expr>, - pub as_token: Token![as], - pub ty: Box<Type>, - }), - - /// A type ascription expression: `foo: f64`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Type(ExprType #full { - pub attrs: Vec<Attribute>, - pub expr: Box<Expr>, - pub colon_token: Token![:], - pub ty: Box<Type>, - }), - - /// A `let` guard: `let Some(x) = opt`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Let(ExprLet #full { - pub attrs: Vec<Attribute>, - pub let_token: Token![let], - pub pats: Punctuated<Pat, Token![|]>, - pub eq_token: Token![=], - pub expr: Box<Expr>, - }), - - /// An `if` expression with an optional `else` block: `if expr { ... } - /// else { ... }`. - /// - /// The `else` branch expression may only be an `If` or `Block` - /// expression, not any of the other types of expression. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub If(ExprIf #full { - pub attrs: Vec<Attribute>, - pub if_token: Token![if], - pub cond: Box<Expr>, - pub then_branch: Block, - pub else_branch: Option<(Token![else], Box<Expr>)>, - }), - - /// A while loop: `while expr { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub While(ExprWhile #full { - pub attrs: Vec<Attribute>, - pub label: Option<Label>, - pub while_token: Token![while], - pub cond: Box<Expr>, - pub body: Block, - }), - - /// A for loop: `for pat in expr { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub ForLoop(ExprForLoop #full { - pub attrs: Vec<Attribute>, - pub label: Option<Label>, - pub for_token: Token![for], - pub pat: Box<Pat>, - pub in_token: Token![in], - pub expr: Box<Expr>, - pub body: Block, - }), - - /// Conditionless loop: `loop { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Loop(ExprLoop #full { - pub attrs: Vec<Attribute>, - pub label: Option<Label>, - pub loop_token: Token![loop], - pub body: Block, - }), - - /// A `match` expression: `match n { Some(n) => {}, None => {} }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Match(ExprMatch #full { - pub attrs: Vec<Attribute>, - pub match_token: Token![match], - pub expr: Box<Expr>, - pub brace_token: token::Brace, - pub arms: Vec<Arm>, - }), - - /// A closure expression: `|a, b| a + b`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Closure(ExprClosure #full { - pub attrs: Vec<Attribute>, - pub asyncness: Option<Token![async]>, - pub movability: Option<Token![static]>, - pub capture: Option<Token![move]>, - pub or1_token: Token![|], - pub inputs: Punctuated<FnArg, Token![,]>, - pub or2_token: Token![|], - pub output: ReturnType, - pub body: Box<Expr>, - }), - - /// An unsafe block: `unsafe { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Unsafe(ExprUnsafe #full { - pub attrs: Vec<Attribute>, - pub unsafe_token: Token![unsafe], - pub block: Block, - }), - - /// A blocked scope: `{ ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Block(ExprBlock #full { - pub attrs: Vec<Attribute>, - pub label: Option<Label>, - pub block: Block, - }), - - /// An assignment expression: `a = compute()`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Assign(ExprAssign #full { - pub attrs: Vec<Attribute>, - pub left: Box<Expr>, - pub eq_token: Token![=], - pub right: Box<Expr>, - }), - - /// A compound assignment expression: `counter += 1`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub AssignOp(ExprAssignOp #full { - pub attrs: Vec<Attribute>, - pub left: Box<Expr>, - pub op: BinOp, - pub right: Box<Expr>, - }), - - /// Access of a named struct field (`obj.k`) or unnamed tuple struct - /// field (`obj.0`). - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Field(ExprField { - pub attrs: Vec<Attribute>, - pub base: Box<Expr>, - pub dot_token: Token![.], - pub member: Member, - }), - - /// A square bracketed indexing expression: `vector[2]`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Index(ExprIndex { - pub attrs: Vec<Attribute>, - pub expr: Box<Expr>, - pub bracket_token: token::Bracket, - pub index: Box<Expr>, - }), - - /// A range expression: `1..2`, `1..`, `..2`, `1..=2`, `..=2`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Range(ExprRange #full { - pub attrs: Vec<Attribute>, - pub from: Option<Box<Expr>>, - pub limits: RangeLimits, - pub to: Option<Box<Expr>>, - }), - - /// A path like `std::mem::replace` possibly containing generic - /// parameters and a qualified self-type. - /// - /// A plain identifier like `x` is a path of length 1. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Path(ExprPath { - pub attrs: Vec<Attribute>, - pub qself: Option<QSelf>, - pub path: Path, - }), - - /// A referencing operation: `&a` or `&mut a`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Reference(ExprReference #full { - pub attrs: Vec<Attribute>, - pub and_token: Token![&], - pub mutability: Option<Token![mut]>, - pub expr: Box<Expr>, - }), - - /// A `break`, with an optional label to break and an optional - /// expression. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Break(ExprBreak #full { - pub attrs: Vec<Attribute>, - pub break_token: Token![break], - pub label: Option<Lifetime>, - pub expr: Option<Box<Expr>>, - }), - - /// A `continue`, with an optional label. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Continue(ExprContinue #full { - pub attrs: Vec<Attribute>, - pub continue_token: Token![continue], - pub label: Option<Lifetime>, - }), - - /// A `return`, with an optional value to be returned. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Return(ExprReturn #full { - pub attrs: Vec<Attribute>, - pub return_token: Token![return], - pub expr: Option<Box<Expr>>, - }), - - /// A macro invocation expression: `format!("{}", q)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Macro(ExprMacro #full { - pub attrs: Vec<Attribute>, - pub mac: Macro, - }), - - /// A struct literal expression: `Point { x: 1, y: 1 }`. - /// - /// The `rest` provides the value of the remaining fields as in `S { a: - /// 1, b: 1, ..rest }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Struct(ExprStruct #full { - pub attrs: Vec<Attribute>, - pub path: Path, - pub brace_token: token::Brace, - pub fields: Punctuated<FieldValue, Token![,]>, - pub dot2_token: Option<Token![..]>, - pub rest: Option<Box<Expr>>, - }), - - /// An array literal constructed from one repeated element: `[0u8; N]`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Repeat(ExprRepeat #full { - pub attrs: Vec<Attribute>, - pub bracket_token: token::Bracket, - pub expr: Box<Expr>, - pub semi_token: Token![;], - pub len: Box<Expr>, - }), - - /// A parenthesized expression: `(a + b)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Paren(ExprParen { - pub attrs: Vec<Attribute>, - pub paren_token: token::Paren, - pub expr: Box<Expr>, - }), - - /// An expression contained within invisible delimiters. - /// - /// This variant is important for faithfully representing the precedence - /// of expressions and is related to `None`-delimited spans in a - /// `TokenStream`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Group(ExprGroup #full { - pub attrs: Vec<Attribute>, - pub group_token: token::Group, - pub expr: Box<Expr>, - }), - - /// A try-expression: `expr?`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Try(ExprTry #full { - pub attrs: Vec<Attribute>, - pub expr: Box<Expr>, - pub question_token: Token![?], - }), - - /// An async block: `async { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Async(ExprAsync #full { - pub attrs: Vec<Attribute>, - pub async_token: Token![async], - pub capture: Option<Token![move]>, - pub block: Block, - }), - - /// A try block: `try { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub TryBlock(ExprTryBlock #full { - pub attrs: Vec<Attribute>, - pub try_token: Token![try], - pub block: Block, - }), - - /// A yield expression: `yield expr`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Yield(ExprYield #full { - pub attrs: Vec<Attribute>, - pub yield_token: Token![yield], - pub expr: Option<Box<Expr>>, - }), - - /// Tokens in expression position not interpreted by Syn. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Verbatim(ExprVerbatim #manual_extra_traits { - pub tts: TokenStream, - }), - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for ExprVerbatim {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for ExprVerbatim { - fn eq(&self, other: &Self) -> bool { - TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for ExprVerbatim { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - TokenStreamHelper(&self.tts).hash(state); - } -} - -impl Expr { - #[cfg(all(feature = "parsing", feature = "full"))] - fn replace_attrs(&mut self, new: Vec<Attribute>) -> Vec<Attribute> { - match *self { - Expr::Box(ExprBox { ref mut attrs, .. }) - | Expr::InPlace(ExprInPlace { ref mut attrs, .. }) - | Expr::Array(ExprArray { ref mut attrs, .. }) - | Expr::Call(ExprCall { ref mut attrs, .. }) - | Expr::MethodCall(ExprMethodCall { ref mut attrs, .. }) - | Expr::Tuple(ExprTuple { ref mut attrs, .. }) - | Expr::Binary(ExprBinary { ref mut attrs, .. }) - | Expr::Unary(ExprUnary { ref mut attrs, .. }) - | Expr::Lit(ExprLit { ref mut attrs, .. }) - | Expr::Cast(ExprCast { ref mut attrs, .. }) - | Expr::Type(ExprType { ref mut attrs, .. }) - | Expr::Let(ExprLet { ref mut attrs, .. }) - | Expr::If(ExprIf { ref mut attrs, .. }) - | Expr::While(ExprWhile { ref mut attrs, .. }) - | Expr::ForLoop(ExprForLoop { ref mut attrs, .. }) - | Expr::Loop(ExprLoop { ref mut attrs, .. }) - | Expr::Match(ExprMatch { ref mut attrs, .. }) - | Expr::Closure(ExprClosure { ref mut attrs, .. }) - | Expr::Unsafe(ExprUnsafe { ref mut attrs, .. }) - | Expr::Block(ExprBlock { ref mut attrs, .. }) - | Expr::Assign(ExprAssign { ref mut attrs, .. }) - | Expr::AssignOp(ExprAssignOp { ref mut attrs, .. }) - | Expr::Field(ExprField { ref mut attrs, .. }) - | Expr::Index(ExprIndex { ref mut attrs, .. }) - | Expr::Range(ExprRange { ref mut attrs, .. }) - | Expr::Path(ExprPath { ref mut attrs, .. }) - | Expr::Reference(ExprReference { ref mut attrs, .. }) - | Expr::Break(ExprBreak { ref mut attrs, .. }) - | Expr::Continue(ExprContinue { ref mut attrs, .. }) - | Expr::Return(ExprReturn { ref mut attrs, .. }) - | Expr::Macro(ExprMacro { ref mut attrs, .. }) - | Expr::Struct(ExprStruct { ref mut attrs, .. }) - | Expr::Repeat(ExprRepeat { ref mut attrs, .. }) - | Expr::Paren(ExprParen { ref mut attrs, .. }) - | Expr::Group(ExprGroup { ref mut attrs, .. }) - | Expr::Try(ExprTry { ref mut attrs, .. }) - | Expr::Async(ExprAsync { ref mut attrs, .. }) - | Expr::TryBlock(ExprTryBlock { ref mut attrs, .. }) - | Expr::Yield(ExprYield { ref mut attrs, .. }) => mem::replace(attrs, new), - Expr::Verbatim(_) => Vec::new(), - } - } -} - -ast_enum! { - /// A struct or tuple struct field accessed in a struct literal or field - /// expression. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum Member { - /// A named field like `self.x`. - Named(Ident), - /// An unnamed field like `self.0`. - Unnamed(Index), - } -} - -ast_struct! { - /// The index of an unnamed tuple struct field. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct Index #manual_extra_traits { - pub index: u32, - pub span: Span, - } -} - -impl From<usize> for Index { - fn from(index: usize) -> Index { - assert!(index < u32::max_value() as usize); - Index { - index: index as u32, - span: Span::call_site(), - } - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for Index {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Index { - fn eq(&self, other: &Self) -> bool { - self.index == other.index - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Index { - fn hash<H: Hasher>(&self, state: &mut H) { - self.index.hash(state); - } -} - -#[cfg(feature = "full")] -ast_struct! { - /// The `::<>` explicit type parameters passed to a method call: - /// `parse::<u64>()`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct MethodTurbofish { - pub colon2_token: Token![::], - pub lt_token: Token![<], - pub args: Punctuated<GenericMethodArgument, Token![,]>, - pub gt_token: Token![>], - } -} - -#[cfg(feature = "full")] -ast_enum! { - /// An individual generic argument to a method, like `T`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub enum GenericMethodArgument { - /// A type argument. - Type(Type), - /// A const expression. Must be inside of a block. - /// - /// NOTE: Identity expressions are represented as Type arguments, as - /// they are indistinguishable syntactically. - Const(Expr), - } -} - -#[cfg(feature = "full")] -ast_struct! { - /// A field-value pair in a struct literal. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct FieldValue { - /// Attributes tagged on the field. - pub attrs: Vec<Attribute>, - - /// Name or index of the field. - pub member: Member, - - /// The colon in `Struct { x: x }`. If written in shorthand like - /// `Struct { x }`, there is no colon. - pub colon_token: Option<Token![:]>, - - /// Value of the field. - pub expr: Expr, - } -} - -#[cfg(feature = "full")] -ast_struct! { - /// A lifetime labeling a `for`, `while`, or `loop`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct Label { - pub name: Lifetime, - pub colon_token: Token![:], - } -} - -#[cfg(feature = "full")] -ast_struct! { - /// A braced block containing Rust statements. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct Block { - pub brace_token: token::Brace, - /// Statements in a block - pub stmts: Vec<Stmt>, - } -} - -#[cfg(feature = "full")] -ast_enum! { - /// A statement, usually ending in a semicolon. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub enum Stmt { - /// A local (let) binding. - Local(Local), - - /// An item definition. - Item(Item), - - /// Expr without trailing semicolon. - Expr(Expr), - - /// Expression with trailing semicolon. - Semi(Expr, Token![;]), - } -} - -#[cfg(feature = "full")] -ast_struct! { - /// A local `let` binding: `let x: u64 = s.parse()?`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct Local { - pub attrs: Vec<Attribute>, - pub let_token: Token![let], - pub pats: Punctuated<Pat, Token![|]>, - pub ty: Option<(Token![:], Box<Type>)>, - pub init: Option<(Token![=], Box<Expr>)>, - pub semi_token: Token![;], - } -} - -#[cfg(feature = "full")] -ast_enum_of_structs! { - /// A pattern in a local binding, function signature, match expression, or - /// various other places. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Pat { - /// A pattern that matches any value: `_`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Wild(PatWild { - pub underscore_token: Token![_], - }), - - /// A pattern that binds a new variable: `ref mut binding @ SUBPATTERN`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Ident(PatIdent { - pub by_ref: Option<Token![ref]>, - pub mutability: Option<Token![mut]>, - pub ident: Ident, - pub subpat: Option<(Token![@], Box<Pat>)>, - }), - - /// A struct or struct variant pattern: `Variant { x, y, .. }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Struct(PatStruct { - pub path: Path, - pub brace_token: token::Brace, - pub fields: Punctuated<FieldPat, Token![,]>, - pub dot2_token: Option<Token![..]>, - }), - - /// A tuple struct or tuple variant pattern: `Variant(x, y, .., z)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub TupleStruct(PatTupleStruct { - pub path: Path, - pub pat: PatTuple, - }), - - /// A path pattern like `Color::Red`, optionally qualified with a - /// self-type. - /// - /// Unqualified path patterns can legally refer to variants, structs, - /// constants or associated constants. Qualified path patterns like - /// `<A>::B::C` and `<A as Trait>::B::C` can only legally refer to - /// associated constants. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Path(PatPath { - pub qself: Option<QSelf>, - pub path: Path, - }), - - /// A tuple pattern: `(a, b)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Tuple(PatTuple { - pub paren_token: token::Paren, - pub front: Punctuated<Pat, Token![,]>, - pub dot2_token: Option<Token![..]>, - pub comma_token: Option<Token![,]>, - pub back: Punctuated<Pat, Token![,]>, - }), - - /// A box pattern: `box v`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Box(PatBox { - pub box_token: Token![box], - pub pat: Box<Pat>, - }), - - /// A reference pattern: `&mut (first, second)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Ref(PatRef { - pub and_token: Token![&], - pub mutability: Option<Token![mut]>, - pub pat: Box<Pat>, - }), - - /// A literal pattern: `0`. - /// - /// This holds an `Expr` rather than a `Lit` because negative numbers - /// are represented as an `Expr::Unary`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Lit(PatLit { - pub expr: Box<Expr>, - }), - - /// A range pattern: `1..=2`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Range(PatRange { - pub lo: Box<Expr>, - pub limits: RangeLimits, - pub hi: Box<Expr>, - }), - - /// A dynamically sized slice pattern: `[a, b, i.., y, z]`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Slice(PatSlice { - pub bracket_token: token::Bracket, - pub front: Punctuated<Pat, Token![,]>, - pub middle: Option<Box<Pat>>, - pub dot2_token: Option<Token![..]>, - pub comma_token: Option<Token![,]>, - pub back: Punctuated<Pat, Token![,]>, - }), - - /// A macro in expression position. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Macro(PatMacro { - pub mac: Macro, - }), - - /// Tokens in pattern position not interpreted by Syn. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Verbatim(PatVerbatim #manual_extra_traits { - pub tts: TokenStream, - }), - } -} - -#[cfg(all(feature = "full", feature = "extra-traits"))] -impl Eq for PatVerbatim {} - -#[cfg(all(feature = "full", feature = "extra-traits"))] -impl PartialEq for PatVerbatim { - fn eq(&self, other: &Self) -> bool { - TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) - } -} - -#[cfg(all(feature = "full", feature = "extra-traits"))] -impl Hash for PatVerbatim { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - TokenStreamHelper(&self.tts).hash(state); - } -} - -#[cfg(feature = "full")] -ast_struct! { - /// One arm of a `match` expression: `0...10 => { return true; }`. - /// - /// As in: - /// - /// ```edition2018 - /// # fn f() -> bool { - /// # let n = 0; - /// match n { - /// 0...10 => { - /// return true; - /// } - /// // ... - /// # _ => {} - /// } - /// # false - /// # } - /// ``` - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct Arm { - pub attrs: Vec<Attribute>, - pub leading_vert: Option<Token![|]>, - pub pats: Punctuated<Pat, Token![|]>, - pub guard: Option<(Token![if], Box<Expr>)>, - pub fat_arrow_token: Token![=>], - pub body: Box<Expr>, - pub comma: Option<Token![,]>, - } -} - -#[cfg(feature = "full")] -ast_enum! { - /// Limit types of a range, inclusive or exclusive. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - #[cfg_attr(feature = "clone-impls", derive(Copy))] - pub enum RangeLimits { - /// Inclusive at the beginning, exclusive at the end. - HalfOpen(Token![..]), - /// Inclusive at the beginning and end. - Closed(Token![..=]), - } -} - -#[cfg(feature = "full")] -ast_struct! { - /// A single field in a struct pattern. - /// - /// Patterns like the fields of Foo `{ x, ref y, ref mut z }` are treated - /// the same as `x: x, y: ref y, z: ref mut z` but there is no colon token. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct FieldPat { - pub attrs: Vec<Attribute>, - pub member: Member, - pub colon_token: Option<Token![:]>, - pub pat: Box<Pat>, - } -} - -#[cfg(any(feature = "parsing", feature = "printing"))] -#[cfg(feature = "full")] -fn requires_terminator(expr: &Expr) -> bool { - // see https://github.com/rust-lang/rust/blob/eb8f2586e/src/libsyntax/parse/classify.rs#L17-L37 - match *expr { - Expr::Unsafe(..) - | Expr::Block(..) - | Expr::If(..) - | Expr::Match(..) - | Expr::While(..) - | Expr::Loop(..) - | Expr::ForLoop(..) - | Expr::Async(..) - | Expr::TryBlock(..) => false, - _ => true, - } -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - #[cfg(feature = "full")] - use ext::IdentExt; - use parse::{Parse, ParseStream, Result}; - use path; - - // When we're parsing expressions which occur before blocks, like in an if - // statement's condition, we cannot parse a struct literal. - // - // Struct literals are ambiguous in certain positions - // https://github.com/rust-lang/rfcs/pull/92 - #[derive(Copy, Clone)] - pub struct AllowStruct(bool); - - #[derive(Copy, Clone, PartialEq, PartialOrd)] - enum Precedence { - Any, - Assign, - Range, - Or, - And, - Compare, - BitOr, - BitXor, - BitAnd, - Shift, - Arithmetic, - Term, - Cast, - } - - impl Precedence { - fn of(op: &BinOp) -> Self { - match *op { - BinOp::Add(_) | BinOp::Sub(_) => Precedence::Arithmetic, - BinOp::Mul(_) | BinOp::Div(_) | BinOp::Rem(_) => Precedence::Term, - BinOp::And(_) => Precedence::And, - BinOp::Or(_) => Precedence::Or, - BinOp::BitXor(_) => Precedence::BitXor, - BinOp::BitAnd(_) => Precedence::BitAnd, - BinOp::BitOr(_) => Precedence::BitOr, - BinOp::Shl(_) | BinOp::Shr(_) => Precedence::Shift, - BinOp::Eq(_) - | BinOp::Lt(_) - | BinOp::Le(_) - | BinOp::Ne(_) - | BinOp::Ge(_) - | BinOp::Gt(_) => Precedence::Compare, - BinOp::AddEq(_) - | BinOp::SubEq(_) - | BinOp::MulEq(_) - | BinOp::DivEq(_) - | BinOp::RemEq(_) - | BinOp::BitXorEq(_) - | BinOp::BitAndEq(_) - | BinOp::BitOrEq(_) - | BinOp::ShlEq(_) - | BinOp::ShrEq(_) => Precedence::Assign, - } - } - } - - impl Parse for Expr { - fn parse(input: ParseStream) -> Result<Self> { - ambiguous_expr(input, AllowStruct(true)) - } - } - - #[cfg(feature = "full")] - fn expr_no_struct(input: ParseStream) -> Result<Expr> { - ambiguous_expr(input, AllowStruct(false)) - } - - #[cfg(feature = "full")] - fn parse_expr( - input: ParseStream, - mut lhs: Expr, - allow_struct: AllowStruct, - base: Precedence, - ) -> Result<Expr> { - loop { - if input - .fork() - .parse::<BinOp>() - .ok() - .map_or(false, |op| Precedence::of(&op) >= base) - { - let op: BinOp = input.parse()?; - let precedence = Precedence::of(&op); - let mut rhs = unary_expr(input, allow_struct)?; - loop { - let next = peek_precedence(input); - if next > precedence || next == precedence && precedence == Precedence::Assign { - rhs = parse_expr(input, rhs, allow_struct, next)?; - } else { - break; - } - } - lhs = if precedence == Precedence::Assign { - Expr::AssignOp(ExprAssignOp { - attrs: Vec::new(), - left: Box::new(lhs), - op: op, - right: Box::new(rhs), - }) - } else { - Expr::Binary(ExprBinary { - attrs: Vec::new(), - left: Box::new(lhs), - op: op, - right: Box::new(rhs), - }) - }; - } else if Precedence::Assign >= base - && input.peek(Token![=]) - && !input.peek(Token![==]) - && !input.peek(Token![=>]) - { - let eq_token: Token![=] = input.parse()?; - let mut rhs = unary_expr(input, allow_struct)?; - loop { - let next = peek_precedence(input); - if next >= Precedence::Assign { - rhs = parse_expr(input, rhs, allow_struct, next)?; - } else { - break; - } - } - lhs = Expr::Assign(ExprAssign { - attrs: Vec::new(), - left: Box::new(lhs), - eq_token: eq_token, - right: Box::new(rhs), - }); - } else if Precedence::Range >= base && input.peek(Token![..]) { - let limits: RangeLimits = input.parse()?; - let rhs = if input.is_empty() - || input.peek(Token![,]) - || input.peek(Token![;]) - || !allow_struct.0 && input.peek(token::Brace) - { - None - } else { - let mut rhs = unary_expr(input, allow_struct)?; - loop { - let next = peek_precedence(input); - if next > Precedence::Range { - rhs = parse_expr(input, rhs, allow_struct, next)?; - } else { - break; - } - } - Some(rhs) - }; - lhs = Expr::Range(ExprRange { - attrs: Vec::new(), - from: Some(Box::new(lhs)), - limits: limits, - to: rhs.map(Box::new), - }); - } else if Precedence::Cast >= base && input.peek(Token![as]) { - let as_token: Token![as] = input.parse()?; - let ty = input.call(Type::without_plus)?; - lhs = Expr::Cast(ExprCast { - attrs: Vec::new(), - expr: Box::new(lhs), - as_token: as_token, - ty: Box::new(ty), - }); - } else if Precedence::Cast >= base && input.peek(Token![:]) && !input.peek(Token![::]) { - let colon_token: Token![:] = input.parse()?; - let ty = input.call(Type::without_plus)?; - lhs = Expr::Type(ExprType { - attrs: Vec::new(), - expr: Box::new(lhs), - colon_token: colon_token, - ty: Box::new(ty), - }); - } else { - break; - } - } - Ok(lhs) - } - - #[cfg(not(feature = "full"))] - fn parse_expr( - input: ParseStream, - mut lhs: Expr, - allow_struct: AllowStruct, - base: Precedence, - ) -> Result<Expr> { - loop { - if input - .fork() - .parse::<BinOp>() - .ok() - .map_or(false, |op| Precedence::of(&op) >= base) - { - let op: BinOp = input.parse()?; - let precedence = Precedence::of(&op); - let mut rhs = unary_expr(input, allow_struct)?; - loop { - let next = peek_precedence(input); - if next > precedence || next == precedence && precedence == Precedence::Assign { - rhs = parse_expr(input, rhs, allow_struct, next)?; - } else { - break; - } - } - lhs = Expr::Binary(ExprBinary { - attrs: Vec::new(), - left: Box::new(lhs), - op: op, - right: Box::new(rhs), - }); - } else if Precedence::Cast >= base && input.peek(Token![as]) { - let as_token: Token![as] = input.parse()?; - let ty = input.call(Type::without_plus)?; - lhs = Expr::Cast(ExprCast { - attrs: Vec::new(), - expr: Box::new(lhs), - as_token: as_token, - ty: Box::new(ty), - }); - } else { - break; - } - } - Ok(lhs) - } - - fn peek_precedence(input: ParseStream) -> Precedence { - if let Ok(op) = input.fork().parse() { - Precedence::of(&op) - } else if input.peek(Token![=]) && !input.peek(Token![=>]) { - Precedence::Assign - } else if input.peek(Token![..]) { - Precedence::Range - } else if input.peek(Token![as]) || input.peek(Token![:]) && !input.peek(Token![::]) { - Precedence::Cast - } else { - Precedence::Any - } - } - - // Parse an arbitrary expression. - fn ambiguous_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - let lhs = unary_expr(input, allow_struct)?; - parse_expr(input, lhs, allow_struct, Precedence::Any) - } - - // <UnOp> <trailer> - // & <trailer> - // &mut <trailer> - // box <trailer> - #[cfg(feature = "full")] - fn unary_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - // TODO: optimize using advance_to - let ahead = input.fork(); - ahead.call(Attribute::parse_outer)?; - if ahead.peek(Token![&]) - || ahead.peek(Token![box]) - || ahead.peek(Token![*]) - || ahead.peek(Token![!]) - || ahead.peek(Token![-]) - { - let attrs = input.call(Attribute::parse_outer)?; - if input.peek(Token![&]) { - Ok(Expr::Reference(ExprReference { - attrs: attrs, - and_token: input.parse()?, - mutability: input.parse()?, - expr: Box::new(unary_expr(input, allow_struct)?), - })) - } else if input.peek(Token![box]) { - Ok(Expr::Box(ExprBox { - attrs: attrs, - box_token: input.parse()?, - expr: Box::new(unary_expr(input, allow_struct)?), - })) - } else { - Ok(Expr::Unary(ExprUnary { - attrs: attrs, - op: input.parse()?, - expr: Box::new(unary_expr(input, allow_struct)?), - })) - } - } else { - trailer_expr(input, allow_struct) - } - } - - #[cfg(not(feature = "full"))] - fn unary_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - // TODO: optimize using advance_to - let ahead = input.fork(); - ahead.call(Attribute::parse_outer)?; - if ahead.peek(Token![*]) || ahead.peek(Token![!]) || ahead.peek(Token![-]) { - Ok(Expr::Unary(ExprUnary { - attrs: input.call(Attribute::parse_outer)?, - op: input.parse()?, - expr: Box::new(unary_expr(input, allow_struct)?), - })) - } else { - trailer_expr(input, allow_struct) - } - } - - // <atom> (..<args>) ... - // <atom> . <ident> (..<args>) ... - // <atom> . <ident> ... - // <atom> . <lit> ... - // <atom> [ <expr> ] ... - // <atom> ? ... - #[cfg(feature = "full")] - fn trailer_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - if input.peek(token::Group) { - return input.call(expr_group).map(Expr::Group); - } - - let outer_attrs = input.call(Attribute::parse_outer)?; - - let atom = atom_expr(input, allow_struct)?; - let mut e = trailer_helper(input, atom)?; - - let inner_attrs = e.replace_attrs(Vec::new()); - let attrs = private::attrs(outer_attrs, inner_attrs); - e.replace_attrs(attrs); - Ok(e) - } - - #[cfg(feature = "full")] - fn trailer_helper(input: ParseStream, mut e: Expr) -> Result<Expr> { - loop { - if input.peek(token::Paren) { - let content; - e = Expr::Call(ExprCall { - attrs: Vec::new(), - func: Box::new(e), - paren_token: parenthesized!(content in input), - args: content.parse_terminated(Expr::parse)?, - }); - } else if input.peek(Token![.]) && !input.peek(Token![..]) { - let dot_token: Token![.] = input.parse()?; - let member: Member = input.parse()?; - let turbofish = if member.is_named() && input.peek(Token![::]) { - Some(MethodTurbofish { - colon2_token: input.parse()?, - lt_token: input.parse()?, - args: { - let mut args = Punctuated::new(); - loop { - if input.peek(Token![>]) { - break; - } - let value = input.call(generic_method_argument)?; - args.push_value(value); - if input.peek(Token![>]) { - break; - } - let punct = input.parse()?; - args.push_punct(punct); - } - args - }, - gt_token: input.parse()?, - }) - } else { - None - }; - - if turbofish.is_some() || input.peek(token::Paren) { - if let Member::Named(method) = member { - let content; - e = Expr::MethodCall(ExprMethodCall { - attrs: Vec::new(), - receiver: Box::new(e), - dot_token: dot_token, - method: method, - turbofish: turbofish, - paren_token: parenthesized!(content in input), - args: content.parse_terminated(Expr::parse)?, - }); - continue; - } - } - - e = Expr::Field(ExprField { - attrs: Vec::new(), - base: Box::new(e), - dot_token: dot_token, - member: member, - }); - } else if input.peek(token::Bracket) { - let content; - e = Expr::Index(ExprIndex { - attrs: Vec::new(), - expr: Box::new(e), - bracket_token: bracketed!(content in input), - index: content.parse()?, - }); - } else if input.peek(Token![?]) { - e = Expr::Try(ExprTry { - attrs: Vec::new(), - expr: Box::new(e), - question_token: input.parse()?, - }); - } else { - break; - } - } - Ok(e) - } - - #[cfg(not(feature = "full"))] - fn trailer_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - let mut e = atom_expr(input, allow_struct)?; - - loop { - if input.peek(token::Paren) { - let content; - e = Expr::Call(ExprCall { - attrs: Vec::new(), - func: Box::new(e), - paren_token: parenthesized!(content in input), - args: content.parse_terminated(Expr::parse)?, - }); - } else if input.peek(Token![.]) { - e = Expr::Field(ExprField { - attrs: Vec::new(), - base: Box::new(e), - dot_token: input.parse()?, - member: input.parse()?, - }); - } else if input.peek(token::Bracket) { - let content; - e = Expr::Index(ExprIndex { - attrs: Vec::new(), - expr: Box::new(e), - bracket_token: bracketed!(content in input), - index: content.parse()?, - }); - } else { - break; - } - } - - Ok(e) - } - - // Parse all atomic expressions which don't have to worry about precedence - // interactions, as they are fully contained. - #[cfg(feature = "full")] - fn atom_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - if input.peek(token::Group) { - input.call(expr_group).map(Expr::Group) - } else if input.peek(Lit) { - input.parse().map(Expr::Lit) - } else if input.peek(Token![async]) - && (input.peek2(token::Brace) || input.peek2(Token![move]) && input.peek3(token::Brace)) - { - input.call(expr_async).map(Expr::Async) - } else if input.peek(Token![try]) && input.peek2(token::Brace) { - input.call(expr_try_block).map(Expr::TryBlock) - } else if input.peek(Token![|]) - || input.peek(Token![async]) && (input.peek2(Token![|]) || input.peek2(Token![move])) - || input.peek(Token![static]) - || input.peek(Token![move]) - { - expr_closure(input, allow_struct).map(Expr::Closure) - } else if input.peek(Ident) - || input.peek(Token![::]) - || input.peek(Token![<]) - || input.peek(Token![self]) - || input.peek(Token![Self]) - || input.peek(Token![super]) - || input.peek(Token![extern]) - || input.peek(Token![crate]) - { - path_or_macro_or_struct(input, allow_struct) - } else if input.peek(token::Paren) { - paren_or_tuple(input) - } else if input.peek(Token![break]) { - expr_break(input, allow_struct).map(Expr::Break) - } else if input.peek(Token![continue]) { - input.call(expr_continue).map(Expr::Continue) - } else if input.peek(Token![return]) { - expr_ret(input, allow_struct).map(Expr::Return) - } else if input.peek(token::Bracket) { - array_or_repeat(input) - } else if input.peek(Token![let]) { - input.call(expr_let).map(Expr::Let) - } else if input.peek(Token![if]) { - input.parse().map(Expr::If) - } else if input.peek(Token![while]) { - input.parse().map(Expr::While) - } else if input.peek(Token![for]) { - input.parse().map(Expr::ForLoop) - } else if input.peek(Token![loop]) { - input.parse().map(Expr::Loop) - } else if input.peek(Token![match]) { - input.parse().map(Expr::Match) - } else if input.peek(Token![yield]) { - input.call(expr_yield).map(Expr::Yield) - } else if input.peek(Token![unsafe]) { - input.call(expr_unsafe).map(Expr::Unsafe) - } else if input.peek(token::Brace) { - input.call(expr_block).map(Expr::Block) - } else if input.peek(Token![..]) { - expr_range(input, allow_struct).map(Expr::Range) - } else if input.peek(Lifetime) { - let the_label: Label = input.parse()?; - let mut expr = if input.peek(Token![while]) { - Expr::While(input.parse()?) - } else if input.peek(Token![for]) { - Expr::ForLoop(input.parse()?) - } else if input.peek(Token![loop]) { - Expr::Loop(input.parse()?) - } else if input.peek(token::Brace) { - Expr::Block(input.call(expr_block)?) - } else { - return Err(input.error("expected loop or block expression")); - }; - match expr { - Expr::While(ExprWhile { ref mut label, .. }) - | Expr::ForLoop(ExprForLoop { ref mut label, .. }) - | Expr::Loop(ExprLoop { ref mut label, .. }) - | Expr::Block(ExprBlock { ref mut label, .. }) => *label = Some(the_label), - _ => unreachable!(), - } - Ok(expr) - } else { - Err(input.error("expected expression")) - } - } - - #[cfg(not(feature = "full"))] - fn atom_expr(input: ParseStream, _allow_struct: AllowStruct) -> Result<Expr> { - if input.peek(Lit) { - input.parse().map(Expr::Lit) - } else if input.peek(token::Paren) { - input.call(expr_paren).map(Expr::Paren) - } else if input.peek(Ident) - || input.peek(Token![::]) - || input.peek(Token![<]) - || input.peek(Token![self]) - || input.peek(Token![Self]) - || input.peek(Token![super]) - || input.peek(Token![extern]) - || input.peek(Token![crate]) - { - input.parse().map(Expr::Path) - } else { - Err(input.error("unsupported expression; enable syn's features=[\"full\"]")) - } - } - - #[cfg(feature = "full")] - fn path_or_macro_or_struct(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - let expr: ExprPath = input.parse()?; - if expr.qself.is_some() { - return Ok(Expr::Path(expr)); - } - - if input.peek(Token![!]) && !input.peek(Token![!=]) { - let mut contains_arguments = false; - for segment in &expr.path.segments { - match segment.arguments { - PathArguments::None => {} - PathArguments::AngleBracketed(_) | PathArguments::Parenthesized(_) => { - contains_arguments = true; - } - } - } - - if !contains_arguments { - let bang_token: Token![!] = input.parse()?; - let (delimiter, tts) = mac::parse_delimiter(input)?; - return Ok(Expr::Macro(ExprMacro { - attrs: Vec::new(), - mac: Macro { - path: expr.path, - bang_token: bang_token, - delimiter: delimiter, - tts: tts, - }, - })); - } - } - - if allow_struct.0 && input.peek(token::Brace) { - let outer_attrs = Vec::new(); - expr_struct_helper(input, outer_attrs, expr.path).map(Expr::Struct) - } else { - Ok(Expr::Path(expr)) - } - } - - #[cfg(feature = "full")] - fn paren_or_tuple(input: ParseStream) -> Result<Expr> { - let content; - let paren_token = parenthesized!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - if content.is_empty() { - return Ok(Expr::Tuple(ExprTuple { - attrs: inner_attrs, - paren_token: paren_token, - elems: Punctuated::new(), - })); - } - - let first: Expr = content.parse()?; - if content.is_empty() { - return Ok(Expr::Paren(ExprParen { - attrs: inner_attrs, - paren_token: paren_token, - expr: Box::new(first), - })); - } - - let mut elems = Punctuated::new(); - elems.push_value(first); - while !content.is_empty() { - let punct = content.parse()?; - elems.push_punct(punct); - if content.is_empty() { - break; - } - let value = content.parse()?; - elems.push_value(value); - } - Ok(Expr::Tuple(ExprTuple { - attrs: inner_attrs, - paren_token: paren_token, - elems: elems, - })) - } - - #[cfg(feature = "full")] - fn array_or_repeat(input: ParseStream) -> Result<Expr> { - let content; - let bracket_token = bracketed!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - if content.is_empty() { - return Ok(Expr::Array(ExprArray { - attrs: inner_attrs, - bracket_token: bracket_token, - elems: Punctuated::new(), - })); - } - - let first: Expr = content.parse()?; - if content.is_empty() || content.peek(Token![,]) { - let mut elems = Punctuated::new(); - elems.push_value(first); - while !content.is_empty() { - let punct = content.parse()?; - elems.push_punct(punct); - if content.is_empty() { - break; - } - let value = content.parse()?; - elems.push_value(value); - } - Ok(Expr::Array(ExprArray { - attrs: inner_attrs, - bracket_token: bracket_token, - elems: elems, - })) - } else if content.peek(Token![;]) { - let semi_token: Token![;] = content.parse()?; - let len: Expr = content.parse()?; - Ok(Expr::Repeat(ExprRepeat { - attrs: inner_attrs, - bracket_token: bracket_token, - expr: Box::new(first), - semi_token: semi_token, - len: Box::new(len), - })) - } else { - Err(content.error("expected `,` or `;`")) - } - } - - #[cfg(feature = "full")] - fn expr_early(input: ParseStream) -> Result<Expr> { - let mut attrs = input.call(Attribute::parse_outer)?; - let mut expr = if input.peek(Token![if]) { - Expr::If(input.parse()?) - } else if input.peek(Token![while]) { - Expr::While(input.parse()?) - } else if input.peek(Token![for]) { - Expr::ForLoop(input.parse()?) - } else if input.peek(Token![loop]) { - Expr::Loop(input.parse()?) - } else if input.peek(Token![match]) { - Expr::Match(input.parse()?) - } else if input.peek(Token![try]) && input.peek2(token::Brace) { - Expr::TryBlock(input.call(expr_try_block)?) - } else if input.peek(Token![unsafe]) { - Expr::Unsafe(input.call(expr_unsafe)?) - } else if input.peek(token::Brace) { - Expr::Block(input.call(expr_block)?) - } else { - let allow_struct = AllowStruct(true); - let mut expr = unary_expr(input, allow_struct)?; - - attrs.extend(expr.replace_attrs(Vec::new())); - expr.replace_attrs(attrs); - - return parse_expr(input, expr, allow_struct, Precedence::Any); - }; - - if input.peek(Token![.]) || input.peek(Token![?]) { - expr = trailer_helper(input, expr)?; - - attrs.extend(expr.replace_attrs(Vec::new())); - expr.replace_attrs(attrs); - - let allow_struct = AllowStruct(true); - return parse_expr(input, expr, allow_struct, Precedence::Any); - } - - attrs.extend(expr.replace_attrs(Vec::new())); - expr.replace_attrs(attrs); - Ok(expr) - } - - impl Parse for ExprLit { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ExprLit { - attrs: Vec::new(), - lit: input.parse()?, - }) - } - } - - #[cfg(feature = "full")] - fn expr_group(input: ParseStream) -> Result<ExprGroup> { - let group = private::parse_group(input)?; - Ok(ExprGroup { - attrs: Vec::new(), - group_token: group.token, - expr: group.content.parse()?, - }) - } - - #[cfg(not(feature = "full"))] - fn expr_paren(input: ParseStream) -> Result<ExprParen> { - let content; - Ok(ExprParen { - attrs: Vec::new(), - paren_token: parenthesized!(content in input), - expr: content.parse()?, - }) - } - - #[cfg(feature = "full")] - fn generic_method_argument(input: ParseStream) -> Result<GenericMethodArgument> { - // TODO parse const generics as well - input.parse().map(GenericMethodArgument::Type) - } - - #[cfg(feature = "full")] - fn expr_let(input: ParseStream) -> Result<ExprLet> { - Ok(ExprLet { - attrs: Vec::new(), - let_token: input.parse()?, - pats: { - let mut pats = Punctuated::new(); - input.parse::<Option<Token![|]>>()?; - let value: Pat = input.parse()?; - pats.push_value(value); - while input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=]) { - let punct = input.parse()?; - pats.push_punct(punct); - let value: Pat = input.parse()?; - pats.push_value(value); - } - pats - }, - eq_token: input.parse()?, - expr: Box::new(input.call(expr_no_struct)?), - }) - } - - #[cfg(feature = "full")] - impl Parse for ExprIf { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ExprIf { - attrs: Vec::new(), - if_token: input.parse()?, - cond: Box::new(input.call(expr_no_struct)?), - then_branch: input.parse()?, - else_branch: { - if input.peek(Token![else]) { - Some(input.call(else_block)?) - } else { - None - } - }, - }) - } - } - - #[cfg(feature = "full")] - fn else_block(input: ParseStream) -> Result<(Token![else], Box<Expr>)> { - let else_token: Token![else] = input.parse()?; - - let lookahead = input.lookahead1(); - let else_branch = if input.peek(Token![if]) { - input.parse().map(Expr::If)? - } else if input.peek(token::Brace) { - Expr::Block(ExprBlock { - attrs: Vec::new(), - label: None, - block: input.parse()?, - }) - } else { - return Err(lookahead.error()); - }; - - Ok((else_token, Box::new(else_branch))) - } - - #[cfg(feature = "full")] - impl Parse for ExprForLoop { - fn parse(input: ParseStream) -> Result<Self> { - let label: Option<Label> = input.parse()?; - let for_token: Token![for] = input.parse()?; - let pat: Pat = input.parse()?; - let in_token: Token![in] = input.parse()?; - let expr: Expr = input.call(expr_no_struct)?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; - - Ok(ExprForLoop { - attrs: inner_attrs, - label: label, - for_token: for_token, - pat: Box::new(pat), - in_token: in_token, - expr: Box::new(expr), - body: Block { - brace_token: brace_token, - stmts: stmts, - }, - }) - } - } - - #[cfg(feature = "full")] - impl Parse for ExprLoop { - fn parse(input: ParseStream) -> Result<Self> { - let label: Option<Label> = input.parse()?; - let loop_token: Token![loop] = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; - - Ok(ExprLoop { - attrs: inner_attrs, - label: label, - loop_token: loop_token, - body: Block { - brace_token: brace_token, - stmts: stmts, - }, - }) - } - } - - #[cfg(feature = "full")] - impl Parse for ExprMatch { - fn parse(input: ParseStream) -> Result<Self> { - let match_token: Token![match] = input.parse()?; - let expr = expr_no_struct(input)?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - - let mut arms = Vec::new(); - while !content.is_empty() { - arms.push(content.call(Arm::parse)?); - } - - Ok(ExprMatch { - attrs: inner_attrs, - match_token: match_token, - expr: Box::new(expr), - brace_token: brace_token, - arms: arms, - }) - } - } - - #[cfg(all(feature = "full", feature = "printing"))] - impl Parse for ExprInPlace { - fn parse(input: ParseStream) -> Result<Self> { - let msg = "placement expression has been removed from Rust and is no longer parsed"; - Err(input.error(msg)) - } - } - - macro_rules! impl_by_parsing_expr { - ( - $( - $expr_type:ty, $variant:ident, $msg:expr, - )* - ) => { - $( - #[cfg(all(feature = "full", feature = "printing"))] - impl Parse for $expr_type { - fn parse(input: ParseStream) -> Result<Self> { - let mut expr: Expr = input.parse()?; - loop { - match expr { - Expr::$variant(inner) => return Ok(inner), - Expr::Group(next) => expr = *next.expr, - _ => return Err(Error::new_spanned(expr, $msg)), - } - } - } - } - )* - }; - } - - impl_by_parsing_expr! { - ExprBox, Box, "expected box expression", - ExprArray, Array, "expected slice literal expression", - ExprCall, Call, "expected function call expression", - ExprMethodCall, MethodCall, "expected method call expression", - ExprTuple, Tuple, "expected tuple expression", - ExprBinary, Binary, "expected binary operation", - ExprUnary, Unary, "expected unary operation", - ExprCast, Cast, "expected cast expression", - ExprType, Type, "expected type ascription expression", - ExprLet, Let, "expected let guard", - ExprClosure, Closure, "expected closure expression", - ExprUnsafe, Unsafe, "expected unsafe block", - ExprBlock, Block, "expected blocked scope", - ExprAssign, Assign, "expected assignment expression", - ExprAssignOp, AssignOp, "expected compound assignment expression", - ExprField, Field, "expected struct field access", - ExprIndex, Index, "expected indexing expression", - ExprRange, Range, "expected range expression", - ExprReference, Reference, "expected referencing operation", - ExprBreak, Break, "expected break expression", - ExprContinue, Continue, "expected continue expression", - ExprReturn, Return, "expected return expression", - ExprMacro, Macro, "expected macro invocation expression", - ExprStruct, Struct, "expected struct literal expression", - ExprRepeat, Repeat, "expected array literal constructed from one repeated element", - ExprParen, Paren, "expected parenthesized expression", - ExprTry, Try, "expected try expression", - ExprAsync, Async, "expected async block", - ExprTryBlock, TryBlock, "expected try block", - ExprYield, Yield, "expected yield expression", - } - - #[cfg(feature = "full")] - fn expr_try_block(input: ParseStream) -> Result<ExprTryBlock> { - Ok(ExprTryBlock { - attrs: Vec::new(), - try_token: input.parse()?, - block: input.parse()?, - }) - } - - #[cfg(feature = "full")] - fn expr_yield(input: ParseStream) -> Result<ExprYield> { - Ok(ExprYield { - attrs: Vec::new(), - yield_token: input.parse()?, - expr: { - if !input.is_empty() && !input.peek(Token![,]) && !input.peek(Token![;]) { - Some(input.parse()?) - } else { - None - } - }, - }) - } - - #[cfg(feature = "full")] - fn expr_closure(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprClosure> { - let asyncness: Option<Token![async]> = input.parse()?; - let movability: Option<Token![static]> = if asyncness.is_none() { - input.parse()? - } else { - None - }; - let capture: Option<Token![move]> = input.parse()?; - let or1_token: Token![|] = input.parse()?; - - let mut inputs = Punctuated::new(); - loop { - if input.peek(Token![|]) { - break; - } - let value = fn_arg(input)?; - inputs.push_value(value); - if input.peek(Token![|]) { - break; - } - let punct: Token![,] = input.parse()?; - inputs.push_punct(punct); - } - - let or2_token: Token![|] = input.parse()?; - - let (output, body) = if input.peek(Token![->]) { - let arrow_token: Token![->] = input.parse()?; - let ty: Type = input.parse()?; - let body: Block = input.parse()?; - let output = ReturnType::Type(arrow_token, Box::new(ty)); - let block = Expr::Block(ExprBlock { - attrs: Vec::new(), - label: None, - block: body, - }); - (output, block) - } else { - let body = ambiguous_expr(input, allow_struct)?; - (ReturnType::Default, body) - }; - - Ok(ExprClosure { - attrs: Vec::new(), - asyncness: asyncness, - movability: movability, - capture: capture, - or1_token: or1_token, - inputs: inputs, - or2_token: or2_token, - output: output, - body: Box::new(body), - }) - } - - #[cfg(feature = "full")] - fn expr_async(input: ParseStream) -> Result<ExprAsync> { - Ok(ExprAsync { - attrs: Vec::new(), - async_token: input.parse()?, - capture: input.parse()?, - block: input.parse()?, - }) - } - - #[cfg(feature = "full")] - fn fn_arg(input: ParseStream) -> Result<FnArg> { - let pat: Pat = input.parse()?; - - if input.peek(Token![:]) { - Ok(FnArg::Captured(ArgCaptured { - pat: pat, - colon_token: input.parse()?, - ty: input.parse()?, - })) - } else { - Ok(FnArg::Inferred(pat)) - } - } - - #[cfg(feature = "full")] - impl Parse for ExprWhile { - fn parse(input: ParseStream) -> Result<Self> { - let label: Option<Label> = input.parse()?; - let while_token: Token![while] = input.parse()?; - let cond = expr_no_struct(input)?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; - - Ok(ExprWhile { - attrs: inner_attrs, - label: label, - while_token: while_token, - cond: Box::new(cond), - body: Block { - brace_token: brace_token, - stmts: stmts, - }, - }) - } - } - - #[cfg(feature = "full")] - impl Parse for Label { - fn parse(input: ParseStream) -> Result<Self> { - Ok(Label { - name: input.parse()?, - colon_token: input.parse()?, - }) - } - } - - #[cfg(feature = "full")] - impl Parse for Option<Label> { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Lifetime) { - input.parse().map(Some) - } else { - Ok(None) - } - } - } - - #[cfg(feature = "full")] - fn expr_continue(input: ParseStream) -> Result<ExprContinue> { - Ok(ExprContinue { - attrs: Vec::new(), - continue_token: input.parse()?, - label: input.parse()?, - }) - } - - #[cfg(feature = "full")] - fn expr_break(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprBreak> { - Ok(ExprBreak { - attrs: Vec::new(), - break_token: input.parse()?, - label: input.parse()?, - expr: { - if input.is_empty() - || input.peek(Token![,]) - || input.peek(Token![;]) - || !allow_struct.0 && input.peek(token::Brace) - { - None - } else { - let expr = ambiguous_expr(input, allow_struct)?; - Some(Box::new(expr)) - } - }, - }) - } - - #[cfg(feature = "full")] - fn expr_ret(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprReturn> { - Ok(ExprReturn { - attrs: Vec::new(), - return_token: input.parse()?, - expr: { - if input.is_empty() || input.peek(Token![,]) || input.peek(Token![;]) { - None - } else { - // NOTE: return is greedy and eats blocks after it even when in a - // position where structs are not allowed, such as in if statement - // conditions. For example: - // - // if return { println!("A") } {} // Prints "A" - let expr = ambiguous_expr(input, allow_struct)?; - Some(Box::new(expr)) - } - }, - }) - } - - #[cfg(feature = "full")] - impl Parse for FieldValue { - fn parse(input: ParseStream) -> Result<Self> { - let member: Member = input.parse()?; - let (colon_token, value) = if input.peek(Token![:]) || !member.is_named() { - let colon_token: Token![:] = input.parse()?; - let value: Expr = input.parse()?; - (Some(colon_token), value) - } else if let Member::Named(ref ident) = member { - let value = Expr::Path(ExprPath { - attrs: Vec::new(), - qself: None, - path: Path::from(ident.clone()), - }); - (None, value) - } else { - unreachable!() - }; - - Ok(FieldValue { - attrs: Vec::new(), - member: member, - colon_token: colon_token, - expr: value, - }) - } - } - - #[cfg(feature = "full")] - fn expr_struct_helper( - input: ParseStream, - outer_attrs: Vec<Attribute>, - path: Path, - ) -> Result<ExprStruct> { - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - - let mut fields = Punctuated::new(); - loop { - let attrs = content.call(Attribute::parse_outer)?; - // TODO: optimize using advance_to - if content.fork().parse::<Member>().is_err() { - if attrs.is_empty() { - break; - } else { - return Err(content.error("expected struct field")); - } - } - - fields.push(FieldValue { - attrs: attrs, - ..content.parse()? - }); - - if !content.peek(Token![,]) { - break; - } - let punct: Token![,] = content.parse()?; - fields.push_punct(punct); - } - - let (dot2_token, rest) = if fields.empty_or_trailing() && content.peek(Token![..]) { - let dot2_token: Token![..] = content.parse()?; - let rest: Expr = content.parse()?; - (Some(dot2_token), Some(Box::new(rest))) - } else { - (None, None) - }; - - Ok(ExprStruct { - attrs: private::attrs(outer_attrs, inner_attrs), - brace_token: brace_token, - path: path, - fields: fields, - dot2_token: dot2_token, - rest: rest, - }) - } - - #[cfg(feature = "full")] - fn expr_unsafe(input: ParseStream) -> Result<ExprUnsafe> { - let unsafe_token: Token![unsafe] = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; - - Ok(ExprUnsafe { - attrs: inner_attrs, - unsafe_token: unsafe_token, - block: Block { - brace_token: brace_token, - stmts: stmts, - }, - }) - } - - #[cfg(feature = "full")] - pub fn expr_block(input: ParseStream) -> Result<ExprBlock> { - let label: Option<Label> = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; - - Ok(ExprBlock { - attrs: inner_attrs, - label: label, - block: Block { - brace_token: brace_token, - stmts: stmts, - }, - }) - } - - #[cfg(feature = "full")] - fn expr_range(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprRange> { - Ok(ExprRange { - attrs: Vec::new(), - from: None, - limits: input.parse()?, - to: { - if input.is_empty() - || input.peek(Token![,]) - || input.peek(Token![;]) - || !allow_struct.0 && input.peek(token::Brace) - { - None - } else { - let to = ambiguous_expr(input, allow_struct)?; - Some(Box::new(to)) - } - }, - }) - } - - #[cfg(feature = "full")] - impl Parse for RangeLimits { - fn parse(input: ParseStream) -> Result<Self> { - let lookahead = input.lookahead1(); - if lookahead.peek(Token![..=]) { - input.parse().map(RangeLimits::Closed) - } else if lookahead.peek(Token![...]) { - let dot3: Token![...] = input.parse()?; - Ok(RangeLimits::Closed(Token![..=](dot3.spans))) - } else if lookahead.peek(Token![..]) { - input.parse().map(RangeLimits::HalfOpen) - } else { - Err(lookahead.error()) - } - } - } - - impl Parse for ExprPath { - fn parse(input: ParseStream) -> Result<Self> { - #[cfg(not(feature = "full"))] - let attrs = Vec::new(); - #[cfg(feature = "full")] - let attrs = input.call(Attribute::parse_outer)?; - - let (qself, path) = path::parsing::qpath(input, true)?; - - Ok(ExprPath { - attrs: attrs, - qself: qself, - path: path, - }) - } - } - - #[cfg(feature = "full")] - impl Parse for Block { - fn parse(input: ParseStream) -> Result<Self> { - let content; - Ok(Block { - brace_token: braced!(content in input), - stmts: content.call(Block::parse_within)?, - }) - } - } - - #[cfg(feature = "full")] - impl Block { - /// Parse the body of a block as zero or more statements, possibly - /// including one trailing expression. - /// - /// *This function is available if Syn is built with the `"parsing"` - /// feature.* - /// - /// # Example - /// - /// ```edition2018 - /// use syn::{braced, token, Attribute, Block, Ident, Result, Stmt, Token}; - /// use syn::parse::{Parse, ParseStream}; - /// - /// // Parse a function with no generics or parameter list. - /// // - /// // fn playground { - /// // let mut x = 1; - /// // x += 1; - /// // println!("{}", x); - /// // } - /// struct MiniFunction { - /// attrs: Vec<Attribute>, - /// fn_token: Token![fn], - /// name: Ident, - /// brace_token: token::Brace, - /// stmts: Vec<Stmt>, - /// } - /// - /// impl Parse for MiniFunction { - /// fn parse(input: ParseStream) -> Result<Self> { - /// let outer_attrs = input.call(Attribute::parse_outer)?; - /// let fn_token: Token![fn] = input.parse()?; - /// let name: Ident = input.parse()?; - /// - /// let content; - /// let brace_token = braced!(content in input); - /// let inner_attrs = content.call(Attribute::parse_inner)?; - /// let stmts = content.call(Block::parse_within)?; - /// - /// Ok(MiniFunction { - /// attrs: { - /// let mut attrs = outer_attrs; - /// attrs.extend(inner_attrs); - /// attrs - /// }, - /// fn_token: fn_token, - /// name: name, - /// brace_token: brace_token, - /// stmts: stmts, - /// }) - /// } - /// } - /// ``` - pub fn parse_within(input: ParseStream) -> Result<Vec<Stmt>> { - let mut stmts = Vec::new(); - loop { - while input.peek(Token![;]) { - input.parse::<Token![;]>()?; - } - if input.is_empty() { - break; - } - let s = parse_stmt(input, true)?; - let requires_semicolon = if let Stmt::Expr(ref s) = s { - requires_terminator(s) - } else { - false - }; - stmts.push(s); - if input.is_empty() { - break; - } else if requires_semicolon { - return Err(input.error("unexpected token")); - } - } - Ok(stmts) - } - } - - #[cfg(feature = "full")] - impl Parse for Stmt { - fn parse(input: ParseStream) -> Result<Self> { - parse_stmt(input, false) - } - } - - #[cfg(feature = "full")] - fn parse_stmt(input: ParseStream, allow_nosemi: bool) -> Result<Stmt> { - // TODO: optimize using advance_to - let ahead = input.fork(); - ahead.call(Attribute::parse_outer)?; - - if { - let ahead = ahead.fork(); - // Only parse braces here; paren and bracket will get parsed as - // expression statements - ahead.call(Path::parse_mod_style).is_ok() - && ahead.parse::<Token![!]>().is_ok() - && (ahead.peek(token::Brace) || ahead.peek(Ident)) - } { - stmt_mac(input) - } else if ahead.peek(Token![let]) { - stmt_local(input).map(Stmt::Local) - } else if ahead.peek(Token![pub]) - || ahead.peek(Token![crate]) && !ahead.peek2(Token![::]) - || ahead.peek(Token![extern]) && !ahead.peek2(Token![::]) - || ahead.peek(Token![use]) - || ahead.peek(Token![static]) && (ahead.peek2(Token![mut]) || ahead.peek2(Ident)) - || ahead.peek(Token![const]) - || ahead.peek(Token![unsafe]) && !ahead.peek2(token::Brace) - || ahead.peek(Token![async]) - && (ahead.peek2(Token![unsafe]) - || ahead.peek2(Token![extern]) - || ahead.peek2(Token![fn])) - || ahead.peek(Token![fn]) - || ahead.peek(Token![mod]) - || ahead.peek(Token![type]) - || ahead.peek(Token![existential]) && ahead.peek2(Token![type]) - || ahead.peek(Token![struct]) - || ahead.peek(Token![enum]) - || ahead.peek(Token![union]) && ahead.peek2(Ident) - || ahead.peek(Token![auto]) && ahead.peek2(Token![trait]) - || ahead.peek(Token![trait]) - || ahead.peek(Token![default]) - && (ahead.peek2(Token![unsafe]) || ahead.peek2(Token![impl])) - || ahead.peek(Token![impl]) - || ahead.peek(Token![macro]) - { - input.parse().map(Stmt::Item) - } else { - stmt_expr(input, allow_nosemi) - } - } - - #[cfg(feature = "full")] - fn stmt_mac(input: ParseStream) -> Result<Stmt> { - let attrs = input.call(Attribute::parse_outer)?; - let path = input.call(Path::parse_mod_style)?; - let bang_token: Token![!] = input.parse()?; - let ident: Option<Ident> = input.parse()?; - let (delimiter, tts) = mac::parse_delimiter(input)?; - let semi_token: Option<Token![;]> = input.parse()?; - - Ok(Stmt::Item(Item::Macro(ItemMacro { - attrs: attrs, - ident: ident, - mac: Macro { - path: path, - bang_token: bang_token, - delimiter: delimiter, - tts: tts, - }, - semi_token: semi_token, - }))) - } - - #[cfg(feature = "full")] - fn stmt_local(input: ParseStream) -> Result<Local> { - Ok(Local { - attrs: input.call(Attribute::parse_outer)?, - let_token: input.parse()?, - pats: { - let mut pats = Punctuated::new(); - let value: Pat = input.parse()?; - pats.push_value(value); - while input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=]) { - let punct = input.parse()?; - pats.push_punct(punct); - let value: Pat = input.parse()?; - pats.push_value(value); - } - pats - }, - ty: { - if input.peek(Token![:]) { - let colon_token: Token![:] = input.parse()?; - let ty: Type = input.parse()?; - Some((colon_token, Box::new(ty))) - } else { - None - } - }, - init: { - if input.peek(Token![=]) { - let eq_token: Token![=] = input.parse()?; - let init: Expr = input.parse()?; - Some((eq_token, Box::new(init))) - } else { - None - } - }, - semi_token: input.parse()?, - }) - } - - #[cfg(feature = "full")] - fn stmt_expr(input: ParseStream, allow_nosemi: bool) -> Result<Stmt> { - let mut attrs = input.call(Attribute::parse_outer)?; - let mut e = expr_early(input)?; - - attrs.extend(e.replace_attrs(Vec::new())); - e.replace_attrs(attrs); - - if input.peek(Token![;]) { - return Ok(Stmt::Semi(e, input.parse()?)); - } - - if allow_nosemi || !requires_terminator(&e) { - Ok(Stmt::Expr(e)) - } else { - Err(input.error("expected semicolon")) - } - } - - #[cfg(feature = "full")] - impl Parse for Pat { - fn parse(input: ParseStream) -> Result<Self> { - let lookahead = input.lookahead1(); - if lookahead.peek(Token![_]) { - input.call(pat_wild).map(Pat::Wild) - } else if lookahead.peek(Token![box]) { - input.call(pat_box).map(Pat::Box) - } else if lookahead.peek(Token![-]) || lookahead.peek(Lit) { - pat_lit_or_range(input) - } else if input.peek(Ident) - && ({ - input.peek2(Token![::]) - || input.peek2(Token![!]) - || input.peek2(token::Brace) - || input.peek2(token::Paren) - || input.peek2(Token![..]) - && !{ - let ahead = input.fork(); - ahead.parse::<Ident>()?; - ahead.parse::<RangeLimits>()?; - ahead.is_empty() || ahead.peek(Token![,]) - } - }) - || input.peek(Token![self]) && input.peek2(Token![::]) - || input.peek(Token![::]) - || input.peek(Token![<]) - || input.peek(Token![Self]) - || input.peek(Token![super]) - || input.peek(Token![extern]) - || input.peek(Token![crate]) - { - pat_path_or_macro_or_struct_or_range(input) - } else if input.peek(Token![ref]) - || input.peek(Token![mut]) - || input.peek(Token![self]) - || input.peek(Ident) - { - input.call(pat_ident).map(Pat::Ident) - } else if lookahead.peek(token::Paren) { - input.call(pat_tuple).map(Pat::Tuple) - } else if lookahead.peek(Token![&]) { - input.call(pat_ref).map(Pat::Ref) - } else if lookahead.peek(token::Bracket) { - input.call(pat_slice).map(Pat::Slice) - } else { - Err(lookahead.error()) - } - } - } - - #[cfg(feature = "full")] - fn pat_path_or_macro_or_struct_or_range(input: ParseStream) -> Result<Pat> { - let (qself, path) = path::parsing::qpath(input, true)?; - - if input.peek(Token![..]) { - return pat_range(input, qself, path).map(Pat::Range); - } - - if qself.is_some() { - return Ok(Pat::Path(PatPath { - qself: qself, - path: path, - })); - } - - if input.peek(Token![!]) && !input.peek(Token![!=]) { - let mut contains_arguments = false; - for segment in &path.segments { - match segment.arguments { - PathArguments::None => {} - PathArguments::AngleBracketed(_) | PathArguments::Parenthesized(_) => { - contains_arguments = true; - } - } - } - - if !contains_arguments { - let bang_token: Token![!] = input.parse()?; - let (delimiter, tts) = mac::parse_delimiter(input)?; - return Ok(Pat::Macro(PatMacro { - mac: Macro { - path: path, - bang_token: bang_token, - delimiter: delimiter, - tts: tts, - }, - })); - } - } - - if input.peek(token::Brace) { - pat_struct(input, path).map(Pat::Struct) - } else if input.peek(token::Paren) { - pat_tuple_struct(input, path).map(Pat::TupleStruct) - } else if input.peek(Token![..]) { - pat_range(input, qself, path).map(Pat::Range) - } else { - Ok(Pat::Path(PatPath { - qself: qself, - path: path, - })) - } - } - - #[cfg(feature = "full")] - fn pat_wild(input: ParseStream) -> Result<PatWild> { - Ok(PatWild { - underscore_token: input.parse()?, - }) - } - - #[cfg(feature = "full")] - fn pat_box(input: ParseStream) -> Result<PatBox> { - Ok(PatBox { - box_token: input.parse()?, - pat: input.parse()?, - }) - } - - #[cfg(feature = "full")] - fn pat_ident(input: ParseStream) -> Result<PatIdent> { - Ok(PatIdent { - by_ref: input.parse()?, - mutability: input.parse()?, - ident: input.call(Ident::parse_any)?, - subpat: { - if input.peek(Token![@]) { - let at_token: Token![@] = input.parse()?; - let subpat: Pat = input.parse()?; - Some((at_token, Box::new(subpat))) - } else { - None - } - }, - }) - } - - #[cfg(feature = "full")] - fn pat_tuple_struct(input: ParseStream, path: Path) -> Result<PatTupleStruct> { - Ok(PatTupleStruct { - path: path, - pat: input.call(pat_tuple)?, - }) - } - - #[cfg(feature = "full")] - fn pat_struct(input: ParseStream, path: Path) -> Result<PatStruct> { - let content; - let brace_token = braced!(content in input); - - let mut fields = Punctuated::new(); - while !content.is_empty() && !content.peek(Token![..]) { - let value = content.call(field_pat)?; - fields.push_value(value); - if !content.peek(Token![,]) { - break; - } - let punct: Token![,] = content.parse()?; - fields.push_punct(punct); - } - - let dot2_token = if fields.empty_or_trailing() && content.peek(Token![..]) { - Some(content.parse()?) - } else { - None - }; - - Ok(PatStruct { - path: path, - brace_token: brace_token, - fields: fields, - dot2_token: dot2_token, - }) - } - - #[cfg(feature = "full")] - fn field_pat(input: ParseStream) -> Result<FieldPat> { - let boxed: Option<Token![box]> = input.parse()?; - let by_ref: Option<Token![ref]> = input.parse()?; - let mutability: Option<Token![mut]> = input.parse()?; - let member: Member = input.parse()?; - - if boxed.is_none() && by_ref.is_none() && mutability.is_none() && input.peek(Token![:]) - || member.is_unnamed() - { - return Ok(FieldPat { - attrs: Vec::new(), - member: member, - colon_token: input.parse()?, - pat: input.parse()?, - }); - } - - let ident = match member { - Member::Named(ident) => ident, - Member::Unnamed(_) => unreachable!(), - }; - - let mut pat = Pat::Ident(PatIdent { - by_ref: by_ref, - mutability: mutability, - ident: ident.clone(), - subpat: None, - }); - - if let Some(boxed) = boxed { - pat = Pat::Box(PatBox { - pat: Box::new(pat), - box_token: boxed, - }); - } - - Ok(FieldPat { - member: Member::Named(ident), - pat: Box::new(pat), - attrs: Vec::new(), - colon_token: None, - }) - } - - impl Parse for Member { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Ident) { - input.parse().map(Member::Named) - } else if input.peek(LitInt) { - input.parse().map(Member::Unnamed) - } else { - Err(input.error("expected identifier or integer")) - } - } - } - - #[cfg(feature = "full")] - impl Parse for Arm { - fn parse(input: ParseStream) -> Result<Arm> { - let requires_comma; - Ok(Arm { - attrs: input.call(Attribute::parse_outer)?, - leading_vert: input.parse()?, - pats: { - let mut pats = Punctuated::new(); - let value: Pat = input.parse()?; - pats.push_value(value); - loop { - if !input.peek(Token![|]) { - break; - } - let punct = input.parse()?; - pats.push_punct(punct); - let value: Pat = input.parse()?; - pats.push_value(value); - } - pats - }, - guard: { - if input.peek(Token![if]) { - let if_token: Token![if] = input.parse()?; - let guard: Expr = input.parse()?; - Some((if_token, Box::new(guard))) - } else { - None - } - }, - fat_arrow_token: input.parse()?, - body: { - let body = input.call(expr_early)?; - requires_comma = requires_terminator(&body); - Box::new(body) - }, - comma: { - if requires_comma && !input.is_empty() { - Some(input.parse()?) - } else { - input.parse()? - } - }, - }) - } - } - - impl Parse for Index { - fn parse(input: ParseStream) -> Result<Self> { - let lit: LitInt = input.parse()?; - if let IntSuffix::None = lit.suffix() { - Ok(Index { - index: lit.value() as u32, - span: lit.span(), - }) - } else { - Err(Error::new(lit.span(), "expected unsuffixed integer")) - } - } - } - - #[cfg(feature = "full")] - fn pat_range(input: ParseStream, qself: Option<QSelf>, path: Path) -> Result<PatRange> { - Ok(PatRange { - lo: Box::new(Expr::Path(ExprPath { - attrs: Vec::new(), - qself: qself, - path: path, - })), - limits: input.parse()?, - hi: input.call(pat_lit_expr)?, - }) - } - - #[cfg(feature = "full")] - fn pat_tuple(input: ParseStream) -> Result<PatTuple> { - let content; - let paren_token = parenthesized!(content in input); - - let mut front = Punctuated::new(); - let mut dot2_token = None::<Token![..]>; - let mut comma_token = None::<Token![,]>; - loop { - if content.is_empty() { - break; - } - if content.peek(Token![..]) { - dot2_token = Some(content.parse()?); - comma_token = content.parse()?; - break; - } - let value: Pat = content.parse()?; - front.push_value(value); - if content.is_empty() { - break; - } - let punct = content.parse()?; - front.push_punct(punct); - } - - let mut back = Punctuated::new(); - while !content.is_empty() { - let value: Pat = content.parse()?; - back.push_value(value); - if content.is_empty() { - break; - } - let punct = content.parse()?; - back.push_punct(punct); - } - - Ok(PatTuple { - paren_token: paren_token, - front: front, - dot2_token: dot2_token, - comma_token: comma_token, - back: back, - }) - } - - #[cfg(feature = "full")] - fn pat_ref(input: ParseStream) -> Result<PatRef> { - Ok(PatRef { - and_token: input.parse()?, - mutability: input.parse()?, - pat: input.parse()?, - }) - } - - #[cfg(feature = "full")] - fn pat_lit_or_range(input: ParseStream) -> Result<Pat> { - let lo = input.call(pat_lit_expr)?; - if input.peek(Token![..]) { - Ok(Pat::Range(PatRange { - lo: lo, - limits: input.parse()?, - hi: input.call(pat_lit_expr)?, - })) - } else { - Ok(Pat::Lit(PatLit { expr: lo })) - } - } - - #[cfg(feature = "full")] - fn pat_lit_expr(input: ParseStream) -> Result<Box<Expr>> { - let neg: Option<Token![-]> = input.parse()?; - - let lookahead = input.lookahead1(); - let expr = if lookahead.peek(Lit) { - Expr::Lit(input.parse()?) - } else if lookahead.peek(Ident) - || lookahead.peek(Token![::]) - || lookahead.peek(Token![<]) - || lookahead.peek(Token![self]) - || lookahead.peek(Token![Self]) - || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![crate]) - { - Expr::Path(input.parse()?) - } else { - return Err(lookahead.error()); - }; - - Ok(Box::new(if let Some(neg) = neg { - Expr::Unary(ExprUnary { - attrs: Vec::new(), - op: UnOp::Neg(neg), - expr: Box::new(expr), - }) - } else { - expr - })) - } - - #[cfg(feature = "full")] - fn pat_slice(input: ParseStream) -> Result<PatSlice> { - let content; - let bracket_token = bracketed!(content in input); - - let mut front = Punctuated::new(); - let mut middle = None; - loop { - if content.is_empty() || content.peek(Token![..]) { - break; - } - let value: Pat = content.parse()?; - if content.peek(Token![..]) { - middle = Some(Box::new(value)); - break; - } - front.push_value(value); - if content.is_empty() { - break; - } - let punct = content.parse()?; - front.push_punct(punct); - } - - let dot2_token: Option<Token![..]> = content.parse()?; - let mut comma_token = None::<Token![,]>; - let mut back = Punctuated::new(); - if dot2_token.is_some() { - comma_token = content.parse()?; - if comma_token.is_some() { - loop { - if content.is_empty() { - break; - } - let value: Pat = content.parse()?; - back.push_value(value); - if content.is_empty() { - break; - } - let punct = content.parse()?; - back.push_punct(punct); - } - } - } - - Ok(PatSlice { - bracket_token: bracket_token, - front: front, - middle: middle, - dot2_token: dot2_token, - comma_token: comma_token, - back: back, - }) - } - - #[cfg(feature = "full")] - impl Member { - fn is_named(&self) -> bool { - match *self { - Member::Named(_) => true, - Member::Unnamed(_) => false, - } - } - - fn is_unnamed(&self) -> bool { - match *self { - Member::Named(_) => false, - Member::Unnamed(_) => true, - } - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - - use proc_macro2::{Literal, TokenStream}; - use quote::{ToTokens, TokenStreamExt}; - - #[cfg(feature = "full")] - use attr::FilterAttrs; - #[cfg(feature = "full")] - use print::TokensOrDefault; - - // If the given expression is a bare `ExprStruct`, wraps it in parenthesis - // before appending it to `TokenStream`. - #[cfg(feature = "full")] - fn wrap_bare_struct(tokens: &mut TokenStream, e: &Expr) { - if let Expr::Struct(_) = *e { - token::Paren::default().surround(tokens, |tokens| { - e.to_tokens(tokens); - }); - } else { - e.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - fn outer_attrs_to_tokens(attrs: &[Attribute], tokens: &mut TokenStream) { - tokens.append_all(attrs.outer()); - } - - #[cfg(feature = "full")] - fn inner_attrs_to_tokens(attrs: &[Attribute], tokens: &mut TokenStream) { - tokens.append_all(attrs.inner()); - } - - #[cfg(not(feature = "full"))] - fn outer_attrs_to_tokens(_attrs: &[Attribute], _tokens: &mut TokenStream) {} - - #[cfg(not(feature = "full"))] - fn inner_attrs_to_tokens(_attrs: &[Attribute], _tokens: &mut TokenStream) {} - - #[cfg(feature = "full")] - impl ToTokens for ExprBox { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.box_token.to_tokens(tokens); - self.expr.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprInPlace { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.place.to_tokens(tokens); - self.arrow_token.to_tokens(tokens); - self.value.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprArray { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.bracket_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - self.elems.to_tokens(tokens); - }) - } - } - - impl ToTokens for ExprCall { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.func.to_tokens(tokens); - self.paren_token.surround(tokens, |tokens| { - self.args.to_tokens(tokens); - }) - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprMethodCall { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.receiver.to_tokens(tokens); - self.dot_token.to_tokens(tokens); - self.method.to_tokens(tokens); - self.turbofish.to_tokens(tokens); - self.paren_token.surround(tokens, |tokens| { - self.args.to_tokens(tokens); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for MethodTurbofish { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.colon2_token.to_tokens(tokens); - self.lt_token.to_tokens(tokens); - self.args.to_tokens(tokens); - self.gt_token.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for GenericMethodArgument { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - GenericMethodArgument::Type(ref t) => t.to_tokens(tokens), - GenericMethodArgument::Const(ref c) => c.to_tokens(tokens), - } - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprTuple { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.paren_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - self.elems.to_tokens(tokens); - // If we only have one argument, we need a trailing comma to - // distinguish ExprTuple from ExprParen. - if self.elems.len() == 1 && !self.elems.trailing_punct() { - <Token![,]>::default().to_tokens(tokens); - } - }) - } - } - - impl ToTokens for ExprBinary { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.left.to_tokens(tokens); - self.op.to_tokens(tokens); - self.right.to_tokens(tokens); - } - } - - impl ToTokens for ExprUnary { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.op.to_tokens(tokens); - self.expr.to_tokens(tokens); - } - } - - impl ToTokens for ExprLit { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.lit.to_tokens(tokens); - } - } - - impl ToTokens for ExprCast { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.expr.to_tokens(tokens); - self.as_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprType { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.expr.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - fn maybe_wrap_else(tokens: &mut TokenStream, else_: &Option<(Token![else], Box<Expr>)>) { - if let Some((ref else_token, ref else_)) = *else_ { - else_token.to_tokens(tokens); - - // If we are not one of the valid expressions to exist in an else - // clause, wrap ourselves in a block. - match **else_ { - Expr::If(_) | Expr::Block(_) => { - else_.to_tokens(tokens); - } - _ => { - token::Brace::default().surround(tokens, |tokens| { - else_.to_tokens(tokens); - }); - } - } - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprLet { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.let_token.to_tokens(tokens); - self.pats.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - wrap_bare_struct(tokens, &self.expr); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprIf { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.if_token.to_tokens(tokens); - wrap_bare_struct(tokens, &self.cond); - self.then_branch.to_tokens(tokens); - maybe_wrap_else(tokens, &self.else_branch); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprWhile { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.label.to_tokens(tokens); - self.while_token.to_tokens(tokens); - wrap_bare_struct(tokens, &self.cond); - self.body.brace_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - tokens.append_all(&self.body.stmts); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprForLoop { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.label.to_tokens(tokens); - self.for_token.to_tokens(tokens); - self.pat.to_tokens(tokens); - self.in_token.to_tokens(tokens); - wrap_bare_struct(tokens, &self.expr); - self.body.brace_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - tokens.append_all(&self.body.stmts); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprLoop { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.label.to_tokens(tokens); - self.loop_token.to_tokens(tokens); - self.body.brace_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - tokens.append_all(&self.body.stmts); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprMatch { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.match_token.to_tokens(tokens); - wrap_bare_struct(tokens, &self.expr); - self.brace_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - for (i, arm) in self.arms.iter().enumerate() { - arm.to_tokens(tokens); - // Ensure that we have a comma after a non-block arm, except - // for the last one. - let is_last = i == self.arms.len() - 1; - if !is_last && requires_terminator(&arm.body) && arm.comma.is_none() { - <Token![,]>::default().to_tokens(tokens); - } - } - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprAsync { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.async_token.to_tokens(tokens); - self.capture.to_tokens(tokens); - self.block.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprTryBlock { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.try_token.to_tokens(tokens); - self.block.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprYield { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.yield_token.to_tokens(tokens); - self.expr.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprClosure { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.asyncness.to_tokens(tokens); - self.movability.to_tokens(tokens); - self.capture.to_tokens(tokens); - self.or1_token.to_tokens(tokens); - for input in self.inputs.pairs() { - match **input.value() { - FnArg::Captured(ArgCaptured { - ref pat, - ty: Type::Infer(_), - .. - }) => { - pat.to_tokens(tokens); - } - _ => input.value().to_tokens(tokens), - } - input.punct().to_tokens(tokens); - } - self.or2_token.to_tokens(tokens); - self.output.to_tokens(tokens); - self.body.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprUnsafe { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.unsafe_token.to_tokens(tokens); - self.block.brace_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - tokens.append_all(&self.block.stmts); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprBlock { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.label.to_tokens(tokens); - self.block.brace_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - tokens.append_all(&self.block.stmts); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprAssign { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.left.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.right.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprAssignOp { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.left.to_tokens(tokens); - self.op.to_tokens(tokens); - self.right.to_tokens(tokens); - } - } - - impl ToTokens for ExprField { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.base.to_tokens(tokens); - self.dot_token.to_tokens(tokens); - self.member.to_tokens(tokens); - } - } - - impl ToTokens for Member { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - Member::Named(ref ident) => ident.to_tokens(tokens), - Member::Unnamed(ref index) => index.to_tokens(tokens), - } - } - } - - impl ToTokens for Index { - fn to_tokens(&self, tokens: &mut TokenStream) { - let mut lit = Literal::i64_unsuffixed(i64::from(self.index)); - lit.set_span(self.span); - tokens.append(lit); - } - } - - impl ToTokens for ExprIndex { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.expr.to_tokens(tokens); - self.bracket_token.surround(tokens, |tokens| { - self.index.to_tokens(tokens); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprRange { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.from.to_tokens(tokens); - match self.limits { - RangeLimits::HalfOpen(ref t) => t.to_tokens(tokens), - RangeLimits::Closed(ref t) => t.to_tokens(tokens), - } - self.to.to_tokens(tokens); - } - } - - impl ToTokens for ExprPath { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - private::print_path(tokens, &self.qself, &self.path); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprReference { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.and_token.to_tokens(tokens); - self.mutability.to_tokens(tokens); - self.expr.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprBreak { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.break_token.to_tokens(tokens); - self.label.to_tokens(tokens); - self.expr.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprContinue { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.continue_token.to_tokens(tokens); - self.label.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprReturn { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.return_token.to_tokens(tokens); - self.expr.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprMacro { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.mac.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprStruct { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.path.to_tokens(tokens); - self.brace_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - self.fields.to_tokens(tokens); - if self.rest.is_some() { - TokensOrDefault(&self.dot2_token).to_tokens(tokens); - self.rest.to_tokens(tokens); - } - }) - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprRepeat { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.bracket_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - self.expr.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - self.len.to_tokens(tokens); - }) - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprGroup { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.group_token.surround(tokens, |tokens| { - self.expr.to_tokens(tokens); - }); - } - } - - impl ToTokens for ExprParen { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.paren_token.surround(tokens, |tokens| { - inner_attrs_to_tokens(&self.attrs, tokens); - self.expr.to_tokens(tokens); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for ExprTry { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.expr.to_tokens(tokens); - self.question_token.to_tokens(tokens); - } - } - - impl ToTokens for ExprVerbatim { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.tts.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for Label { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.name.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for FieldValue { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.member.to_tokens(tokens); - if let Some(ref colon_token) = self.colon_token { - colon_token.to_tokens(tokens); - self.expr.to_tokens(tokens); - } - } - } - - #[cfg(feature = "full")] - impl ToTokens for Arm { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(&self.attrs); - self.leading_vert.to_tokens(tokens); - self.pats.to_tokens(tokens); - if let Some((ref if_token, ref guard)) = self.guard { - if_token.to_tokens(tokens); - guard.to_tokens(tokens); - } - self.fat_arrow_token.to_tokens(tokens); - self.body.to_tokens(tokens); - self.comma.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatWild { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.underscore_token.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatIdent { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.by_ref.to_tokens(tokens); - self.mutability.to_tokens(tokens); - self.ident.to_tokens(tokens); - if let Some((ref at_token, ref subpat)) = self.subpat { - at_token.to_tokens(tokens); - subpat.to_tokens(tokens); - } - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatStruct { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.path.to_tokens(tokens); - self.brace_token.surround(tokens, |tokens| { - self.fields.to_tokens(tokens); - // NOTE: We need a comma before the dot2 token if it is present. - if !self.fields.empty_or_trailing() && self.dot2_token.is_some() { - <Token![,]>::default().to_tokens(tokens); - } - self.dot2_token.to_tokens(tokens); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatTupleStruct { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.path.to_tokens(tokens); - self.pat.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatPath { - fn to_tokens(&self, tokens: &mut TokenStream) { - private::print_path(tokens, &self.qself, &self.path); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatTuple { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.paren_token.surround(tokens, |tokens| { - self.front.to_tokens(tokens); - if let Some(ref dot2_token) = self.dot2_token { - if !self.front.empty_or_trailing() { - // Ensure there is a comma before the .. token. - <Token![,]>::default().to_tokens(tokens); - } - dot2_token.to_tokens(tokens); - self.comma_token.to_tokens(tokens); - if self.comma_token.is_none() && !self.back.is_empty() { - // Ensure there is a comma after the .. token. - <Token![,]>::default().to_tokens(tokens); - } - } - self.back.to_tokens(tokens); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatBox { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.box_token.to_tokens(tokens); - self.pat.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatRef { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.and_token.to_tokens(tokens); - self.mutability.to_tokens(tokens); - self.pat.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatLit { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.expr.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatRange { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.lo.to_tokens(tokens); - match self.limits { - RangeLimits::HalfOpen(ref t) => t.to_tokens(tokens), - RangeLimits::Closed(ref t) => t.to_tokens(tokens), - } - self.hi.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatSlice { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.bracket_token.surround(tokens, |tokens| { - self.front.to_tokens(tokens); - - // If we need a comma before the middle or standalone .. token, - // then make sure it's present. - if !self.front.empty_or_trailing() - && (self.middle.is_some() || self.dot2_token.is_some()) - { - <Token![,]>::default().to_tokens(tokens); - } - - // If we have an identifier, we always need a .. token. - if self.middle.is_some() { - self.middle.to_tokens(tokens); - TokensOrDefault(&self.dot2_token).to_tokens(tokens); - } else if self.dot2_token.is_some() { - self.dot2_token.to_tokens(tokens); - } - - // Make sure we have a comma before the back half. - if !self.back.is_empty() { - TokensOrDefault(&self.comma_token).to_tokens(tokens); - self.back.to_tokens(tokens); - } else { - self.comma_token.to_tokens(tokens); - } - }) - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatMacro { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.mac.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for PatVerbatim { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.tts.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for FieldPat { - fn to_tokens(&self, tokens: &mut TokenStream) { - if let Some(ref colon_token) = self.colon_token { - self.member.to_tokens(tokens); - colon_token.to_tokens(tokens); - } - self.pat.to_tokens(tokens); - } - } - - #[cfg(feature = "full")] - impl ToTokens for Block { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.brace_token.surround(tokens, |tokens| { - tokens.append_all(&self.stmts); - }); - } - } - - #[cfg(feature = "full")] - impl ToTokens for Stmt { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - Stmt::Local(ref local) => local.to_tokens(tokens), - Stmt::Item(ref item) => item.to_tokens(tokens), - Stmt::Expr(ref expr) => expr.to_tokens(tokens), - Stmt::Semi(ref expr, ref semi) => { - expr.to_tokens(tokens); - semi.to_tokens(tokens); - } - } - } - } - - #[cfg(feature = "full")] - impl ToTokens for Local { - fn to_tokens(&self, tokens: &mut TokenStream) { - outer_attrs_to_tokens(&self.attrs, tokens); - self.let_token.to_tokens(tokens); - self.pats.to_tokens(tokens); - if let Some((ref colon_token, ref ty)) = self.ty { - colon_token.to_tokens(tokens); - ty.to_tokens(tokens); - } - if let Some((ref eq_token, ref init)) = self.init { - eq_token.to_tokens(tokens); - init.to_tokens(tokens); - } - self.semi_token.to_tokens(tokens); - } - } -} diff --git a/0.15.42/src/ext.rs b/0.15.42/src/ext.rs deleted file mode 100644 index 17721d56..00000000 --- a/0.15.42/src/ext.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Extension traits to provide parsing methods on foreign types. -//! -//! *This module is available if Syn is built with the `"parsing"` feature.* - -use proc_macro2::Ident; - -use parse::{ParseStream, Result}; - -#[cfg(syn_can_use_associated_constants)] -use buffer::Cursor; -#[cfg(syn_can_use_associated_constants)] -use parse::Peek; -#[cfg(syn_can_use_associated_constants)] -use sealed::lookahead; -#[cfg(syn_can_use_associated_constants)] -use token::CustomToken; - -/// Additional methods for `Ident` not provided by proc-macro2 or libproc_macro. -/// -/// This trait is sealed and cannot be implemented for types outside of Syn. It -/// is implemented only for `proc_macro2::Ident`. -/// -/// *This trait is available if Syn is built with the `"parsing"` feature.* -pub trait IdentExt: Sized + private::Sealed { - /// Parses any identifier including keywords. - /// - /// This is useful when parsing macro input which allows Rust keywords as - /// identifiers. - /// - /// # Example - /// - /// ```edition2018 - /// use syn::{Error, Ident, Result, Token}; - /// use syn::ext::IdentExt; - /// use syn::parse::ParseStream; - /// - /// mod kw { - /// syn::custom_keyword!(name); - /// } - /// - /// // Parses input that looks like `name = NAME` where `NAME` can be - /// // any identifier. - /// // - /// // Examples: - /// // - /// // name = anything - /// // name = impl - /// fn parse_dsl(input: ParseStream) -> Result<Ident> { - /// input.parse::<kw::name>()?; - /// input.parse::<Token![=]>()?; - /// let name = input.call(Ident::parse_any)?; - /// Ok(name) - /// } - /// ``` - fn parse_any(input: ParseStream) -> Result<Self>; - - /// Peeks any identifier including keywords. Usage: - /// `input.peek(Ident::peek_any)` - /// - /// This is different from `input.peek(Ident)` which only returns true in - /// the case of an ident which is not a Rust keyword. - #[cfg(syn_can_use_associated_constants)] - #[allow(non_upper_case_globals)] - const peek_any: private::PeekFn = private::PeekFn; - - /// Strips the raw marker `r#`, if any, from the beginning of an ident. - /// - /// - unraw(`x`) = `x` - /// - unraw(`move`) = `move` - /// - unraw(`r#move`) = `move` - /// - /// # Example - /// - /// In the case of interop with other languages like Python that have a - /// different set of keywords than Rust, we might come across macro input - /// that involves raw identifiers to refer to ordinary variables in the - /// other language with a name that happens to be a Rust keyword. - /// - /// The function below appends an identifier from the caller's input onto a - /// fixed prefix. Without using `unraw()`, this would tend to produce - /// invalid identifiers like `__pyo3_get_r#move`. - /// - /// ```edition2018 - /// use proc_macro2::Span; - /// use syn::Ident; - /// use syn::ext::IdentExt; - /// - /// fn ident_for_getter(variable: &Ident) -> Ident { - /// let getter = format!("__pyo3_get_{}", variable.unraw()); - /// Ident::new(&getter, Span::call_site()) - /// } - /// ``` - fn unraw(&self) -> Ident; -} - -impl IdentExt for Ident { - fn parse_any(input: ParseStream) -> Result<Self> { - input.step(|cursor| match cursor.ident() { - Some((ident, rest)) => Ok((ident, rest)), - None => Err(cursor.error("expected ident")), - }) - } - - fn unraw(&self) -> Ident { - let string = self.to_string(); - if string.starts_with("r#") { - Ident::new(&string[2..], self.span()) - } else { - self.clone() - } - } -} - -#[cfg(syn_can_use_associated_constants)] -impl Peek for private::PeekFn { - type Token = private::IdentAny; -} - -#[cfg(syn_can_use_associated_constants)] -impl CustomToken for private::IdentAny { - fn peek(cursor: Cursor) -> bool { - cursor.ident().is_some() - } - - fn display() -> &'static str { - "identifier" - } -} - -#[cfg(syn_can_use_associated_constants)] -impl lookahead::Sealed for private::PeekFn {} - -mod private { - use proc_macro2::Ident; - - pub trait Sealed {} - - impl Sealed for Ident {} - - #[cfg(syn_can_use_associated_constants)] - #[derive(Copy, Clone)] - pub struct PeekFn; - #[cfg(syn_can_use_associated_constants)] - pub struct IdentAny; -} diff --git a/0.15.42/src/file.rs b/0.15.42/src/file.rs deleted file mode 100644 index 30defe7d..00000000 --- a/0.15.42/src/file.rs +++ /dev/null @@ -1,113 +0,0 @@ -use super::*; - -ast_struct! { - /// A complete file of Rust source code. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - /// - /// # Example - /// - /// Parse a Rust source file into a `syn::File` and print out a debug - /// representation of the syntax tree. - /// - /// ```edition2018 - /// use std::env; - /// use std::fs::File; - /// use std::io::Read; - /// use std::process; - /// - /// fn main() { - /// # } - /// # - /// # fn fake_main() { - /// let mut args = env::args(); - /// let _ = args.next(); // executable name - /// - /// let filename = match (args.next(), args.next()) { - /// (Some(filename), None) => filename, - /// _ => { - /// eprintln!("Usage: dump-syntax path/to/filename.rs"); - /// process::exit(1); - /// } - /// }; - /// - /// 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 syntax = syn::parse_file(&src).expect("Unable to parse file"); - /// println!("{:#?}", syntax); - /// } - /// ``` - /// - /// Running with its own source code as input, this program prints output - /// that begins with: - /// - /// ```text - /// File { - /// shebang: None, - /// attrs: [], - /// items: [ - /// ExternCrate( - /// ItemExternCrate { - /// attrs: [], - /// vis: Inherited, - /// extern_token: Extern, - /// crate_token: Crate, - /// ident: Ident { - /// term: Term( - /// "syn" - /// ), - /// span: Span - /// }, - /// rename: None, - /// semi_token: Semi - /// } - /// ), - /// ... - /// ``` - pub struct File { - pub shebang: Option<String>, - pub attrs: Vec<Attribute>, - pub items: Vec<Item>, - } -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use parse::{Parse, ParseStream, Result}; - - impl Parse for File { - fn parse(input: ParseStream) -> Result<Self> { - Ok(File { - shebang: None, - attrs: input.call(Attribute::parse_inner)?, - items: { - let mut items = Vec::new(); - while !input.is_empty() { - items.push(input.parse()?); - } - items - }, - }) - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - use attr::FilterAttrs; - use proc_macro2::TokenStream; - use quote::{ToTokens, TokenStreamExt}; - - impl ToTokens for File { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.inner()); - tokens.append_all(&self.items); - } - } -} diff --git a/0.15.42/src/gen/fold.rs b/0.15.42/src/gen/fold.rs deleted file mode 100644 index 9d9fc252..00000000 --- a/0.15.42/src/gen/fold.rs +++ /dev/null @@ -1,2958 +0,0 @@ -// This file is @generated by syn-internal-codegen. -// It is not intended for manual editing. - -#![allow(unreachable_code)] -#[cfg(any(feature = "full", feature = "derive"))] -use gen::helper::fold::*; -use proc_macro2::Span; -#[cfg(any(feature = "full", feature = "derive"))] -use token::{Brace, Bracket, Group, Paren}; -use *; -#[cfg(feature = "full")] -macro_rules! full { - ($e:expr) => { - $e - }; -} -#[cfg(all(feature = "derive", not(feature = "full")))] -macro_rules! full { - ($e:expr) => { - unreachable!() - }; -} -/// Syntax tree traversal to transform the nodes of an owned syntax tree. -/// -/// See the [module documentation] for details. -/// -/// [module documentation]: self -/// -/// *This trait is available if Syn is built with the `"fold"` feature.* -pub trait Fold { - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_abi(&mut self, i: Abi) -> Abi { - fold_abi(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_angle_bracketed_generic_arguments( - &mut self, - i: AngleBracketedGenericArguments, - ) -> AngleBracketedGenericArguments { - fold_angle_bracketed_generic_arguments(self, i) - } - #[cfg(feature = "full")] - fn fold_arg_captured(&mut self, i: ArgCaptured) -> ArgCaptured { - fold_arg_captured(self, i) - } - #[cfg(feature = "full")] - fn fold_arg_self(&mut self, i: ArgSelf) -> ArgSelf { - fold_arg_self(self, i) - } - #[cfg(feature = "full")] - fn fold_arg_self_ref(&mut self, i: ArgSelfRef) -> ArgSelfRef { - fold_arg_self_ref(self, i) - } - #[cfg(feature = "full")] - fn fold_arm(&mut self, i: Arm) -> Arm { - fold_arm(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_attr_style(&mut self, i: AttrStyle) -> AttrStyle { - fold_attr_style(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_attribute(&mut self, i: Attribute) -> Attribute { - fold_attribute(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_bare_fn_arg(&mut self, i: BareFnArg) -> BareFnArg { - fold_bare_fn_arg(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_bare_fn_arg_name(&mut self, i: BareFnArgName) -> BareFnArgName { - fold_bare_fn_arg_name(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_bin_op(&mut self, i: BinOp) -> BinOp { - fold_bin_op(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_binding(&mut self, i: Binding) -> Binding { - fold_binding(self, i) - } - #[cfg(feature = "full")] - fn fold_block(&mut self, i: Block) -> Block { - fold_block(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_bound_lifetimes(&mut self, i: BoundLifetimes) -> BoundLifetimes { - fold_bound_lifetimes(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_const_param(&mut self, i: ConstParam) -> ConstParam { - fold_const_param(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_constraint(&mut self, i: Constraint) -> Constraint { - fold_constraint(self, i) - } - #[cfg(feature = "derive")] - fn fold_data(&mut self, i: Data) -> Data { - fold_data(self, i) - } - #[cfg(feature = "derive")] - fn fold_data_enum(&mut self, i: DataEnum) -> DataEnum { - fold_data_enum(self, i) - } - #[cfg(feature = "derive")] - fn fold_data_struct(&mut self, i: DataStruct) -> DataStruct { - fold_data_struct(self, i) - } - #[cfg(feature = "derive")] - fn fold_data_union(&mut self, i: DataUnion) -> DataUnion { - fold_data_union(self, i) - } - #[cfg(feature = "derive")] - fn fold_derive_input(&mut self, i: DeriveInput) -> DeriveInput { - fold_derive_input(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr(&mut self, i: Expr) -> Expr { - fold_expr(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_array(&mut self, i: ExprArray) -> ExprArray { - fold_expr_array(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_assign(&mut self, i: ExprAssign) -> ExprAssign { - fold_expr_assign(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_assign_op(&mut self, i: ExprAssignOp) -> ExprAssignOp { - fold_expr_assign_op(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_async(&mut self, i: ExprAsync) -> ExprAsync { - fold_expr_async(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_binary(&mut self, i: ExprBinary) -> ExprBinary { - fold_expr_binary(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_block(&mut self, i: ExprBlock) -> ExprBlock { - fold_expr_block(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_box(&mut self, i: ExprBox) -> ExprBox { - fold_expr_box(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_break(&mut self, i: ExprBreak) -> ExprBreak { - fold_expr_break(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_call(&mut self, i: ExprCall) -> ExprCall { - fold_expr_call(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_cast(&mut self, i: ExprCast) -> ExprCast { - fold_expr_cast(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_closure(&mut self, i: ExprClosure) -> ExprClosure { - fold_expr_closure(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_continue(&mut self, i: ExprContinue) -> ExprContinue { - fold_expr_continue(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_field(&mut self, i: ExprField) -> ExprField { - fold_expr_field(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_for_loop(&mut self, i: ExprForLoop) -> ExprForLoop { - fold_expr_for_loop(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_group(&mut self, i: ExprGroup) -> ExprGroup { - fold_expr_group(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_if(&mut self, i: ExprIf) -> ExprIf { - fold_expr_if(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_in_place(&mut self, i: ExprInPlace) -> ExprInPlace { - fold_expr_in_place(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_index(&mut self, i: ExprIndex) -> ExprIndex { - fold_expr_index(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_let(&mut self, i: ExprLet) -> ExprLet { - fold_expr_let(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_lit(&mut self, i: ExprLit) -> ExprLit { - fold_expr_lit(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_loop(&mut self, i: ExprLoop) -> ExprLoop { - fold_expr_loop(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_macro(&mut self, i: ExprMacro) -> ExprMacro { - fold_expr_macro(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_match(&mut self, i: ExprMatch) -> ExprMatch { - fold_expr_match(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_method_call(&mut self, i: ExprMethodCall) -> ExprMethodCall { - fold_expr_method_call(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_paren(&mut self, i: ExprParen) -> ExprParen { - fold_expr_paren(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_path(&mut self, i: ExprPath) -> ExprPath { - fold_expr_path(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_range(&mut self, i: ExprRange) -> ExprRange { - fold_expr_range(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_reference(&mut self, i: ExprReference) -> ExprReference { - fold_expr_reference(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_repeat(&mut self, i: ExprRepeat) -> ExprRepeat { - fold_expr_repeat(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_return(&mut self, i: ExprReturn) -> ExprReturn { - fold_expr_return(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_struct(&mut self, i: ExprStruct) -> ExprStruct { - fold_expr_struct(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_try(&mut self, i: ExprTry) -> ExprTry { - fold_expr_try(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_try_block(&mut self, i: ExprTryBlock) -> ExprTryBlock { - fold_expr_try_block(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_tuple(&mut self, i: ExprTuple) -> ExprTuple { - fold_expr_tuple(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_type(&mut self, i: ExprType) -> ExprType { - fold_expr_type(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_unary(&mut self, i: ExprUnary) -> ExprUnary { - fold_expr_unary(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_unsafe(&mut self, i: ExprUnsafe) -> ExprUnsafe { - fold_expr_unsafe(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_expr_verbatim(&mut self, i: ExprVerbatim) -> ExprVerbatim { - fold_expr_verbatim(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_while(&mut self, i: ExprWhile) -> ExprWhile { - fold_expr_while(self, i) - } - #[cfg(feature = "full")] - fn fold_expr_yield(&mut self, i: ExprYield) -> ExprYield { - fold_expr_yield(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_field(&mut self, i: Field) -> Field { - fold_field(self, i) - } - #[cfg(feature = "full")] - fn fold_field_pat(&mut self, i: FieldPat) -> FieldPat { - fold_field_pat(self, i) - } - #[cfg(feature = "full")] - fn fold_field_value(&mut self, i: FieldValue) -> FieldValue { - fold_field_value(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_fields(&mut self, i: Fields) -> Fields { - fold_fields(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_fields_named(&mut self, i: FieldsNamed) -> FieldsNamed { - fold_fields_named(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_fields_unnamed(&mut self, i: FieldsUnnamed) -> FieldsUnnamed { - fold_fields_unnamed(self, i) - } - #[cfg(feature = "full")] - fn fold_file(&mut self, i: File) -> File { - fold_file(self, i) - } - #[cfg(feature = "full")] - fn fold_fn_arg(&mut self, i: FnArg) -> FnArg { - fold_fn_arg(self, i) - } - #[cfg(feature = "full")] - fn fold_fn_decl(&mut self, i: FnDecl) -> FnDecl { - fold_fn_decl(self, i) - } - #[cfg(feature = "full")] - fn fold_foreign_item(&mut self, i: ForeignItem) -> ForeignItem { - fold_foreign_item(self, i) - } - #[cfg(feature = "full")] - fn fold_foreign_item_fn(&mut self, i: ForeignItemFn) -> ForeignItemFn { - fold_foreign_item_fn(self, i) - } - #[cfg(feature = "full")] - fn fold_foreign_item_macro(&mut self, i: ForeignItemMacro) -> ForeignItemMacro { - fold_foreign_item_macro(self, i) - } - #[cfg(feature = "full")] - fn fold_foreign_item_static(&mut self, i: ForeignItemStatic) -> ForeignItemStatic { - fold_foreign_item_static(self, i) - } - #[cfg(feature = "full")] - fn fold_foreign_item_type(&mut self, i: ForeignItemType) -> ForeignItemType { - fold_foreign_item_type(self, i) - } - #[cfg(feature = "full")] - fn fold_foreign_item_verbatim(&mut self, i: ForeignItemVerbatim) -> ForeignItemVerbatim { - fold_foreign_item_verbatim(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_generic_argument(&mut self, i: GenericArgument) -> GenericArgument { - fold_generic_argument(self, i) - } - #[cfg(feature = "full")] - fn fold_generic_method_argument(&mut self, i: GenericMethodArgument) -> GenericMethodArgument { - fold_generic_method_argument(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_generic_param(&mut self, i: GenericParam) -> GenericParam { - fold_generic_param(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_generics(&mut self, i: Generics) -> Generics { - fold_generics(self, i) - } - #[cfg(feature = "full")] - fn fold_impl_item(&mut self, i: ImplItem) -> ImplItem { - fold_impl_item(self, i) - } - #[cfg(feature = "full")] - fn fold_impl_item_const(&mut self, i: ImplItemConst) -> ImplItemConst { - fold_impl_item_const(self, i) - } - #[cfg(feature = "full")] - fn fold_impl_item_existential(&mut self, i: ImplItemExistential) -> ImplItemExistential { - fold_impl_item_existential(self, i) - } - #[cfg(feature = "full")] - fn fold_impl_item_macro(&mut self, i: ImplItemMacro) -> ImplItemMacro { - fold_impl_item_macro(self, i) - } - #[cfg(feature = "full")] - fn fold_impl_item_method(&mut self, i: ImplItemMethod) -> ImplItemMethod { - fold_impl_item_method(self, i) - } - #[cfg(feature = "full")] - fn fold_impl_item_type(&mut self, i: ImplItemType) -> ImplItemType { - fold_impl_item_type(self, i) - } - #[cfg(feature = "full")] - fn fold_impl_item_verbatim(&mut self, i: ImplItemVerbatim) -> ImplItemVerbatim { - fold_impl_item_verbatim(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_index(&mut self, i: Index) -> Index { - fold_index(self, i) - } - #[cfg(feature = "full")] - fn fold_item(&mut self, i: Item) -> Item { - fold_item(self, i) - } - #[cfg(feature = "full")] - fn fold_item_const(&mut self, i: ItemConst) -> ItemConst { - fold_item_const(self, i) - } - #[cfg(feature = "full")] - fn fold_item_enum(&mut self, i: ItemEnum) -> ItemEnum { - fold_item_enum(self, i) - } - #[cfg(feature = "full")] - fn fold_item_existential(&mut self, i: ItemExistential) -> ItemExistential { - fold_item_existential(self, i) - } - #[cfg(feature = "full")] - fn fold_item_extern_crate(&mut self, i: ItemExternCrate) -> ItemExternCrate { - fold_item_extern_crate(self, i) - } - #[cfg(feature = "full")] - fn fold_item_fn(&mut self, i: ItemFn) -> ItemFn { - fold_item_fn(self, i) - } - #[cfg(feature = "full")] - fn fold_item_foreign_mod(&mut self, i: ItemForeignMod) -> ItemForeignMod { - fold_item_foreign_mod(self, i) - } - #[cfg(feature = "full")] - fn fold_item_impl(&mut self, i: ItemImpl) -> ItemImpl { - fold_item_impl(self, i) - } - #[cfg(feature = "full")] - fn fold_item_macro(&mut self, i: ItemMacro) -> ItemMacro { - fold_item_macro(self, i) - } - #[cfg(feature = "full")] - fn fold_item_macro2(&mut self, i: ItemMacro2) -> ItemMacro2 { - fold_item_macro2(self, i) - } - #[cfg(feature = "full")] - fn fold_item_mod(&mut self, i: ItemMod) -> ItemMod { - fold_item_mod(self, i) - } - #[cfg(feature = "full")] - fn fold_item_static(&mut self, i: ItemStatic) -> ItemStatic { - fold_item_static(self, i) - } - #[cfg(feature = "full")] - fn fold_item_struct(&mut self, i: ItemStruct) -> ItemStruct { - fold_item_struct(self, i) - } - #[cfg(feature = "full")] - fn fold_item_trait(&mut self, i: ItemTrait) -> ItemTrait { - fold_item_trait(self, i) - } - #[cfg(feature = "full")] - fn fold_item_trait_alias(&mut self, i: ItemTraitAlias) -> ItemTraitAlias { - fold_item_trait_alias(self, i) - } - #[cfg(feature = "full")] - fn fold_item_type(&mut self, i: ItemType) -> ItemType { - fold_item_type(self, i) - } - #[cfg(feature = "full")] - fn fold_item_union(&mut self, i: ItemUnion) -> ItemUnion { - fold_item_union(self, i) - } - #[cfg(feature = "full")] - fn fold_item_use(&mut self, i: ItemUse) -> ItemUse { - fold_item_use(self, i) - } - #[cfg(feature = "full")] - fn fold_item_verbatim(&mut self, i: ItemVerbatim) -> ItemVerbatim { - fold_item_verbatim(self, i) - } - #[cfg(feature = "full")] - fn fold_label(&mut self, i: Label) -> Label { - fold_label(self, i) - } - fn fold_lifetime(&mut self, i: Lifetime) -> Lifetime { - fold_lifetime(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lifetime_def(&mut self, i: LifetimeDef) -> LifetimeDef { - fold_lifetime_def(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lit(&mut self, i: Lit) -> Lit { - fold_lit(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lit_bool(&mut self, i: LitBool) -> LitBool { - fold_lit_bool(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lit_byte(&mut self, i: LitByte) -> LitByte { - fold_lit_byte(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lit_byte_str(&mut self, i: LitByteStr) -> LitByteStr { - fold_lit_byte_str(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lit_char(&mut self, i: LitChar) -> LitChar { - fold_lit_char(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lit_float(&mut self, i: LitFloat) -> LitFloat { - fold_lit_float(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lit_int(&mut self, i: LitInt) -> LitInt { - fold_lit_int(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lit_str(&mut self, i: LitStr) -> LitStr { - fold_lit_str(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_lit_verbatim(&mut self, i: LitVerbatim) -> LitVerbatim { - fold_lit_verbatim(self, i) - } - #[cfg(feature = "full")] - fn fold_local(&mut self, i: Local) -> Local { - fold_local(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_macro(&mut self, i: Macro) -> Macro { - fold_macro(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_macro_delimiter(&mut self, i: MacroDelimiter) -> MacroDelimiter { - fold_macro_delimiter(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_member(&mut self, i: Member) -> Member { - fold_member(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_meta(&mut self, i: Meta) -> Meta { - fold_meta(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_meta_list(&mut self, i: MetaList) -> MetaList { - fold_meta_list(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_meta_name_value(&mut self, i: MetaNameValue) -> MetaNameValue { - fold_meta_name_value(self, i) - } - #[cfg(feature = "full")] - fn fold_method_sig(&mut self, i: MethodSig) -> MethodSig { - fold_method_sig(self, i) - } - #[cfg(feature = "full")] - fn fold_method_turbofish(&mut self, i: MethodTurbofish) -> MethodTurbofish { - fold_method_turbofish(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_nested_meta(&mut self, i: NestedMeta) -> NestedMeta { - fold_nested_meta(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_parenthesized_generic_arguments( - &mut self, - i: ParenthesizedGenericArguments, - ) -> ParenthesizedGenericArguments { - fold_parenthesized_generic_arguments(self, i) - } - #[cfg(feature = "full")] - fn fold_pat(&mut self, i: Pat) -> Pat { - fold_pat(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_box(&mut self, i: PatBox) -> PatBox { - fold_pat_box(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_ident(&mut self, i: PatIdent) -> PatIdent { - fold_pat_ident(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_lit(&mut self, i: PatLit) -> PatLit { - fold_pat_lit(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_macro(&mut self, i: PatMacro) -> PatMacro { - fold_pat_macro(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_path(&mut self, i: PatPath) -> PatPath { - fold_pat_path(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_range(&mut self, i: PatRange) -> PatRange { - fold_pat_range(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_ref(&mut self, i: PatRef) -> PatRef { - fold_pat_ref(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_slice(&mut self, i: PatSlice) -> PatSlice { - fold_pat_slice(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_struct(&mut self, i: PatStruct) -> PatStruct { - fold_pat_struct(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_tuple(&mut self, i: PatTuple) -> PatTuple { - fold_pat_tuple(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_tuple_struct(&mut self, i: PatTupleStruct) -> PatTupleStruct { - fold_pat_tuple_struct(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_verbatim(&mut self, i: PatVerbatim) -> PatVerbatim { - fold_pat_verbatim(self, i) - } - #[cfg(feature = "full")] - fn fold_pat_wild(&mut self, i: PatWild) -> PatWild { - fold_pat_wild(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_path(&mut self, i: Path) -> Path { - fold_path(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_path_arguments(&mut self, i: PathArguments) -> PathArguments { - fold_path_arguments(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_path_segment(&mut self, i: PathSegment) -> PathSegment { - fold_path_segment(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_predicate_eq(&mut self, i: PredicateEq) -> PredicateEq { - fold_predicate_eq(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_predicate_lifetime(&mut self, i: PredicateLifetime) -> PredicateLifetime { - fold_predicate_lifetime(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_predicate_type(&mut self, i: PredicateType) -> PredicateType { - fold_predicate_type(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_qself(&mut self, i: QSelf) -> QSelf { - fold_qself(self, i) - } - #[cfg(feature = "full")] - fn fold_range_limits(&mut self, i: RangeLimits) -> RangeLimits { - fold_range_limits(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_return_type(&mut self, i: ReturnType) -> ReturnType { - fold_return_type(self, i) - } - #[cfg(feature = "full")] - fn fold_stmt(&mut self, i: Stmt) -> Stmt { - fold_stmt(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_trait_bound(&mut self, i: TraitBound) -> TraitBound { - fold_trait_bound(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_trait_bound_modifier(&mut self, i: TraitBoundModifier) -> TraitBoundModifier { - fold_trait_bound_modifier(self, i) - } - #[cfg(feature = "full")] - fn fold_trait_item(&mut self, i: TraitItem) -> TraitItem { - fold_trait_item(self, i) - } - #[cfg(feature = "full")] - fn fold_trait_item_const(&mut self, i: TraitItemConst) -> TraitItemConst { - fold_trait_item_const(self, i) - } - #[cfg(feature = "full")] - fn fold_trait_item_macro(&mut self, i: TraitItemMacro) -> TraitItemMacro { - fold_trait_item_macro(self, i) - } - #[cfg(feature = "full")] - fn fold_trait_item_method(&mut self, i: TraitItemMethod) -> TraitItemMethod { - fold_trait_item_method(self, i) - } - #[cfg(feature = "full")] - fn fold_trait_item_type(&mut self, i: TraitItemType) -> TraitItemType { - fold_trait_item_type(self, i) - } - #[cfg(feature = "full")] - fn fold_trait_item_verbatim(&mut self, i: TraitItemVerbatim) -> TraitItemVerbatim { - fold_trait_item_verbatim(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type(&mut self, i: Type) -> Type { - fold_type(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_array(&mut self, i: TypeArray) -> TypeArray { - fold_type_array(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_bare_fn(&mut self, i: TypeBareFn) -> TypeBareFn { - fold_type_bare_fn(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_group(&mut self, i: TypeGroup) -> TypeGroup { - fold_type_group(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_impl_trait(&mut self, i: TypeImplTrait) -> TypeImplTrait { - fold_type_impl_trait(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_infer(&mut self, i: TypeInfer) -> TypeInfer { - fold_type_infer(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_macro(&mut self, i: TypeMacro) -> TypeMacro { - fold_type_macro(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_never(&mut self, i: TypeNever) -> TypeNever { - fold_type_never(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_param(&mut self, i: TypeParam) -> TypeParam { - fold_type_param(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_param_bound(&mut self, i: TypeParamBound) -> TypeParamBound { - fold_type_param_bound(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_paren(&mut self, i: TypeParen) -> TypeParen { - fold_type_paren(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_path(&mut self, i: TypePath) -> TypePath { - fold_type_path(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_ptr(&mut self, i: TypePtr) -> TypePtr { - fold_type_ptr(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_reference(&mut self, i: TypeReference) -> TypeReference { - fold_type_reference(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_slice(&mut self, i: TypeSlice) -> TypeSlice { - fold_type_slice(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_trait_object(&mut self, i: TypeTraitObject) -> TypeTraitObject { - fold_type_trait_object(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_tuple(&mut self, i: TypeTuple) -> TypeTuple { - fold_type_tuple(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_type_verbatim(&mut self, i: TypeVerbatim) -> TypeVerbatim { - fold_type_verbatim(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_un_op(&mut self, i: UnOp) -> UnOp { - fold_un_op(self, i) - } - #[cfg(feature = "full")] - fn fold_use_glob(&mut self, i: UseGlob) -> UseGlob { - fold_use_glob(self, i) - } - #[cfg(feature = "full")] - fn fold_use_group(&mut self, i: UseGroup) -> UseGroup { - fold_use_group(self, i) - } - #[cfg(feature = "full")] - fn fold_use_name(&mut self, i: UseName) -> UseName { - fold_use_name(self, i) - } - #[cfg(feature = "full")] - fn fold_use_path(&mut self, i: UsePath) -> UsePath { - fold_use_path(self, i) - } - #[cfg(feature = "full")] - fn fold_use_rename(&mut self, i: UseRename) -> UseRename { - fold_use_rename(self, i) - } - #[cfg(feature = "full")] - fn fold_use_tree(&mut self, i: UseTree) -> UseTree { - fold_use_tree(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_variant(&mut self, i: Variant) -> Variant { - fold_variant(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_vis_crate(&mut self, i: VisCrate) -> VisCrate { - fold_vis_crate(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_vis_public(&mut self, i: VisPublic) -> VisPublic { - fold_vis_public(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_vis_restricted(&mut self, i: VisRestricted) -> VisRestricted { - fold_vis_restricted(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_visibility(&mut self, i: Visibility) -> Visibility { - fold_visibility(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_where_clause(&mut self, i: WhereClause) -> WhereClause { - fold_where_clause(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn fold_where_predicate(&mut self, i: WherePredicate) -> WherePredicate { - fold_where_predicate(self, i) - } - fn fold_span(&mut self, i: Span) -> Span { - fold_span(self, i) - } - fn fold_ident(&mut self, i: Ident) -> Ident { - fold_ident(self, i) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_abi<V: Fold + ?Sized>(_visitor: &mut V, _i: Abi) -> Abi { - Abi { - extern_token: Token![extern](tokens_helper(_visitor, &_i.extern_token.span)), - name: (_i.name).map(|it| _visitor.fold_lit_str(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_angle_bracketed_generic_arguments<V: Fold + ?Sized>( - _visitor: &mut V, - _i: AngleBracketedGenericArguments, -) -> AngleBracketedGenericArguments { - AngleBracketedGenericArguments { - colon2_token: (_i.colon2_token) - .map(|it| Token ! [ :: ](tokens_helper(_visitor, &it.spans))), - lt_token: Token ! [ < ](tokens_helper(_visitor, &_i.lt_token.spans)), - args: FoldHelper::lift(_i.args, |it| _visitor.fold_generic_argument(it)), - gt_token: Token ! [ > ](tokens_helper(_visitor, &_i.gt_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_arg_captured<V: Fold + ?Sized>(_visitor: &mut V, _i: ArgCaptured) -> ArgCaptured { - ArgCaptured { - pat: _visitor.fold_pat(_i.pat), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - ty: _visitor.fold_type(_i.ty), - } -} -#[cfg(feature = "full")] -pub fn fold_arg_self<V: Fold + ?Sized>(_visitor: &mut V, _i: ArgSelf) -> ArgSelf { - ArgSelf { - mutability: (_i.mutability).map(|it| Token![mut](tokens_helper(_visitor, &it.span))), - self_token: Token![self](tokens_helper(_visitor, &_i.self_token.span)), - } -} -#[cfg(feature = "full")] -pub fn fold_arg_self_ref<V: Fold + ?Sized>(_visitor: &mut V, _i: ArgSelfRef) -> ArgSelfRef { - ArgSelfRef { - and_token: Token ! [ & ](tokens_helper(_visitor, &_i.and_token.spans)), - lifetime: (_i.lifetime).map(|it| _visitor.fold_lifetime(it)), - mutability: (_i.mutability).map(|it| Token![mut](tokens_helper(_visitor, &it.span))), - self_token: Token![self](tokens_helper(_visitor, &_i.self_token.span)), - } -} -#[cfg(feature = "full")] -pub fn fold_arm<V: Fold + ?Sized>(_visitor: &mut V, _i: Arm) -> Arm { - Arm { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - leading_vert: (_i.leading_vert).map(|it| Token ! [ | ](tokens_helper(_visitor, &it.spans))), - pats: FoldHelper::lift(_i.pats, |it| _visitor.fold_pat(it)), - guard: (_i.guard).map(|it| { - ( - Token![if](tokens_helper(_visitor, &(it).0.span)), - Box::new(_visitor.fold_expr(*(it).1)), - ) - }), - fat_arrow_token: Token ! [ => ](tokens_helper(_visitor, &_i.fat_arrow_token.spans)), - body: Box::new(_visitor.fold_expr(*_i.body)), - comma: (_i.comma).map(|it| Token ! [ , ](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_attr_style<V: Fold + ?Sized>(_visitor: &mut V, _i: AttrStyle) -> AttrStyle { - match _i { - AttrStyle::Outer => AttrStyle::Outer, - AttrStyle::Inner(_binding_0) => { - AttrStyle::Inner(Token![!](tokens_helper(_visitor, &_binding_0.spans))) - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_attribute<V: Fold + ?Sized>(_visitor: &mut V, _i: Attribute) -> Attribute { - Attribute { - pound_token: Token ! [ # ](tokens_helper(_visitor, &_i.pound_token.spans)), - style: _visitor.fold_attr_style(_i.style), - bracket_token: Bracket(tokens_helper(_visitor, &_i.bracket_token.span)), - path: _visitor.fold_path(_i.path), - tts: _i.tts, - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_bare_fn_arg<V: Fold + ?Sized>(_visitor: &mut V, _i: BareFnArg) -> BareFnArg { - BareFnArg { - name: (_i.name).map(|it| { - ( - _visitor.fold_bare_fn_arg_name((it).0), - Token ! [ : ](tokens_helper(_visitor, &(it).1.spans)), - ) - }), - ty: _visitor.fold_type(_i.ty), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_bare_fn_arg_name<V: Fold + ?Sized>( - _visitor: &mut V, - _i: BareFnArgName, -) -> BareFnArgName { - match _i { - BareFnArgName::Named(_binding_0) => BareFnArgName::Named(_visitor.fold_ident(_binding_0)), - BareFnArgName::Wild(_binding_0) => { - BareFnArgName::Wild(Token![_](tokens_helper(_visitor, &_binding_0.spans))) - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_bin_op<V: Fold + ?Sized>(_visitor: &mut V, _i: BinOp) -> BinOp { - match _i { - BinOp::Add(_binding_0) => { - BinOp::Add(Token ! [ + ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Sub(_binding_0) => { - BinOp::Sub(Token ! [ - ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Mul(_binding_0) => { - BinOp::Mul(Token ! [ * ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Div(_binding_0) => { - BinOp::Div(Token ! [ / ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Rem(_binding_0) => { - BinOp::Rem(Token ! [ % ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::And(_binding_0) => { - BinOp::And(Token ! [ && ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Or(_binding_0) => { - BinOp::Or(Token ! [ || ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::BitXor(_binding_0) => { - BinOp::BitXor(Token ! [ ^ ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::BitAnd(_binding_0) => { - BinOp::BitAnd(Token ! [ & ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::BitOr(_binding_0) => { - BinOp::BitOr(Token ! [ | ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Shl(_binding_0) => { - BinOp::Shl(Token ! [ << ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Shr(_binding_0) => { - BinOp::Shr(Token ! [ >> ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Eq(_binding_0) => { - BinOp::Eq(Token ! [ == ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Lt(_binding_0) => { - BinOp::Lt(Token ! [ < ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Le(_binding_0) => { - BinOp::Le(Token ! [ <= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Ne(_binding_0) => { - BinOp::Ne(Token ! [ != ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Ge(_binding_0) => { - BinOp::Ge(Token ! [ >= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::Gt(_binding_0) => { - BinOp::Gt(Token ! [ > ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::AddEq(_binding_0) => { - BinOp::AddEq(Token ! [ += ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::SubEq(_binding_0) => { - BinOp::SubEq(Token ! [ -= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::MulEq(_binding_0) => { - BinOp::MulEq(Token ! [ *= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::DivEq(_binding_0) => { - BinOp::DivEq(Token ! [ /= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::RemEq(_binding_0) => { - BinOp::RemEq(Token ! [ %= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::BitXorEq(_binding_0) => { - BinOp::BitXorEq(Token ! [ ^= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::BitAndEq(_binding_0) => { - BinOp::BitAndEq(Token ! [ &= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::BitOrEq(_binding_0) => { - BinOp::BitOrEq(Token ! [ |= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::ShlEq(_binding_0) => { - BinOp::ShlEq(Token ! [ <<= ](tokens_helper(_visitor, &_binding_0.spans))) - } - BinOp::ShrEq(_binding_0) => { - BinOp::ShrEq(Token ! [ >>= ](tokens_helper(_visitor, &_binding_0.spans))) - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_binding<V: Fold + ?Sized>(_visitor: &mut V, _i: Binding) -> Binding { - Binding { - ident: _visitor.fold_ident(_i.ident), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - ty: _visitor.fold_type(_i.ty), - } -} -#[cfg(feature = "full")] -pub fn fold_block<V: Fold + ?Sized>(_visitor: &mut V, _i: Block) -> Block { - Block { - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - stmts: FoldHelper::lift(_i.stmts, |it| _visitor.fold_stmt(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_bound_lifetimes<V: Fold + ?Sized>( - _visitor: &mut V, - _i: BoundLifetimes, -) -> BoundLifetimes { - BoundLifetimes { - for_token: Token![for](tokens_helper(_visitor, &_i.for_token.span)), - lt_token: Token ! [ < ](tokens_helper(_visitor, &_i.lt_token.spans)), - lifetimes: FoldHelper::lift(_i.lifetimes, |it| _visitor.fold_lifetime_def(it)), - gt_token: Token ! [ > ](tokens_helper(_visitor, &_i.gt_token.spans)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_const_param<V: Fold + ?Sized>(_visitor: &mut V, _i: ConstParam) -> ConstParam { - ConstParam { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - const_token: Token![const](tokens_helper(_visitor, &_i.const_token.span)), - ident: _visitor.fold_ident(_i.ident), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - ty: _visitor.fold_type(_i.ty), - eq_token: (_i.eq_token).map(|it| Token ! [ = ](tokens_helper(_visitor, &it.spans))), - default: (_i.default).map(|it| _visitor.fold_expr(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_constraint<V: Fold + ?Sized>(_visitor: &mut V, _i: Constraint) -> Constraint { - Constraint { - ident: _visitor.fold_ident(_i.ident), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_type_param_bound(it)), - } -} -#[cfg(feature = "derive")] -pub fn fold_data<V: Fold + ?Sized>(_visitor: &mut V, _i: Data) -> Data { - match _i { - Data::Struct(_binding_0) => Data::Struct(_visitor.fold_data_struct(_binding_0)), - Data::Enum(_binding_0) => Data::Enum(_visitor.fold_data_enum(_binding_0)), - Data::Union(_binding_0) => Data::Union(_visitor.fold_data_union(_binding_0)), - } -} -#[cfg(feature = "derive")] -pub fn fold_data_enum<V: Fold + ?Sized>(_visitor: &mut V, _i: DataEnum) -> DataEnum { - DataEnum { - enum_token: Token![enum](tokens_helper(_visitor, &_i.enum_token.span)), - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - variants: FoldHelper::lift(_i.variants, |it| _visitor.fold_variant(it)), - } -} -#[cfg(feature = "derive")] -pub fn fold_data_struct<V: Fold + ?Sized>(_visitor: &mut V, _i: DataStruct) -> DataStruct { - DataStruct { - struct_token: Token![struct](tokens_helper(_visitor, &_i.struct_token.span)), - fields: _visitor.fold_fields(_i.fields), - semi_token: (_i.semi_token).map(|it| Token ! [ ; ](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(feature = "derive")] -pub fn fold_data_union<V: Fold + ?Sized>(_visitor: &mut V, _i: DataUnion) -> DataUnion { - DataUnion { - union_token: Token![union](tokens_helper(_visitor, &_i.union_token.span)), - fields: _visitor.fold_fields_named(_i.fields), - } -} -#[cfg(feature = "derive")] -pub fn fold_derive_input<V: Fold + ?Sized>(_visitor: &mut V, _i: DeriveInput) -> DeriveInput { - DeriveInput { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - data: _visitor.fold_data(_i.data), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr<V: Fold + ?Sized>(_visitor: &mut V, _i: Expr) -> Expr { - match _i { - Expr::Box(_binding_0) => Expr::Box(full!(_visitor.fold_expr_box(_binding_0))), - Expr::InPlace(_binding_0) => Expr::InPlace(full!(_visitor.fold_expr_in_place(_binding_0))), - Expr::Array(_binding_0) => Expr::Array(full!(_visitor.fold_expr_array(_binding_0))), - Expr::Call(_binding_0) => Expr::Call(_visitor.fold_expr_call(_binding_0)), - Expr::MethodCall(_binding_0) => { - Expr::MethodCall(full!(_visitor.fold_expr_method_call(_binding_0))) - } - Expr::Tuple(_binding_0) => Expr::Tuple(full!(_visitor.fold_expr_tuple(_binding_0))), - Expr::Binary(_binding_0) => Expr::Binary(_visitor.fold_expr_binary(_binding_0)), - Expr::Unary(_binding_0) => Expr::Unary(_visitor.fold_expr_unary(_binding_0)), - Expr::Lit(_binding_0) => Expr::Lit(_visitor.fold_expr_lit(_binding_0)), - Expr::Cast(_binding_0) => Expr::Cast(_visitor.fold_expr_cast(_binding_0)), - Expr::Type(_binding_0) => Expr::Type(full!(_visitor.fold_expr_type(_binding_0))), - Expr::Let(_binding_0) => Expr::Let(full!(_visitor.fold_expr_let(_binding_0))), - Expr::If(_binding_0) => Expr::If(full!(_visitor.fold_expr_if(_binding_0))), - Expr::While(_binding_0) => Expr::While(full!(_visitor.fold_expr_while(_binding_0))), - Expr::ForLoop(_binding_0) => Expr::ForLoop(full!(_visitor.fold_expr_for_loop(_binding_0))), - Expr::Loop(_binding_0) => Expr::Loop(full!(_visitor.fold_expr_loop(_binding_0))), - Expr::Match(_binding_0) => Expr::Match(full!(_visitor.fold_expr_match(_binding_0))), - Expr::Closure(_binding_0) => Expr::Closure(full!(_visitor.fold_expr_closure(_binding_0))), - Expr::Unsafe(_binding_0) => Expr::Unsafe(full!(_visitor.fold_expr_unsafe(_binding_0))), - Expr::Block(_binding_0) => Expr::Block(full!(_visitor.fold_expr_block(_binding_0))), - Expr::Assign(_binding_0) => Expr::Assign(full!(_visitor.fold_expr_assign(_binding_0))), - Expr::AssignOp(_binding_0) => { - Expr::AssignOp(full!(_visitor.fold_expr_assign_op(_binding_0))) - } - Expr::Field(_binding_0) => Expr::Field(_visitor.fold_expr_field(_binding_0)), - Expr::Index(_binding_0) => Expr::Index(_visitor.fold_expr_index(_binding_0)), - Expr::Range(_binding_0) => Expr::Range(full!(_visitor.fold_expr_range(_binding_0))), - Expr::Path(_binding_0) => Expr::Path(_visitor.fold_expr_path(_binding_0)), - Expr::Reference(_binding_0) => { - Expr::Reference(full!(_visitor.fold_expr_reference(_binding_0))) - } - Expr::Break(_binding_0) => Expr::Break(full!(_visitor.fold_expr_break(_binding_0))), - Expr::Continue(_binding_0) => { - Expr::Continue(full!(_visitor.fold_expr_continue(_binding_0))) - } - Expr::Return(_binding_0) => Expr::Return(full!(_visitor.fold_expr_return(_binding_0))), - Expr::Macro(_binding_0) => Expr::Macro(full!(_visitor.fold_expr_macro(_binding_0))), - Expr::Struct(_binding_0) => Expr::Struct(full!(_visitor.fold_expr_struct(_binding_0))), - Expr::Repeat(_binding_0) => Expr::Repeat(full!(_visitor.fold_expr_repeat(_binding_0))), - Expr::Paren(_binding_0) => Expr::Paren(_visitor.fold_expr_paren(_binding_0)), - Expr::Group(_binding_0) => Expr::Group(full!(_visitor.fold_expr_group(_binding_0))), - Expr::Try(_binding_0) => Expr::Try(full!(_visitor.fold_expr_try(_binding_0))), - Expr::Async(_binding_0) => Expr::Async(full!(_visitor.fold_expr_async(_binding_0))), - Expr::TryBlock(_binding_0) => { - Expr::TryBlock(full!(_visitor.fold_expr_try_block(_binding_0))) - } - Expr::Yield(_binding_0) => Expr::Yield(full!(_visitor.fold_expr_yield(_binding_0))), - Expr::Verbatim(_binding_0) => Expr::Verbatim(_visitor.fold_expr_verbatim(_binding_0)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_array<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprArray) -> ExprArray { - ExprArray { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - bracket_token: Bracket(tokens_helper(_visitor, &_i.bracket_token.span)), - elems: FoldHelper::lift(_i.elems, |it| _visitor.fold_expr(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_assign<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprAssign) -> ExprAssign { - ExprAssign { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - left: Box::new(_visitor.fold_expr(*_i.left)), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - right: Box::new(_visitor.fold_expr(*_i.right)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_assign_op<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprAssignOp) -> ExprAssignOp { - ExprAssignOp { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - left: Box::new(_visitor.fold_expr(*_i.left)), - op: _visitor.fold_bin_op(_i.op), - right: Box::new(_visitor.fold_expr(*_i.right)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_async<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprAsync) -> ExprAsync { - ExprAsync { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - async_token: Token![async](tokens_helper(_visitor, &_i.async_token.span)), - capture: (_i.capture).map(|it| Token![move](tokens_helper(_visitor, &it.span))), - block: _visitor.fold_block(_i.block), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_binary<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprBinary) -> ExprBinary { - ExprBinary { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - left: Box::new(_visitor.fold_expr(*_i.left)), - op: _visitor.fold_bin_op(_i.op), - right: Box::new(_visitor.fold_expr(*_i.right)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_block<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprBlock) -> ExprBlock { - ExprBlock { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - label: (_i.label).map(|it| _visitor.fold_label(it)), - block: _visitor.fold_block(_i.block), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_box<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprBox) -> ExprBox { - ExprBox { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - box_token: Token![box](tokens_helper(_visitor, &_i.box_token.span)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_break<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprBreak) -> ExprBreak { - ExprBreak { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - break_token: Token![break](tokens_helper(_visitor, &_i.break_token.span)), - label: (_i.label).map(|it| _visitor.fold_lifetime(it)), - expr: (_i.expr).map(|it| Box::new(_visitor.fold_expr(*it))), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_call<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprCall) -> ExprCall { - ExprCall { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - func: Box::new(_visitor.fold_expr(*_i.func)), - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - args: FoldHelper::lift(_i.args, |it| _visitor.fold_expr(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_cast<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprCast) -> ExprCast { - ExprCast { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - as_token: Token![as](tokens_helper(_visitor, &_i.as_token.span)), - ty: Box::new(_visitor.fold_type(*_i.ty)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_closure<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprClosure) -> ExprClosure { - ExprClosure { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - asyncness: (_i.asyncness).map(|it| Token![async](tokens_helper(_visitor, &it.span))), - movability: (_i.movability).map(|it| Token![static](tokens_helper(_visitor, &it.span))), - capture: (_i.capture).map(|it| Token![move](tokens_helper(_visitor, &it.span))), - or1_token: Token ! [ | ](tokens_helper(_visitor, &_i.or1_token.spans)), - inputs: FoldHelper::lift(_i.inputs, |it| _visitor.fold_fn_arg(it)), - or2_token: Token ! [ | ](tokens_helper(_visitor, &_i.or2_token.spans)), - output: _visitor.fold_return_type(_i.output), - body: Box::new(_visitor.fold_expr(*_i.body)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_continue<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprContinue) -> ExprContinue { - ExprContinue { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - continue_token: Token![continue](tokens_helper(_visitor, &_i.continue_token.span)), - label: (_i.label).map(|it| _visitor.fold_lifetime(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_field<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprField) -> ExprField { - ExprField { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - base: Box::new(_visitor.fold_expr(*_i.base)), - dot_token: Token ! [ . ](tokens_helper(_visitor, &_i.dot_token.spans)), - member: _visitor.fold_member(_i.member), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_for_loop<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprForLoop) -> ExprForLoop { - ExprForLoop { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - label: (_i.label).map(|it| _visitor.fold_label(it)), - for_token: Token![for](tokens_helper(_visitor, &_i.for_token.span)), - pat: Box::new(_visitor.fold_pat(*_i.pat)), - in_token: Token![in](tokens_helper(_visitor, &_i.in_token.span)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - body: _visitor.fold_block(_i.body), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_group<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprGroup) -> ExprGroup { - ExprGroup { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - group_token: Group(tokens_helper(_visitor, &_i.group_token.span)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_if<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprIf) -> ExprIf { - ExprIf { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - if_token: Token![if](tokens_helper(_visitor, &_i.if_token.span)), - cond: Box::new(_visitor.fold_expr(*_i.cond)), - then_branch: _visitor.fold_block(_i.then_branch), - else_branch: (_i.else_branch).map(|it| { - ( - Token![else](tokens_helper(_visitor, &(it).0.span)), - Box::new(_visitor.fold_expr(*(it).1)), - ) - }), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_in_place<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprInPlace) -> ExprInPlace { - ExprInPlace { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - place: Box::new(_visitor.fold_expr(*_i.place)), - arrow_token: Token ! [ <- ](tokens_helper(_visitor, &_i.arrow_token.spans)), - value: Box::new(_visitor.fold_expr(*_i.value)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_index<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprIndex) -> ExprIndex { - ExprIndex { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - bracket_token: Bracket(tokens_helper(_visitor, &_i.bracket_token.span)), - index: Box::new(_visitor.fold_expr(*_i.index)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_let<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprLet) -> ExprLet { - ExprLet { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - let_token: Token![let](tokens_helper(_visitor, &_i.let_token.span)), - pats: FoldHelper::lift(_i.pats, |it| _visitor.fold_pat(it)), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_lit<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprLit) -> ExprLit { - ExprLit { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - lit: _visitor.fold_lit(_i.lit), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_loop<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprLoop) -> ExprLoop { - ExprLoop { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - label: (_i.label).map(|it| _visitor.fold_label(it)), - loop_token: Token![loop](tokens_helper(_visitor, &_i.loop_token.span)), - body: _visitor.fold_block(_i.body), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprMacro) -> ExprMacro { - ExprMacro { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - mac: _visitor.fold_macro(_i.mac), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_match<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprMatch) -> ExprMatch { - ExprMatch { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - match_token: Token![match](tokens_helper(_visitor, &_i.match_token.span)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - arms: FoldHelper::lift(_i.arms, |it| _visitor.fold_arm(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_method_call<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ExprMethodCall, -) -> ExprMethodCall { - ExprMethodCall { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - receiver: Box::new(_visitor.fold_expr(*_i.receiver)), - dot_token: Token ! [ . ](tokens_helper(_visitor, &_i.dot_token.spans)), - method: _visitor.fold_ident(_i.method), - turbofish: (_i.turbofish).map(|it| _visitor.fold_method_turbofish(it)), - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - args: FoldHelper::lift(_i.args, |it| _visitor.fold_expr(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_paren<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprParen) -> ExprParen { - ExprParen { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_path<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprPath) -> ExprPath { - ExprPath { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - qself: (_i.qself).map(|it| _visitor.fold_qself(it)), - path: _visitor.fold_path(_i.path), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_range<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprRange) -> ExprRange { - ExprRange { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - from: (_i.from).map(|it| Box::new(_visitor.fold_expr(*it))), - limits: _visitor.fold_range_limits(_i.limits), - to: (_i.to).map(|it| Box::new(_visitor.fold_expr(*it))), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_reference<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprReference) -> ExprReference { - ExprReference { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - and_token: Token ! [ & ](tokens_helper(_visitor, &_i.and_token.spans)), - mutability: (_i.mutability).map(|it| Token![mut](tokens_helper(_visitor, &it.span))), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_repeat<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprRepeat) -> ExprRepeat { - ExprRepeat { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - bracket_token: Bracket(tokens_helper(_visitor, &_i.bracket_token.span)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - len: Box::new(_visitor.fold_expr(*_i.len)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_return<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprReturn) -> ExprReturn { - ExprReturn { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - return_token: Token![return](tokens_helper(_visitor, &_i.return_token.span)), - expr: (_i.expr).map(|it| Box::new(_visitor.fold_expr(*it))), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_struct<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprStruct) -> ExprStruct { - ExprStruct { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - path: _visitor.fold_path(_i.path), - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - fields: FoldHelper::lift(_i.fields, |it| _visitor.fold_field_value(it)), - dot2_token: (_i.dot2_token).map(|it| Token![..](tokens_helper(_visitor, &it.spans))), - rest: (_i.rest).map(|it| Box::new(_visitor.fold_expr(*it))), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_try<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprTry) -> ExprTry { - ExprTry { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - question_token: Token ! [ ? ](tokens_helper(_visitor, &_i.question_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_try_block<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprTryBlock) -> ExprTryBlock { - ExprTryBlock { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - try_token: Token![try](tokens_helper(_visitor, &_i.try_token.span)), - block: _visitor.fold_block(_i.block), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_tuple<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprTuple) -> ExprTuple { - ExprTuple { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - elems: FoldHelper::lift(_i.elems, |it| _visitor.fold_expr(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_type<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprType) -> ExprType { - ExprType { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - ty: Box::new(_visitor.fold_type(*_i.ty)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_unary<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprUnary) -> ExprUnary { - ExprUnary { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - op: _visitor.fold_un_op(_i.op), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_unsafe<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprUnsafe) -> ExprUnsafe { - ExprUnsafe { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - unsafe_token: Token![unsafe](tokens_helper(_visitor, &_i.unsafe_token.span)), - block: _visitor.fold_block(_i.block), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_expr_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprVerbatim) -> ExprVerbatim { - ExprVerbatim { tts: _i.tts } -} -#[cfg(feature = "full")] -pub fn fold_expr_while<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprWhile) -> ExprWhile { - ExprWhile { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - label: (_i.label).map(|it| _visitor.fold_label(it)), - while_token: Token![while](tokens_helper(_visitor, &_i.while_token.span)), - cond: Box::new(_visitor.fold_expr(*_i.cond)), - body: _visitor.fold_block(_i.body), - } -} -#[cfg(feature = "full")] -pub fn fold_expr_yield<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprYield) -> ExprYield { - ExprYield { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - yield_token: Token![yield](tokens_helper(_visitor, &_i.yield_token.span)), - expr: (_i.expr).map(|it| Box::new(_visitor.fold_expr(*it))), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_field<V: Fold + ?Sized>(_visitor: &mut V, _i: Field) -> Field { - Field { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - ident: (_i.ident).map(|it| _visitor.fold_ident(it)), - colon_token: (_i.colon_token).map(|it| Token ! [ : ](tokens_helper(_visitor, &it.spans))), - ty: _visitor.fold_type(_i.ty), - } -} -#[cfg(feature = "full")] -pub fn fold_field_pat<V: Fold + ?Sized>(_visitor: &mut V, _i: FieldPat) -> FieldPat { - FieldPat { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - member: _visitor.fold_member(_i.member), - colon_token: (_i.colon_token).map(|it| Token ! [ : ](tokens_helper(_visitor, &it.spans))), - pat: Box::new(_visitor.fold_pat(*_i.pat)), - } -} -#[cfg(feature = "full")] -pub fn fold_field_value<V: Fold + ?Sized>(_visitor: &mut V, _i: FieldValue) -> FieldValue { - FieldValue { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - member: _visitor.fold_member(_i.member), - colon_token: (_i.colon_token).map(|it| Token ! [ : ](tokens_helper(_visitor, &it.spans))), - expr: _visitor.fold_expr(_i.expr), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_fields<V: Fold + ?Sized>(_visitor: &mut V, _i: Fields) -> Fields { - match _i { - Fields::Named(_binding_0) => Fields::Named(_visitor.fold_fields_named(_binding_0)), - Fields::Unnamed(_binding_0) => Fields::Unnamed(_visitor.fold_fields_unnamed(_binding_0)), - Fields::Unit => Fields::Unit, - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_fields_named<V: Fold + ?Sized>(_visitor: &mut V, _i: FieldsNamed) -> FieldsNamed { - FieldsNamed { - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - named: FoldHelper::lift(_i.named, |it| _visitor.fold_field(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_fields_unnamed<V: Fold + ?Sized>(_visitor: &mut V, _i: FieldsUnnamed) -> FieldsUnnamed { - FieldsUnnamed { - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - unnamed: FoldHelper::lift(_i.unnamed, |it| _visitor.fold_field(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_file<V: Fold + ?Sized>(_visitor: &mut V, _i: File) -> File { - File { - shebang: _i.shebang, - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - items: FoldHelper::lift(_i.items, |it| _visitor.fold_item(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_fn_arg<V: Fold + ?Sized>(_visitor: &mut V, _i: FnArg) -> FnArg { - match _i { - FnArg::SelfRef(_binding_0) => FnArg::SelfRef(_visitor.fold_arg_self_ref(_binding_0)), - FnArg::SelfValue(_binding_0) => FnArg::SelfValue(_visitor.fold_arg_self(_binding_0)), - FnArg::Captured(_binding_0) => FnArg::Captured(_visitor.fold_arg_captured(_binding_0)), - FnArg::Inferred(_binding_0) => FnArg::Inferred(_visitor.fold_pat(_binding_0)), - FnArg::Ignored(_binding_0) => FnArg::Ignored(_visitor.fold_type(_binding_0)), - } -} -#[cfg(feature = "full")] -pub fn fold_fn_decl<V: Fold + ?Sized>(_visitor: &mut V, _i: FnDecl) -> FnDecl { - FnDecl { - fn_token: Token![fn](tokens_helper(_visitor, &_i.fn_token.span)), - generics: _visitor.fold_generics(_i.generics), - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - inputs: FoldHelper::lift(_i.inputs, |it| _visitor.fold_fn_arg(it)), - variadic: (_i.variadic).map(|it| Token ! [ ... ](tokens_helper(_visitor, &it.spans))), - output: _visitor.fold_return_type(_i.output), - } -} -#[cfg(feature = "full")] -pub fn fold_foreign_item<V: Fold + ?Sized>(_visitor: &mut V, _i: ForeignItem) -> ForeignItem { - match _i { - ForeignItem::Fn(_binding_0) => ForeignItem::Fn(_visitor.fold_foreign_item_fn(_binding_0)), - ForeignItem::Static(_binding_0) => { - ForeignItem::Static(_visitor.fold_foreign_item_static(_binding_0)) - } - ForeignItem::Type(_binding_0) => { - ForeignItem::Type(_visitor.fold_foreign_item_type(_binding_0)) - } - ForeignItem::Macro(_binding_0) => { - ForeignItem::Macro(_visitor.fold_foreign_item_macro(_binding_0)) - } - ForeignItem::Verbatim(_binding_0) => { - ForeignItem::Verbatim(_visitor.fold_foreign_item_verbatim(_binding_0)) - } - } -} -#[cfg(feature = "full")] -pub fn fold_foreign_item_fn<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ForeignItemFn, -) -> ForeignItemFn { - ForeignItemFn { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - ident: _visitor.fold_ident(_i.ident), - decl: Box::new(_visitor.fold_fn_decl(*_i.decl)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_foreign_item_macro<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ForeignItemMacro, -) -> ForeignItemMacro { - ForeignItemMacro { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - mac: _visitor.fold_macro(_i.mac), - semi_token: (_i.semi_token).map(|it| Token ! [ ; ](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(feature = "full")] -pub fn fold_foreign_item_static<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ForeignItemStatic, -) -> ForeignItemStatic { - ForeignItemStatic { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - static_token: Token![static](tokens_helper(_visitor, &_i.static_token.span)), - mutability: (_i.mutability).map(|it| Token![mut](tokens_helper(_visitor, &it.span))), - ident: _visitor.fold_ident(_i.ident), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - ty: Box::new(_visitor.fold_type(*_i.ty)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_foreign_item_type<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ForeignItemType, -) -> ForeignItemType { - ForeignItemType { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - type_token: Token![type](tokens_helper(_visitor, &_i.type_token.span)), - ident: _visitor.fold_ident(_i.ident), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_foreign_item_verbatim<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ForeignItemVerbatim, -) -> ForeignItemVerbatim { - ForeignItemVerbatim { tts: _i.tts } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_generic_argument<V: Fold + ?Sized>( - _visitor: &mut V, - _i: GenericArgument, -) -> GenericArgument { - match _i { - GenericArgument::Lifetime(_binding_0) => { - GenericArgument::Lifetime(_visitor.fold_lifetime(_binding_0)) - } - GenericArgument::Type(_binding_0) => GenericArgument::Type(_visitor.fold_type(_binding_0)), - GenericArgument::Binding(_binding_0) => { - GenericArgument::Binding(_visitor.fold_binding(_binding_0)) - } - GenericArgument::Constraint(_binding_0) => { - GenericArgument::Constraint(_visitor.fold_constraint(_binding_0)) - } - GenericArgument::Const(_binding_0) => { - GenericArgument::Const(_visitor.fold_expr(_binding_0)) - } - } -} -#[cfg(feature = "full")] -pub fn fold_generic_method_argument<V: Fold + ?Sized>( - _visitor: &mut V, - _i: GenericMethodArgument, -) -> GenericMethodArgument { - match _i { - GenericMethodArgument::Type(_binding_0) => { - GenericMethodArgument::Type(_visitor.fold_type(_binding_0)) - } - GenericMethodArgument::Const(_binding_0) => { - GenericMethodArgument::Const(_visitor.fold_expr(_binding_0)) - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_generic_param<V: Fold + ?Sized>(_visitor: &mut V, _i: GenericParam) -> GenericParam { - match _i { - GenericParam::Type(_binding_0) => GenericParam::Type(_visitor.fold_type_param(_binding_0)), - GenericParam::Lifetime(_binding_0) => { - GenericParam::Lifetime(_visitor.fold_lifetime_def(_binding_0)) - } - GenericParam::Const(_binding_0) => { - GenericParam::Const(_visitor.fold_const_param(_binding_0)) - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_generics<V: Fold + ?Sized>(_visitor: &mut V, _i: Generics) -> Generics { - Generics { - lt_token: (_i.lt_token).map(|it| Token ! [ < ](tokens_helper(_visitor, &it.spans))), - params: FoldHelper::lift(_i.params, |it| _visitor.fold_generic_param(it)), - gt_token: (_i.gt_token).map(|it| Token ! [ > ](tokens_helper(_visitor, &it.spans))), - where_clause: (_i.where_clause).map(|it| _visitor.fold_where_clause(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_impl_item<V: Fold + ?Sized>(_visitor: &mut V, _i: ImplItem) -> ImplItem { - match _i { - ImplItem::Const(_binding_0) => ImplItem::Const(_visitor.fold_impl_item_const(_binding_0)), - ImplItem::Method(_binding_0) => { - ImplItem::Method(_visitor.fold_impl_item_method(_binding_0)) - } - ImplItem::Type(_binding_0) => ImplItem::Type(_visitor.fold_impl_item_type(_binding_0)), - ImplItem::Existential(_binding_0) => { - ImplItem::Existential(_visitor.fold_impl_item_existential(_binding_0)) - } - ImplItem::Macro(_binding_0) => ImplItem::Macro(_visitor.fold_impl_item_macro(_binding_0)), - ImplItem::Verbatim(_binding_0) => { - ImplItem::Verbatim(_visitor.fold_impl_item_verbatim(_binding_0)) - } - } -} -#[cfg(feature = "full")] -pub fn fold_impl_item_const<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ImplItemConst, -) -> ImplItemConst { - ImplItemConst { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - defaultness: (_i.defaultness).map(|it| Token![default](tokens_helper(_visitor, &it.span))), - const_token: Token![const](tokens_helper(_visitor, &_i.const_token.span)), - ident: _visitor.fold_ident(_i.ident), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - ty: _visitor.fold_type(_i.ty), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - expr: _visitor.fold_expr(_i.expr), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_impl_item_existential<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ImplItemExistential, -) -> ImplItemExistential { - ImplItemExistential { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - existential_token: Token![existential](tokens_helper(_visitor, &_i.existential_token.span)), - type_token: Token![type](tokens_helper(_visitor, &_i.type_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - colon_token: (_i.colon_token).map(|it| Token ! [ : ](tokens_helper(_visitor, &it.spans))), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_type_param_bound(it)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_impl_item_macro<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ImplItemMacro, -) -> ImplItemMacro { - ImplItemMacro { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - mac: _visitor.fold_macro(_i.mac), - semi_token: (_i.semi_token).map(|it| Token ! [ ; ](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(feature = "full")] -pub fn fold_impl_item_method<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ImplItemMethod, -) -> ImplItemMethod { - ImplItemMethod { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - defaultness: (_i.defaultness).map(|it| Token![default](tokens_helper(_visitor, &it.span))), - sig: _visitor.fold_method_sig(_i.sig), - block: _visitor.fold_block(_i.block), - } -} -#[cfg(feature = "full")] -pub fn fold_impl_item_type<V: Fold + ?Sized>(_visitor: &mut V, _i: ImplItemType) -> ImplItemType { - ImplItemType { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - defaultness: (_i.defaultness).map(|it| Token![default](tokens_helper(_visitor, &it.span))), - type_token: Token![type](tokens_helper(_visitor, &_i.type_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - ty: _visitor.fold_type(_i.ty), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_impl_item_verbatim<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ImplItemVerbatim, -) -> ImplItemVerbatim { - ImplItemVerbatim { tts: _i.tts } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_index<V: Fold + ?Sized>(_visitor: &mut V, _i: Index) -> Index { - Index { - index: _i.index, - span: _visitor.fold_span(_i.span), - } -} -#[cfg(feature = "full")] -pub fn fold_item<V: Fold + ?Sized>(_visitor: &mut V, _i: Item) -> Item { - match _i { - Item::ExternCrate(_binding_0) => { - Item::ExternCrate(_visitor.fold_item_extern_crate(_binding_0)) - } - Item::Use(_binding_0) => Item::Use(_visitor.fold_item_use(_binding_0)), - Item::Static(_binding_0) => Item::Static(_visitor.fold_item_static(_binding_0)), - Item::Const(_binding_0) => Item::Const(_visitor.fold_item_const(_binding_0)), - Item::Fn(_binding_0) => Item::Fn(_visitor.fold_item_fn(_binding_0)), - Item::Mod(_binding_0) => Item::Mod(_visitor.fold_item_mod(_binding_0)), - Item::ForeignMod(_binding_0) => { - Item::ForeignMod(_visitor.fold_item_foreign_mod(_binding_0)) - } - Item::Type(_binding_0) => Item::Type(_visitor.fold_item_type(_binding_0)), - Item::Existential(_binding_0) => { - Item::Existential(_visitor.fold_item_existential(_binding_0)) - } - Item::Struct(_binding_0) => Item::Struct(_visitor.fold_item_struct(_binding_0)), - Item::Enum(_binding_0) => Item::Enum(_visitor.fold_item_enum(_binding_0)), - Item::Union(_binding_0) => Item::Union(_visitor.fold_item_union(_binding_0)), - Item::Trait(_binding_0) => Item::Trait(_visitor.fold_item_trait(_binding_0)), - Item::TraitAlias(_binding_0) => { - Item::TraitAlias(_visitor.fold_item_trait_alias(_binding_0)) - } - Item::Impl(_binding_0) => Item::Impl(_visitor.fold_item_impl(_binding_0)), - Item::Macro(_binding_0) => Item::Macro(_visitor.fold_item_macro(_binding_0)), - Item::Macro2(_binding_0) => Item::Macro2(_visitor.fold_item_macro2(_binding_0)), - Item::Verbatim(_binding_0) => Item::Verbatim(_visitor.fold_item_verbatim(_binding_0)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_const<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemConst) -> ItemConst { - ItemConst { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - const_token: Token![const](tokens_helper(_visitor, &_i.const_token.span)), - ident: _visitor.fold_ident(_i.ident), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - ty: Box::new(_visitor.fold_type(*_i.ty)), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_enum<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemEnum) -> ItemEnum { - ItemEnum { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - enum_token: Token![enum](tokens_helper(_visitor, &_i.enum_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - variants: FoldHelper::lift(_i.variants, |it| _visitor.fold_variant(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_existential<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ItemExistential, -) -> ItemExistential { - ItemExistential { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - existential_token: Token![existential](tokens_helper(_visitor, &_i.existential_token.span)), - type_token: Token![type](tokens_helper(_visitor, &_i.type_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - colon_token: (_i.colon_token).map(|it| Token ! [ : ](tokens_helper(_visitor, &it.spans))), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_type_param_bound(it)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_extern_crate<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ItemExternCrate, -) -> ItemExternCrate { - ItemExternCrate { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - extern_token: Token![extern](tokens_helper(_visitor, &_i.extern_token.span)), - crate_token: Token![crate](tokens_helper(_visitor, &_i.crate_token.span)), - ident: _visitor.fold_ident(_i.ident), - rename: (_i.rename).map(|it| { - ( - Token![as](tokens_helper(_visitor, &(it).0.span)), - _visitor.fold_ident((it).1), - ) - }), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_fn<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemFn) -> ItemFn { - ItemFn { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - constness: (_i.constness).map(|it| Token![const](tokens_helper(_visitor, &it.span))), - asyncness: (_i.asyncness).map(|it| Token![async](tokens_helper(_visitor, &it.span))), - unsafety: (_i.unsafety).map(|it| Token![unsafe](tokens_helper(_visitor, &it.span))), - abi: (_i.abi).map(|it| _visitor.fold_abi(it)), - ident: _visitor.fold_ident(_i.ident), - decl: Box::new(_visitor.fold_fn_decl(*_i.decl)), - block: Box::new(_visitor.fold_block(*_i.block)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_foreign_mod<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ItemForeignMod, -) -> ItemForeignMod { - ItemForeignMod { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - abi: _visitor.fold_abi(_i.abi), - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - items: FoldHelper::lift(_i.items, |it| _visitor.fold_foreign_item(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_impl<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemImpl) -> ItemImpl { - ItemImpl { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - defaultness: (_i.defaultness).map(|it| Token![default](tokens_helper(_visitor, &it.span))), - unsafety: (_i.unsafety).map(|it| Token![unsafe](tokens_helper(_visitor, &it.span))), - impl_token: Token![impl](tokens_helper(_visitor, &_i.impl_token.span)), - generics: _visitor.fold_generics(_i.generics), - trait_: (_i.trait_).map(|it| { - ( - ((it).0).map(|it| Token![!](tokens_helper(_visitor, &it.spans))), - _visitor.fold_path((it).1), - Token![for](tokens_helper(_visitor, &(it).2.span)), - ) - }), - self_ty: Box::new(_visitor.fold_type(*_i.self_ty)), - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - items: FoldHelper::lift(_i.items, |it| _visitor.fold_impl_item(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemMacro) -> ItemMacro { - ItemMacro { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - ident: (_i.ident).map(|it| _visitor.fold_ident(it)), - mac: _visitor.fold_macro(_i.mac), - semi_token: (_i.semi_token).map(|it| Token ! [ ; ](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(feature = "full")] -pub fn fold_item_macro2<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemMacro2) -> ItemMacro2 { - ItemMacro2 { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - macro_token: Token![macro](tokens_helper(_visitor, &_i.macro_token.span)), - ident: _visitor.fold_ident(_i.ident), - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - args: _i.args, - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - body: _i.body, - } -} -#[cfg(feature = "full")] -pub fn fold_item_mod<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemMod) -> ItemMod { - ItemMod { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - mod_token: Token![mod](tokens_helper(_visitor, &_i.mod_token.span)), - ident: _visitor.fold_ident(_i.ident), - content: (_i.content).map(|it| { - ( - Brace(tokens_helper(_visitor, &(it).0.span)), - FoldHelper::lift((it).1, |it| _visitor.fold_item(it)), - ) - }), - semi: (_i.semi).map(|it| Token ! [ ; ](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(feature = "full")] -pub fn fold_item_static<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemStatic) -> ItemStatic { - ItemStatic { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - static_token: Token![static](tokens_helper(_visitor, &_i.static_token.span)), - mutability: (_i.mutability).map(|it| Token![mut](tokens_helper(_visitor, &it.span))), - ident: _visitor.fold_ident(_i.ident), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - ty: Box::new(_visitor.fold_type(*_i.ty)), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - expr: Box::new(_visitor.fold_expr(*_i.expr)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_struct<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemStruct) -> ItemStruct { - ItemStruct { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - struct_token: Token![struct](tokens_helper(_visitor, &_i.struct_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - fields: _visitor.fold_fields(_i.fields), - semi_token: (_i.semi_token).map(|it| Token ! [ ; ](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(feature = "full")] -pub fn fold_item_trait<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemTrait) -> ItemTrait { - ItemTrait { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - unsafety: (_i.unsafety).map(|it| Token![unsafe](tokens_helper(_visitor, &it.span))), - auto_token: (_i.auto_token).map(|it| Token![auto](tokens_helper(_visitor, &it.span))), - trait_token: Token![trait](tokens_helper(_visitor, &_i.trait_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - colon_token: (_i.colon_token).map(|it| Token ! [ : ](tokens_helper(_visitor, &it.spans))), - supertraits: FoldHelper::lift(_i.supertraits, |it| _visitor.fold_type_param_bound(it)), - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - items: FoldHelper::lift(_i.items, |it| _visitor.fold_trait_item(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_trait_alias<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ItemTraitAlias, -) -> ItemTraitAlias { - ItemTraitAlias { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - trait_token: Token![trait](tokens_helper(_visitor, &_i.trait_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_type_param_bound(it)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_type<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemType) -> ItemType { - ItemType { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - type_token: Token![type](tokens_helper(_visitor, &_i.type_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - ty: Box::new(_visitor.fold_type(*_i.ty)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_union<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemUnion) -> ItemUnion { - ItemUnion { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - union_token: Token![union](tokens_helper(_visitor, &_i.union_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - fields: _visitor.fold_fields_named(_i.fields), - } -} -#[cfg(feature = "full")] -pub fn fold_item_use<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemUse) -> ItemUse { - ItemUse { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - vis: _visitor.fold_visibility(_i.vis), - use_token: Token![use](tokens_helper(_visitor, &_i.use_token.span)), - leading_colon: (_i.leading_colon) - .map(|it| Token ! [ :: ](tokens_helper(_visitor, &it.spans))), - tree: _visitor.fold_use_tree(_i.tree), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_item_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemVerbatim) -> ItemVerbatim { - ItemVerbatim { tts: _i.tts } -} -#[cfg(feature = "full")] -pub fn fold_label<V: Fold + ?Sized>(_visitor: &mut V, _i: Label) -> Label { - Label { - name: _visitor.fold_lifetime(_i.name), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - } -} -pub fn fold_lifetime<V: Fold + ?Sized>(_visitor: &mut V, _i: Lifetime) -> Lifetime { - Lifetime { - apostrophe: _visitor.fold_span(_i.apostrophe), - ident: _visitor.fold_ident(_i.ident), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lifetime_def<V: Fold + ?Sized>(_visitor: &mut V, _i: LifetimeDef) -> LifetimeDef { - LifetimeDef { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - lifetime: _visitor.fold_lifetime(_i.lifetime), - colon_token: (_i.colon_token).map(|it| Token ! [ : ](tokens_helper(_visitor, &it.spans))), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_lifetime(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lit<V: Fold + ?Sized>(_visitor: &mut V, _i: Lit) -> Lit { - match _i { - Lit::Str(_binding_0) => Lit::Str(_visitor.fold_lit_str(_binding_0)), - Lit::ByteStr(_binding_0) => Lit::ByteStr(_visitor.fold_lit_byte_str(_binding_0)), - Lit::Byte(_binding_0) => Lit::Byte(_visitor.fold_lit_byte(_binding_0)), - Lit::Char(_binding_0) => Lit::Char(_visitor.fold_lit_char(_binding_0)), - Lit::Int(_binding_0) => Lit::Int(_visitor.fold_lit_int(_binding_0)), - Lit::Float(_binding_0) => Lit::Float(_visitor.fold_lit_float(_binding_0)), - Lit::Bool(_binding_0) => Lit::Bool(_visitor.fold_lit_bool(_binding_0)), - Lit::Verbatim(_binding_0) => Lit::Verbatim(_visitor.fold_lit_verbatim(_binding_0)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lit_bool<V: Fold + ?Sized>(_visitor: &mut V, _i: LitBool) -> LitBool { - LitBool { - value: _i.value, - span: _visitor.fold_span(_i.span), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lit_byte<V: Fold + ?Sized>(_visitor: &mut V, _i: LitByte) -> LitByte { - let span = _visitor.fold_span(_i.span()); - let mut _i = _i; - _i.set_span(span); - _i -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lit_byte_str<V: Fold + ?Sized>(_visitor: &mut V, _i: LitByteStr) -> LitByteStr { - let span = _visitor.fold_span(_i.span()); - let mut _i = _i; - _i.set_span(span); - _i -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lit_char<V: Fold + ?Sized>(_visitor: &mut V, _i: LitChar) -> LitChar { - let span = _visitor.fold_span(_i.span()); - let mut _i = _i; - _i.set_span(span); - _i -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lit_float<V: Fold + ?Sized>(_visitor: &mut V, _i: LitFloat) -> LitFloat { - let span = _visitor.fold_span(_i.span()); - let mut _i = _i; - _i.set_span(span); - _i -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lit_int<V: Fold + ?Sized>(_visitor: &mut V, _i: LitInt) -> LitInt { - let span = _visitor.fold_span(_i.span()); - let mut _i = _i; - _i.set_span(span); - _i -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lit_str<V: Fold + ?Sized>(_visitor: &mut V, _i: LitStr) -> LitStr { - let span = _visitor.fold_span(_i.span()); - let mut _i = _i; - _i.set_span(span); - _i -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_lit_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: LitVerbatim) -> LitVerbatim { - LitVerbatim { token: _i.token } -} -#[cfg(feature = "full")] -pub fn fold_local<V: Fold + ?Sized>(_visitor: &mut V, _i: Local) -> Local { - Local { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - let_token: Token![let](tokens_helper(_visitor, &_i.let_token.span)), - pats: FoldHelper::lift(_i.pats, |it| _visitor.fold_pat(it)), - ty: (_i.ty).map(|it| { - ( - Token ! [ : ](tokens_helper(_visitor, &(it).0.spans)), - Box::new(_visitor.fold_type(*(it).1)), - ) - }), - init: (_i.init).map(|it| { - ( - Token ! [ = ](tokens_helper(_visitor, &(it).0.spans)), - Box::new(_visitor.fold_expr(*(it).1)), - ) - }), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: Macro) -> Macro { - Macro { - path: _visitor.fold_path(_i.path), - bang_token: Token![!](tokens_helper(_visitor, &_i.bang_token.spans)), - delimiter: _visitor.fold_macro_delimiter(_i.delimiter), - tts: _i.tts, - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_macro_delimiter<V: Fold + ?Sized>( - _visitor: &mut V, - _i: MacroDelimiter, -) -> MacroDelimiter { - match _i { - MacroDelimiter::Paren(_binding_0) => { - MacroDelimiter::Paren(Paren(tokens_helper(_visitor, &_binding_0.span))) - } - MacroDelimiter::Brace(_binding_0) => { - MacroDelimiter::Brace(Brace(tokens_helper(_visitor, &_binding_0.span))) - } - MacroDelimiter::Bracket(_binding_0) => { - MacroDelimiter::Bracket(Bracket(tokens_helper(_visitor, &_binding_0.span))) - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_member<V: Fold + ?Sized>(_visitor: &mut V, _i: Member) -> Member { - match _i { - Member::Named(_binding_0) => Member::Named(_visitor.fold_ident(_binding_0)), - Member::Unnamed(_binding_0) => Member::Unnamed(_visitor.fold_index(_binding_0)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_meta<V: Fold + ?Sized>(_visitor: &mut V, _i: Meta) -> Meta { - match _i { - Meta::Word(_binding_0) => Meta::Word(_visitor.fold_ident(_binding_0)), - Meta::List(_binding_0) => Meta::List(_visitor.fold_meta_list(_binding_0)), - Meta::NameValue(_binding_0) => Meta::NameValue(_visitor.fold_meta_name_value(_binding_0)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_meta_list<V: Fold + ?Sized>(_visitor: &mut V, _i: MetaList) -> MetaList { - MetaList { - ident: _visitor.fold_ident(_i.ident), - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - nested: FoldHelper::lift(_i.nested, |it| _visitor.fold_nested_meta(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_meta_name_value<V: Fold + ?Sized>( - _visitor: &mut V, - _i: MetaNameValue, -) -> MetaNameValue { - MetaNameValue { - ident: _visitor.fold_ident(_i.ident), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - lit: _visitor.fold_lit(_i.lit), - } -} -#[cfg(feature = "full")] -pub fn fold_method_sig<V: Fold + ?Sized>(_visitor: &mut V, _i: MethodSig) -> MethodSig { - MethodSig { - constness: (_i.constness).map(|it| Token![const](tokens_helper(_visitor, &it.span))), - asyncness: (_i.asyncness).map(|it| Token![async](tokens_helper(_visitor, &it.span))), - unsafety: (_i.unsafety).map(|it| Token![unsafe](tokens_helper(_visitor, &it.span))), - abi: (_i.abi).map(|it| _visitor.fold_abi(it)), - ident: _visitor.fold_ident(_i.ident), - decl: _visitor.fold_fn_decl(_i.decl), - } -} -#[cfg(feature = "full")] -pub fn fold_method_turbofish<V: Fold + ?Sized>( - _visitor: &mut V, - _i: MethodTurbofish, -) -> MethodTurbofish { - MethodTurbofish { - colon2_token: Token ! [ :: ](tokens_helper(_visitor, &_i.colon2_token.spans)), - lt_token: Token ! [ < ](tokens_helper(_visitor, &_i.lt_token.spans)), - args: FoldHelper::lift(_i.args, |it| _visitor.fold_generic_method_argument(it)), - gt_token: Token ! [ > ](tokens_helper(_visitor, &_i.gt_token.spans)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_nested_meta<V: Fold + ?Sized>(_visitor: &mut V, _i: NestedMeta) -> NestedMeta { - match _i { - NestedMeta::Meta(_binding_0) => NestedMeta::Meta(_visitor.fold_meta(_binding_0)), - NestedMeta::Literal(_binding_0) => NestedMeta::Literal(_visitor.fold_lit(_binding_0)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_parenthesized_generic_arguments<V: Fold + ?Sized>( - _visitor: &mut V, - _i: ParenthesizedGenericArguments, -) -> ParenthesizedGenericArguments { - ParenthesizedGenericArguments { - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - inputs: FoldHelper::lift(_i.inputs, |it| _visitor.fold_type(it)), - output: _visitor.fold_return_type(_i.output), - } -} -#[cfg(feature = "full")] -pub fn fold_pat<V: Fold + ?Sized>(_visitor: &mut V, _i: Pat) -> Pat { - match _i { - Pat::Wild(_binding_0) => Pat::Wild(_visitor.fold_pat_wild(_binding_0)), - Pat::Ident(_binding_0) => Pat::Ident(_visitor.fold_pat_ident(_binding_0)), - Pat::Struct(_binding_0) => Pat::Struct(_visitor.fold_pat_struct(_binding_0)), - Pat::TupleStruct(_binding_0) => { - Pat::TupleStruct(_visitor.fold_pat_tuple_struct(_binding_0)) - } - Pat::Path(_binding_0) => Pat::Path(_visitor.fold_pat_path(_binding_0)), - Pat::Tuple(_binding_0) => Pat::Tuple(_visitor.fold_pat_tuple(_binding_0)), - Pat::Box(_binding_0) => Pat::Box(_visitor.fold_pat_box(_binding_0)), - Pat::Ref(_binding_0) => Pat::Ref(_visitor.fold_pat_ref(_binding_0)), - Pat::Lit(_binding_0) => Pat::Lit(_visitor.fold_pat_lit(_binding_0)), - Pat::Range(_binding_0) => Pat::Range(_visitor.fold_pat_range(_binding_0)), - Pat::Slice(_binding_0) => Pat::Slice(_visitor.fold_pat_slice(_binding_0)), - Pat::Macro(_binding_0) => Pat::Macro(_visitor.fold_pat_macro(_binding_0)), - Pat::Verbatim(_binding_0) => Pat::Verbatim(_visitor.fold_pat_verbatim(_binding_0)), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_box<V: Fold + ?Sized>(_visitor: &mut V, _i: PatBox) -> PatBox { - PatBox { - box_token: Token![box](tokens_helper(_visitor, &_i.box_token.span)), - pat: Box::new(_visitor.fold_pat(*_i.pat)), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_ident<V: Fold + ?Sized>(_visitor: &mut V, _i: PatIdent) -> PatIdent { - PatIdent { - by_ref: (_i.by_ref).map(|it| Token![ref](tokens_helper(_visitor, &it.span))), - mutability: (_i.mutability).map(|it| Token![mut](tokens_helper(_visitor, &it.span))), - ident: _visitor.fold_ident(_i.ident), - subpat: (_i.subpat).map(|it| { - ( - Token ! [ @ ](tokens_helper(_visitor, &(it).0.spans)), - Box::new(_visitor.fold_pat(*(it).1)), - ) - }), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_lit<V: Fold + ?Sized>(_visitor: &mut V, _i: PatLit) -> PatLit { - PatLit { - expr: Box::new(_visitor.fold_expr(*_i.expr)), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: PatMacro) -> PatMacro { - PatMacro { - mac: _visitor.fold_macro(_i.mac), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_path<V: Fold + ?Sized>(_visitor: &mut V, _i: PatPath) -> PatPath { - PatPath { - qself: (_i.qself).map(|it| _visitor.fold_qself(it)), - path: _visitor.fold_path(_i.path), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_range<V: Fold + ?Sized>(_visitor: &mut V, _i: PatRange) -> PatRange { - PatRange { - lo: Box::new(_visitor.fold_expr(*_i.lo)), - limits: _visitor.fold_range_limits(_i.limits), - hi: Box::new(_visitor.fold_expr(*_i.hi)), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_ref<V: Fold + ?Sized>(_visitor: &mut V, _i: PatRef) -> PatRef { - PatRef { - and_token: Token ! [ & ](tokens_helper(_visitor, &_i.and_token.spans)), - mutability: (_i.mutability).map(|it| Token![mut](tokens_helper(_visitor, &it.span))), - pat: Box::new(_visitor.fold_pat(*_i.pat)), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_slice<V: Fold + ?Sized>(_visitor: &mut V, _i: PatSlice) -> PatSlice { - PatSlice { - bracket_token: Bracket(tokens_helper(_visitor, &_i.bracket_token.span)), - front: FoldHelper::lift(_i.front, |it| _visitor.fold_pat(it)), - middle: (_i.middle).map(|it| Box::new(_visitor.fold_pat(*it))), - dot2_token: (_i.dot2_token).map(|it| Token![..](tokens_helper(_visitor, &it.spans))), - comma_token: (_i.comma_token).map(|it| Token ! [ , ](tokens_helper(_visitor, &it.spans))), - back: FoldHelper::lift(_i.back, |it| _visitor.fold_pat(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_struct<V: Fold + ?Sized>(_visitor: &mut V, _i: PatStruct) -> PatStruct { - PatStruct { - path: _visitor.fold_path(_i.path), - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - fields: FoldHelper::lift(_i.fields, |it| _visitor.fold_field_pat(it)), - dot2_token: (_i.dot2_token).map(|it| Token![..](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_tuple<V: Fold + ?Sized>(_visitor: &mut V, _i: PatTuple) -> PatTuple { - PatTuple { - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - front: FoldHelper::lift(_i.front, |it| _visitor.fold_pat(it)), - dot2_token: (_i.dot2_token).map(|it| Token![..](tokens_helper(_visitor, &it.spans))), - comma_token: (_i.comma_token).map(|it| Token ! [ , ](tokens_helper(_visitor, &it.spans))), - back: FoldHelper::lift(_i.back, |it| _visitor.fold_pat(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_tuple_struct<V: Fold + ?Sized>( - _visitor: &mut V, - _i: PatTupleStruct, -) -> PatTupleStruct { - PatTupleStruct { - path: _visitor.fold_path(_i.path), - pat: _visitor.fold_pat_tuple(_i.pat), - } -} -#[cfg(feature = "full")] -pub fn fold_pat_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: PatVerbatim) -> PatVerbatim { - PatVerbatim { tts: _i.tts } -} -#[cfg(feature = "full")] -pub fn fold_pat_wild<V: Fold + ?Sized>(_visitor: &mut V, _i: PatWild) -> PatWild { - PatWild { - underscore_token: Token![_](tokens_helper(_visitor, &_i.underscore_token.spans)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_path<V: Fold + ?Sized>(_visitor: &mut V, _i: Path) -> Path { - Path { - leading_colon: (_i.leading_colon) - .map(|it| Token ! [ :: ](tokens_helper(_visitor, &it.spans))), - segments: FoldHelper::lift(_i.segments, |it| _visitor.fold_path_segment(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_path_arguments<V: Fold + ?Sized>(_visitor: &mut V, _i: PathArguments) -> PathArguments { - match _i { - PathArguments::None => PathArguments::None, - PathArguments::AngleBracketed(_binding_0) => PathArguments::AngleBracketed( - _visitor.fold_angle_bracketed_generic_arguments(_binding_0), - ), - PathArguments::Parenthesized(_binding_0) => { - PathArguments::Parenthesized(_visitor.fold_parenthesized_generic_arguments(_binding_0)) - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_path_segment<V: Fold + ?Sized>(_visitor: &mut V, _i: PathSegment) -> PathSegment { - PathSegment { - ident: _visitor.fold_ident(_i.ident), - arguments: _visitor.fold_path_arguments(_i.arguments), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_predicate_eq<V: Fold + ?Sized>(_visitor: &mut V, _i: PredicateEq) -> PredicateEq { - PredicateEq { - lhs_ty: _visitor.fold_type(_i.lhs_ty), - eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)), - rhs_ty: _visitor.fold_type(_i.rhs_ty), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_predicate_lifetime<V: Fold + ?Sized>( - _visitor: &mut V, - _i: PredicateLifetime, -) -> PredicateLifetime { - PredicateLifetime { - lifetime: _visitor.fold_lifetime(_i.lifetime), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_lifetime(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_predicate_type<V: Fold + ?Sized>(_visitor: &mut V, _i: PredicateType) -> PredicateType { - PredicateType { - lifetimes: (_i.lifetimes).map(|it| _visitor.fold_bound_lifetimes(it)), - bounded_ty: _visitor.fold_type(_i.bounded_ty), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_type_param_bound(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_qself<V: Fold + ?Sized>(_visitor: &mut V, _i: QSelf) -> QSelf { - QSelf { - lt_token: Token ! [ < ](tokens_helper(_visitor, &_i.lt_token.spans)), - ty: Box::new(_visitor.fold_type(*_i.ty)), - position: _i.position, - as_token: (_i.as_token).map(|it| Token![as](tokens_helper(_visitor, &it.span))), - gt_token: Token ! [ > ](tokens_helper(_visitor, &_i.gt_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_range_limits<V: Fold + ?Sized>(_visitor: &mut V, _i: RangeLimits) -> RangeLimits { - match _i { - RangeLimits::HalfOpen(_binding_0) => { - RangeLimits::HalfOpen(Token![..](tokens_helper(_visitor, &_binding_0.spans))) - } - RangeLimits::Closed(_binding_0) => { - RangeLimits::Closed(Token ! [ ..= ](tokens_helper(_visitor, &_binding_0.spans))) - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_return_type<V: Fold + ?Sized>(_visitor: &mut V, _i: ReturnType) -> ReturnType { - match _i { - ReturnType::Default => ReturnType::Default, - ReturnType::Type(_binding_0, _binding_1) => ReturnType::Type( - Token ! [ -> ](tokens_helper(_visitor, &_binding_0.spans)), - Box::new(_visitor.fold_type(*_binding_1)), - ), - } -} -#[cfg(feature = "full")] -pub fn fold_stmt<V: Fold + ?Sized>(_visitor: &mut V, _i: Stmt) -> Stmt { - match _i { - Stmt::Local(_binding_0) => Stmt::Local(_visitor.fold_local(_binding_0)), - Stmt::Item(_binding_0) => Stmt::Item(_visitor.fold_item(_binding_0)), - Stmt::Expr(_binding_0) => Stmt::Expr(_visitor.fold_expr(_binding_0)), - Stmt::Semi(_binding_0, _binding_1) => Stmt::Semi( - _visitor.fold_expr(_binding_0), - Token ! [ ; ](tokens_helper(_visitor, &_binding_1.spans)), - ), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_trait_bound<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitBound) -> TraitBound { - TraitBound { - paren_token: (_i.paren_token).map(|it| Paren(tokens_helper(_visitor, &it.span))), - modifier: _visitor.fold_trait_bound_modifier(_i.modifier), - lifetimes: (_i.lifetimes).map(|it| _visitor.fold_bound_lifetimes(it)), - path: _visitor.fold_path(_i.path), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_trait_bound_modifier<V: Fold + ?Sized>( - _visitor: &mut V, - _i: TraitBoundModifier, -) -> TraitBoundModifier { - match _i { - TraitBoundModifier::None => TraitBoundModifier::None, - TraitBoundModifier::Maybe(_binding_0) => { - TraitBoundModifier::Maybe(Token ! [ ? ](tokens_helper(_visitor, &_binding_0.spans))) - } - } -} -#[cfg(feature = "full")] -pub fn fold_trait_item<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitItem) -> TraitItem { - match _i { - TraitItem::Const(_binding_0) => { - TraitItem::Const(_visitor.fold_trait_item_const(_binding_0)) - } - TraitItem::Method(_binding_0) => { - TraitItem::Method(_visitor.fold_trait_item_method(_binding_0)) - } - TraitItem::Type(_binding_0) => TraitItem::Type(_visitor.fold_trait_item_type(_binding_0)), - TraitItem::Macro(_binding_0) => { - TraitItem::Macro(_visitor.fold_trait_item_macro(_binding_0)) - } - TraitItem::Verbatim(_binding_0) => { - TraitItem::Verbatim(_visitor.fold_trait_item_verbatim(_binding_0)) - } - } -} -#[cfg(feature = "full")] -pub fn fold_trait_item_const<V: Fold + ?Sized>( - _visitor: &mut V, - _i: TraitItemConst, -) -> TraitItemConst { - TraitItemConst { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - const_token: Token![const](tokens_helper(_visitor, &_i.const_token.span)), - ident: _visitor.fold_ident(_i.ident), - colon_token: Token ! [ : ](tokens_helper(_visitor, &_i.colon_token.spans)), - ty: _visitor.fold_type(_i.ty), - default: (_i.default).map(|it| { - ( - Token ! [ = ](tokens_helper(_visitor, &(it).0.spans)), - _visitor.fold_expr((it).1), - ) - }), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_trait_item_macro<V: Fold + ?Sized>( - _visitor: &mut V, - _i: TraitItemMacro, -) -> TraitItemMacro { - TraitItemMacro { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - mac: _visitor.fold_macro(_i.mac), - semi_token: (_i.semi_token).map(|it| Token ! [ ; ](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(feature = "full")] -pub fn fold_trait_item_method<V: Fold + ?Sized>( - _visitor: &mut V, - _i: TraitItemMethod, -) -> TraitItemMethod { - TraitItemMethod { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - sig: _visitor.fold_method_sig(_i.sig), - default: (_i.default).map(|it| _visitor.fold_block(it)), - semi_token: (_i.semi_token).map(|it| Token ! [ ; ](tokens_helper(_visitor, &it.spans))), - } -} -#[cfg(feature = "full")] -pub fn fold_trait_item_type<V: Fold + ?Sized>( - _visitor: &mut V, - _i: TraitItemType, -) -> TraitItemType { - TraitItemType { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - type_token: Token![type](tokens_helper(_visitor, &_i.type_token.span)), - ident: _visitor.fold_ident(_i.ident), - generics: _visitor.fold_generics(_i.generics), - colon_token: (_i.colon_token).map(|it| Token ! [ : ](tokens_helper(_visitor, &it.spans))), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_type_param_bound(it)), - default: (_i.default).map(|it| { - ( - Token ! [ = ](tokens_helper(_visitor, &(it).0.spans)), - _visitor.fold_type((it).1), - ) - }), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_trait_item_verbatim<V: Fold + ?Sized>( - _visitor: &mut V, - _i: TraitItemVerbatim, -) -> TraitItemVerbatim { - TraitItemVerbatim { tts: _i.tts } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type<V: Fold + ?Sized>(_visitor: &mut V, _i: Type) -> Type { - match _i { - Type::Slice(_binding_0) => Type::Slice(_visitor.fold_type_slice(_binding_0)), - Type::Array(_binding_0) => Type::Array(_visitor.fold_type_array(_binding_0)), - Type::Ptr(_binding_0) => Type::Ptr(_visitor.fold_type_ptr(_binding_0)), - Type::Reference(_binding_0) => Type::Reference(_visitor.fold_type_reference(_binding_0)), - Type::BareFn(_binding_0) => Type::BareFn(_visitor.fold_type_bare_fn(_binding_0)), - Type::Never(_binding_0) => Type::Never(_visitor.fold_type_never(_binding_0)), - Type::Tuple(_binding_0) => Type::Tuple(_visitor.fold_type_tuple(_binding_0)), - Type::Path(_binding_0) => Type::Path(_visitor.fold_type_path(_binding_0)), - Type::TraitObject(_binding_0) => { - Type::TraitObject(_visitor.fold_type_trait_object(_binding_0)) - } - Type::ImplTrait(_binding_0) => Type::ImplTrait(_visitor.fold_type_impl_trait(_binding_0)), - Type::Paren(_binding_0) => Type::Paren(_visitor.fold_type_paren(_binding_0)), - Type::Group(_binding_0) => Type::Group(_visitor.fold_type_group(_binding_0)), - Type::Infer(_binding_0) => Type::Infer(_visitor.fold_type_infer(_binding_0)), - Type::Macro(_binding_0) => Type::Macro(_visitor.fold_type_macro(_binding_0)), - Type::Verbatim(_binding_0) => Type::Verbatim(_visitor.fold_type_verbatim(_binding_0)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_array<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeArray) -> TypeArray { - TypeArray { - bracket_token: Bracket(tokens_helper(_visitor, &_i.bracket_token.span)), - elem: Box::new(_visitor.fold_type(*_i.elem)), - semi_token: Token ! [ ; ](tokens_helper(_visitor, &_i.semi_token.spans)), - len: _visitor.fold_expr(_i.len), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_bare_fn<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeBareFn) -> TypeBareFn { - TypeBareFn { - lifetimes: (_i.lifetimes).map(|it| _visitor.fold_bound_lifetimes(it)), - unsafety: (_i.unsafety).map(|it| Token![unsafe](tokens_helper(_visitor, &it.span))), - abi: (_i.abi).map(|it| _visitor.fold_abi(it)), - fn_token: Token![fn](tokens_helper(_visitor, &_i.fn_token.span)), - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - inputs: FoldHelper::lift(_i.inputs, |it| _visitor.fold_bare_fn_arg(it)), - variadic: (_i.variadic).map(|it| Token ! [ ... ](tokens_helper(_visitor, &it.spans))), - output: _visitor.fold_return_type(_i.output), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_group<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeGroup) -> TypeGroup { - TypeGroup { - group_token: Group(tokens_helper(_visitor, &_i.group_token.span)), - elem: Box::new(_visitor.fold_type(*_i.elem)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_impl_trait<V: Fold + ?Sized>( - _visitor: &mut V, - _i: TypeImplTrait, -) -> TypeImplTrait { - TypeImplTrait { - impl_token: Token![impl](tokens_helper(_visitor, &_i.impl_token.span)), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_type_param_bound(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_infer<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeInfer) -> TypeInfer { - TypeInfer { - underscore_token: Token![_](tokens_helper(_visitor, &_i.underscore_token.spans)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeMacro) -> TypeMacro { - TypeMacro { - mac: _visitor.fold_macro(_i.mac), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_never<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeNever) -> TypeNever { - TypeNever { - bang_token: Token![!](tokens_helper(_visitor, &_i.bang_token.spans)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_param<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeParam) -> TypeParam { - TypeParam { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - ident: _visitor.fold_ident(_i.ident), - colon_token: (_i.colon_token).map(|it| Token ! [ : ](tokens_helper(_visitor, &it.spans))), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_type_param_bound(it)), - eq_token: (_i.eq_token).map(|it| Token ! [ = ](tokens_helper(_visitor, &it.spans))), - default: (_i.default).map(|it| _visitor.fold_type(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_param_bound<V: Fold + ?Sized>( - _visitor: &mut V, - _i: TypeParamBound, -) -> TypeParamBound { - match _i { - TypeParamBound::Trait(_binding_0) => { - TypeParamBound::Trait(_visitor.fold_trait_bound(_binding_0)) - } - TypeParamBound::Lifetime(_binding_0) => { - TypeParamBound::Lifetime(_visitor.fold_lifetime(_binding_0)) - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_paren<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeParen) -> TypeParen { - TypeParen { - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - elem: Box::new(_visitor.fold_type(*_i.elem)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_path<V: Fold + ?Sized>(_visitor: &mut V, _i: TypePath) -> TypePath { - TypePath { - qself: (_i.qself).map(|it| _visitor.fold_qself(it)), - path: _visitor.fold_path(_i.path), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_ptr<V: Fold + ?Sized>(_visitor: &mut V, _i: TypePtr) -> TypePtr { - TypePtr { - star_token: Token ! [ * ](tokens_helper(_visitor, &_i.star_token.spans)), - const_token: (_i.const_token).map(|it| Token![const](tokens_helper(_visitor, &it.span))), - mutability: (_i.mutability).map(|it| Token![mut](tokens_helper(_visitor, &it.span))), - elem: Box::new(_visitor.fold_type(*_i.elem)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_reference<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeReference) -> TypeReference { - TypeReference { - and_token: Token ! [ & ](tokens_helper(_visitor, &_i.and_token.spans)), - lifetime: (_i.lifetime).map(|it| _visitor.fold_lifetime(it)), - mutability: (_i.mutability).map(|it| Token![mut](tokens_helper(_visitor, &it.span))), - elem: Box::new(_visitor.fold_type(*_i.elem)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_slice<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeSlice) -> TypeSlice { - TypeSlice { - bracket_token: Bracket(tokens_helper(_visitor, &_i.bracket_token.span)), - elem: Box::new(_visitor.fold_type(*_i.elem)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_trait_object<V: Fold + ?Sized>( - _visitor: &mut V, - _i: TypeTraitObject, -) -> TypeTraitObject { - TypeTraitObject { - dyn_token: (_i.dyn_token).map(|it| Token![dyn](tokens_helper(_visitor, &it.span))), - bounds: FoldHelper::lift(_i.bounds, |it| _visitor.fold_type_param_bound(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_tuple<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeTuple) -> TypeTuple { - TypeTuple { - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - elems: FoldHelper::lift(_i.elems, |it| _visitor.fold_type(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_type_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeVerbatim) -> TypeVerbatim { - TypeVerbatim { tts: _i.tts } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_un_op<V: Fold + ?Sized>(_visitor: &mut V, _i: UnOp) -> UnOp { - match _i { - UnOp::Deref(_binding_0) => { - UnOp::Deref(Token ! [ * ](tokens_helper(_visitor, &_binding_0.spans))) - } - UnOp::Not(_binding_0) => UnOp::Not(Token![!](tokens_helper(_visitor, &_binding_0.spans))), - UnOp::Neg(_binding_0) => { - UnOp::Neg(Token ! [ - ](tokens_helper(_visitor, &_binding_0.spans))) - } - } -} -#[cfg(feature = "full")] -pub fn fold_use_glob<V: Fold + ?Sized>(_visitor: &mut V, _i: UseGlob) -> UseGlob { - UseGlob { - star_token: Token ! [ * ](tokens_helper(_visitor, &_i.star_token.spans)), - } -} -#[cfg(feature = "full")] -pub fn fold_use_group<V: Fold + ?Sized>(_visitor: &mut V, _i: UseGroup) -> UseGroup { - UseGroup { - brace_token: Brace(tokens_helper(_visitor, &_i.brace_token.span)), - items: FoldHelper::lift(_i.items, |it| _visitor.fold_use_tree(it)), - } -} -#[cfg(feature = "full")] -pub fn fold_use_name<V: Fold + ?Sized>(_visitor: &mut V, _i: UseName) -> UseName { - UseName { - ident: _visitor.fold_ident(_i.ident), - } -} -#[cfg(feature = "full")] -pub fn fold_use_path<V: Fold + ?Sized>(_visitor: &mut V, _i: UsePath) -> UsePath { - UsePath { - ident: _visitor.fold_ident(_i.ident), - colon2_token: Token ! [ :: ](tokens_helper(_visitor, &_i.colon2_token.spans)), - tree: Box::new(_visitor.fold_use_tree(*_i.tree)), - } -} -#[cfg(feature = "full")] -pub fn fold_use_rename<V: Fold + ?Sized>(_visitor: &mut V, _i: UseRename) -> UseRename { - UseRename { - ident: _visitor.fold_ident(_i.ident), - as_token: Token![as](tokens_helper(_visitor, &_i.as_token.span)), - rename: _visitor.fold_ident(_i.rename), - } -} -#[cfg(feature = "full")] -pub fn fold_use_tree<V: Fold + ?Sized>(_visitor: &mut V, _i: UseTree) -> UseTree { - match _i { - UseTree::Path(_binding_0) => UseTree::Path(_visitor.fold_use_path(_binding_0)), - UseTree::Name(_binding_0) => UseTree::Name(_visitor.fold_use_name(_binding_0)), - UseTree::Rename(_binding_0) => UseTree::Rename(_visitor.fold_use_rename(_binding_0)), - UseTree::Glob(_binding_0) => UseTree::Glob(_visitor.fold_use_glob(_binding_0)), - UseTree::Group(_binding_0) => UseTree::Group(_visitor.fold_use_group(_binding_0)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_variant<V: Fold + ?Sized>(_visitor: &mut V, _i: Variant) -> Variant { - Variant { - attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)), - ident: _visitor.fold_ident(_i.ident), - fields: _visitor.fold_fields(_i.fields), - discriminant: (_i.discriminant).map(|it| { - ( - Token ! [ = ](tokens_helper(_visitor, &(it).0.spans)), - _visitor.fold_expr((it).1), - ) - }), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_vis_crate<V: Fold + ?Sized>(_visitor: &mut V, _i: VisCrate) -> VisCrate { - VisCrate { - crate_token: Token![crate](tokens_helper(_visitor, &_i.crate_token.span)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_vis_public<V: Fold + ?Sized>(_visitor: &mut V, _i: VisPublic) -> VisPublic { - VisPublic { - pub_token: Token![pub](tokens_helper(_visitor, &_i.pub_token.span)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_vis_restricted<V: Fold + ?Sized>(_visitor: &mut V, _i: VisRestricted) -> VisRestricted { - VisRestricted { - pub_token: Token![pub](tokens_helper(_visitor, &_i.pub_token.span)), - paren_token: Paren(tokens_helper(_visitor, &_i.paren_token.span)), - in_token: (_i.in_token).map(|it| Token![in](tokens_helper(_visitor, &it.span))), - path: Box::new(_visitor.fold_path(*_i.path)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_visibility<V: Fold + ?Sized>(_visitor: &mut V, _i: Visibility) -> Visibility { - match _i { - Visibility::Public(_binding_0) => Visibility::Public(_visitor.fold_vis_public(_binding_0)), - Visibility::Crate(_binding_0) => Visibility::Crate(_visitor.fold_vis_crate(_binding_0)), - Visibility::Restricted(_binding_0) => { - Visibility::Restricted(_visitor.fold_vis_restricted(_binding_0)) - } - Visibility::Inherited => Visibility::Inherited, - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_where_clause<V: Fold + ?Sized>(_visitor: &mut V, _i: WhereClause) -> WhereClause { - WhereClause { - where_token: Token![where](tokens_helper(_visitor, &_i.where_token.span)), - predicates: FoldHelper::lift(_i.predicates, |it| _visitor.fold_where_predicate(it)), - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn fold_where_predicate<V: Fold + ?Sized>( - _visitor: &mut V, - _i: WherePredicate, -) -> WherePredicate { - match _i { - WherePredicate::Type(_binding_0) => { - WherePredicate::Type(_visitor.fold_predicate_type(_binding_0)) - } - WherePredicate::Lifetime(_binding_0) => { - WherePredicate::Lifetime(_visitor.fold_predicate_lifetime(_binding_0)) - } - WherePredicate::Eq(_binding_0) => { - WherePredicate::Eq(_visitor.fold_predicate_eq(_binding_0)) - } - } -} -pub fn fold_span<V: Fold + ?Sized>(_visitor: &mut V, _i: Span) -> Span { - _i -} -pub fn fold_ident<V: Fold + ?Sized>(_visitor: &mut V, _i: Ident) -> Ident { - let mut _i = _i; - let span = _visitor.fold_span(_i.span()); - _i.set_span(span); - _i -} diff --git a/0.15.42/src/gen/visit.rs b/0.15.42/src/gen/visit.rs deleted file mode 100644 index 3c551ff8..00000000 --- a/0.15.42/src/gen/visit.rs +++ /dev/null @@ -1,3372 +0,0 @@ -// This file is @generated by syn-internal-codegen. -// It is not intended for manual editing. - -#![cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))] -#[cfg(any(feature = "full", feature = "derive"))] -use gen::helper::visit::*; -use proc_macro2::Span; -#[cfg(any(feature = "full", feature = "derive"))] -use punctuated::Punctuated; -use *; -#[cfg(feature = "full")] -macro_rules! full { - ($e:expr) => { - $e - }; -} -#[cfg(all(feature = "derive", not(feature = "full")))] -macro_rules! full { - ($e:expr) => { - unreachable!() - }; -} -#[cfg(any(feature = "full", feature = "derive"))] -macro_rules! skip { - ($($tt:tt)*) => {}; -} -/// Syntax tree traversal to walk a shared borrow of a syntax tree. -/// -/// See the [module documentation] for details. -/// -/// [module documentation]: self -/// -/// *This trait is available if Syn is built with the `"visit"` feature.* -pub trait Visit<'ast> { - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_abi(&mut self, i: &'ast Abi) { - visit_abi(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_angle_bracketed_generic_arguments(&mut self, i: &'ast AngleBracketedGenericArguments) { - visit_angle_bracketed_generic_arguments(self, i) - } - #[cfg(feature = "full")] - fn visit_arg_captured(&mut self, i: &'ast ArgCaptured) { - visit_arg_captured(self, i) - } - #[cfg(feature = "full")] - fn visit_arg_self(&mut self, i: &'ast ArgSelf) { - visit_arg_self(self, i) - } - #[cfg(feature = "full")] - fn visit_arg_self_ref(&mut self, i: &'ast ArgSelfRef) { - visit_arg_self_ref(self, i) - } - #[cfg(feature = "full")] - fn visit_arm(&mut self, i: &'ast Arm) { - visit_arm(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_attr_style(&mut self, i: &'ast AttrStyle) { - visit_attr_style(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_attribute(&mut self, i: &'ast Attribute) { - visit_attribute(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_bare_fn_arg(&mut self, i: &'ast BareFnArg) { - visit_bare_fn_arg(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_bare_fn_arg_name(&mut self, i: &'ast BareFnArgName) { - visit_bare_fn_arg_name(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_bin_op(&mut self, i: &'ast BinOp) { - visit_bin_op(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_binding(&mut self, i: &'ast Binding) { - visit_binding(self, i) - } - #[cfg(feature = "full")] - fn visit_block(&mut self, i: &'ast Block) { - visit_block(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_bound_lifetimes(&mut self, i: &'ast BoundLifetimes) { - visit_bound_lifetimes(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_const_param(&mut self, i: &'ast ConstParam) { - visit_const_param(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_constraint(&mut self, i: &'ast Constraint) { - visit_constraint(self, i) - } - #[cfg(feature = "derive")] - fn visit_data(&mut self, i: &'ast Data) { - visit_data(self, i) - } - #[cfg(feature = "derive")] - fn visit_data_enum(&mut self, i: &'ast DataEnum) { - visit_data_enum(self, i) - } - #[cfg(feature = "derive")] - fn visit_data_struct(&mut self, i: &'ast DataStruct) { - visit_data_struct(self, i) - } - #[cfg(feature = "derive")] - fn visit_data_union(&mut self, i: &'ast DataUnion) { - visit_data_union(self, i) - } - #[cfg(feature = "derive")] - fn visit_derive_input(&mut self, i: &'ast DeriveInput) { - visit_derive_input(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr(&mut self, i: &'ast Expr) { - visit_expr(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_array(&mut self, i: &'ast ExprArray) { - visit_expr_array(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_assign(&mut self, i: &'ast ExprAssign) { - visit_expr_assign(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_assign_op(&mut self, i: &'ast ExprAssignOp) { - visit_expr_assign_op(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_async(&mut self, i: &'ast ExprAsync) { - visit_expr_async(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_binary(&mut self, i: &'ast ExprBinary) { - visit_expr_binary(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_block(&mut self, i: &'ast ExprBlock) { - visit_expr_block(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_box(&mut self, i: &'ast ExprBox) { - visit_expr_box(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_break(&mut self, i: &'ast ExprBreak) { - visit_expr_break(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_call(&mut self, i: &'ast ExprCall) { - visit_expr_call(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_cast(&mut self, i: &'ast ExprCast) { - visit_expr_cast(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_closure(&mut self, i: &'ast ExprClosure) { - visit_expr_closure(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_continue(&mut self, i: &'ast ExprContinue) { - visit_expr_continue(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_field(&mut self, i: &'ast ExprField) { - visit_expr_field(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_for_loop(&mut self, i: &'ast ExprForLoop) { - visit_expr_for_loop(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_group(&mut self, i: &'ast ExprGroup) { - visit_expr_group(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_if(&mut self, i: &'ast ExprIf) { - visit_expr_if(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_in_place(&mut self, i: &'ast ExprInPlace) { - visit_expr_in_place(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_index(&mut self, i: &'ast ExprIndex) { - visit_expr_index(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_let(&mut self, i: &'ast ExprLet) { - visit_expr_let(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_lit(&mut self, i: &'ast ExprLit) { - visit_expr_lit(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_loop(&mut self, i: &'ast ExprLoop) { - visit_expr_loop(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_macro(&mut self, i: &'ast ExprMacro) { - visit_expr_macro(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_match(&mut self, i: &'ast ExprMatch) { - visit_expr_match(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_method_call(&mut self, i: &'ast ExprMethodCall) { - visit_expr_method_call(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_paren(&mut self, i: &'ast ExprParen) { - visit_expr_paren(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_path(&mut self, i: &'ast ExprPath) { - visit_expr_path(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_range(&mut self, i: &'ast ExprRange) { - visit_expr_range(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_reference(&mut self, i: &'ast ExprReference) { - visit_expr_reference(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_repeat(&mut self, i: &'ast ExprRepeat) { - visit_expr_repeat(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_return(&mut self, i: &'ast ExprReturn) { - visit_expr_return(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_struct(&mut self, i: &'ast ExprStruct) { - visit_expr_struct(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_try(&mut self, i: &'ast ExprTry) { - visit_expr_try(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_try_block(&mut self, i: &'ast ExprTryBlock) { - visit_expr_try_block(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_tuple(&mut self, i: &'ast ExprTuple) { - visit_expr_tuple(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_type(&mut self, i: &'ast ExprType) { - visit_expr_type(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_unary(&mut self, i: &'ast ExprUnary) { - visit_expr_unary(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_unsafe(&mut self, i: &'ast ExprUnsafe) { - visit_expr_unsafe(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_verbatim(&mut self, i: &'ast ExprVerbatim) { - visit_expr_verbatim(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_while(&mut self, i: &'ast ExprWhile) { - visit_expr_while(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_yield(&mut self, i: &'ast ExprYield) { - visit_expr_yield(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_field(&mut self, i: &'ast Field) { - visit_field(self, i) - } - #[cfg(feature = "full")] - fn visit_field_pat(&mut self, i: &'ast FieldPat) { - visit_field_pat(self, i) - } - #[cfg(feature = "full")] - fn visit_field_value(&mut self, i: &'ast FieldValue) { - visit_field_value(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_fields(&mut self, i: &'ast Fields) { - visit_fields(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_fields_named(&mut self, i: &'ast FieldsNamed) { - visit_fields_named(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_fields_unnamed(&mut self, i: &'ast FieldsUnnamed) { - visit_fields_unnamed(self, i) - } - #[cfg(feature = "full")] - fn visit_file(&mut self, i: &'ast File) { - visit_file(self, i) - } - #[cfg(feature = "full")] - fn visit_fn_arg(&mut self, i: &'ast FnArg) { - visit_fn_arg(self, i) - } - #[cfg(feature = "full")] - fn visit_fn_decl(&mut self, i: &'ast FnDecl) { - visit_fn_decl(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item(&mut self, i: &'ast ForeignItem) { - visit_foreign_item(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_fn(&mut self, i: &'ast ForeignItemFn) { - visit_foreign_item_fn(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_macro(&mut self, i: &'ast ForeignItemMacro) { - visit_foreign_item_macro(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_static(&mut self, i: &'ast ForeignItemStatic) { - visit_foreign_item_static(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_type(&mut self, i: &'ast ForeignItemType) { - visit_foreign_item_type(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_verbatim(&mut self, i: &'ast ForeignItemVerbatim) { - visit_foreign_item_verbatim(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_generic_argument(&mut self, i: &'ast GenericArgument) { - visit_generic_argument(self, i) - } - #[cfg(feature = "full")] - fn visit_generic_method_argument(&mut self, i: &'ast GenericMethodArgument) { - visit_generic_method_argument(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_generic_param(&mut self, i: &'ast GenericParam) { - visit_generic_param(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_generics(&mut self, i: &'ast Generics) { - visit_generics(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item(&mut self, i: &'ast ImplItem) { - visit_impl_item(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_const(&mut self, i: &'ast ImplItemConst) { - visit_impl_item_const(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_existential(&mut self, i: &'ast ImplItemExistential) { - visit_impl_item_existential(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_macro(&mut self, i: &'ast ImplItemMacro) { - visit_impl_item_macro(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_method(&mut self, i: &'ast ImplItemMethod) { - visit_impl_item_method(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_type(&mut self, i: &'ast ImplItemType) { - visit_impl_item_type(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_verbatim(&mut self, i: &'ast ImplItemVerbatim) { - visit_impl_item_verbatim(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_index(&mut self, i: &'ast Index) { - visit_index(self, i) - } - #[cfg(feature = "full")] - fn visit_item(&mut self, i: &'ast Item) { - visit_item(self, i) - } - #[cfg(feature = "full")] - fn visit_item_const(&mut self, i: &'ast ItemConst) { - visit_item_const(self, i) - } - #[cfg(feature = "full")] - fn visit_item_enum(&mut self, i: &'ast ItemEnum) { - visit_item_enum(self, i) - } - #[cfg(feature = "full")] - fn visit_item_existential(&mut self, i: &'ast ItemExistential) { - visit_item_existential(self, i) - } - #[cfg(feature = "full")] - fn visit_item_extern_crate(&mut self, i: &'ast ItemExternCrate) { - visit_item_extern_crate(self, i) - } - #[cfg(feature = "full")] - fn visit_item_fn(&mut self, i: &'ast ItemFn) { - visit_item_fn(self, i) - } - #[cfg(feature = "full")] - fn visit_item_foreign_mod(&mut self, i: &'ast ItemForeignMod) { - visit_item_foreign_mod(self, i) - } - #[cfg(feature = "full")] - fn visit_item_impl(&mut self, i: &'ast ItemImpl) { - visit_item_impl(self, i) - } - #[cfg(feature = "full")] - fn visit_item_macro(&mut self, i: &'ast ItemMacro) { - visit_item_macro(self, i) - } - #[cfg(feature = "full")] - fn visit_item_macro2(&mut self, i: &'ast ItemMacro2) { - visit_item_macro2(self, i) - } - #[cfg(feature = "full")] - fn visit_item_mod(&mut self, i: &'ast ItemMod) { - visit_item_mod(self, i) - } - #[cfg(feature = "full")] - fn visit_item_static(&mut self, i: &'ast ItemStatic) { - visit_item_static(self, i) - } - #[cfg(feature = "full")] - fn visit_item_struct(&mut self, i: &'ast ItemStruct) { - visit_item_struct(self, i) - } - #[cfg(feature = "full")] - fn visit_item_trait(&mut self, i: &'ast ItemTrait) { - visit_item_trait(self, i) - } - #[cfg(feature = "full")] - fn visit_item_trait_alias(&mut self, i: &'ast ItemTraitAlias) { - visit_item_trait_alias(self, i) - } - #[cfg(feature = "full")] - fn visit_item_type(&mut self, i: &'ast ItemType) { - visit_item_type(self, i) - } - #[cfg(feature = "full")] - fn visit_item_union(&mut self, i: &'ast ItemUnion) { - visit_item_union(self, i) - } - #[cfg(feature = "full")] - fn visit_item_use(&mut self, i: &'ast ItemUse) { - visit_item_use(self, i) - } - #[cfg(feature = "full")] - fn visit_item_verbatim(&mut self, i: &'ast ItemVerbatim) { - visit_item_verbatim(self, i) - } - #[cfg(feature = "full")] - fn visit_label(&mut self, i: &'ast Label) { - visit_label(self, i) - } - fn visit_lifetime(&mut self, i: &'ast Lifetime) { - visit_lifetime(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lifetime_def(&mut self, i: &'ast LifetimeDef) { - visit_lifetime_def(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit(&mut self, i: &'ast Lit) { - visit_lit(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_bool(&mut self, i: &'ast LitBool) { - visit_lit_bool(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_byte(&mut self, i: &'ast LitByte) { - visit_lit_byte(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_byte_str(&mut self, i: &'ast LitByteStr) { - visit_lit_byte_str(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_char(&mut self, i: &'ast LitChar) { - visit_lit_char(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_float(&mut self, i: &'ast LitFloat) { - visit_lit_float(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_int(&mut self, i: &'ast LitInt) { - visit_lit_int(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_str(&mut self, i: &'ast LitStr) { - visit_lit_str(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_verbatim(&mut self, i: &'ast LitVerbatim) { - visit_lit_verbatim(self, i) - } - #[cfg(feature = "full")] - fn visit_local(&mut self, i: &'ast Local) { - visit_local(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_macro(&mut self, i: &'ast Macro) { - visit_macro(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_macro_delimiter(&mut self, i: &'ast MacroDelimiter) { - visit_macro_delimiter(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_member(&mut self, i: &'ast Member) { - visit_member(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_meta(&mut self, i: &'ast Meta) { - visit_meta(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_meta_list(&mut self, i: &'ast MetaList) { - visit_meta_list(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_meta_name_value(&mut self, i: &'ast MetaNameValue) { - visit_meta_name_value(self, i) - } - #[cfg(feature = "full")] - fn visit_method_sig(&mut self, i: &'ast MethodSig) { - visit_method_sig(self, i) - } - #[cfg(feature = "full")] - fn visit_method_turbofish(&mut self, i: &'ast MethodTurbofish) { - visit_method_turbofish(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_nested_meta(&mut self, i: &'ast NestedMeta) { - visit_nested_meta(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_parenthesized_generic_arguments(&mut self, i: &'ast ParenthesizedGenericArguments) { - visit_parenthesized_generic_arguments(self, i) - } - #[cfg(feature = "full")] - fn visit_pat(&mut self, i: &'ast Pat) { - visit_pat(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_box(&mut self, i: &'ast PatBox) { - visit_pat_box(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_ident(&mut self, i: &'ast PatIdent) { - visit_pat_ident(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_lit(&mut self, i: &'ast PatLit) { - visit_pat_lit(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_macro(&mut self, i: &'ast PatMacro) { - visit_pat_macro(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_path(&mut self, i: &'ast PatPath) { - visit_pat_path(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_range(&mut self, i: &'ast PatRange) { - visit_pat_range(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_ref(&mut self, i: &'ast PatRef) { - visit_pat_ref(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_slice(&mut self, i: &'ast PatSlice) { - visit_pat_slice(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_struct(&mut self, i: &'ast PatStruct) { - visit_pat_struct(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_tuple(&mut self, i: &'ast PatTuple) { - visit_pat_tuple(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_tuple_struct(&mut self, i: &'ast PatTupleStruct) { - visit_pat_tuple_struct(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_verbatim(&mut self, i: &'ast PatVerbatim) { - visit_pat_verbatim(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_wild(&mut self, i: &'ast PatWild) { - visit_pat_wild(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_path(&mut self, i: &'ast Path) { - visit_path(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_path_arguments(&mut self, i: &'ast PathArguments) { - visit_path_arguments(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_path_segment(&mut self, i: &'ast PathSegment) { - visit_path_segment(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_predicate_eq(&mut self, i: &'ast PredicateEq) { - visit_predicate_eq(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_predicate_lifetime(&mut self, i: &'ast PredicateLifetime) { - visit_predicate_lifetime(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_predicate_type(&mut self, i: &'ast PredicateType) { - visit_predicate_type(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_qself(&mut self, i: &'ast QSelf) { - visit_qself(self, i) - } - #[cfg(feature = "full")] - fn visit_range_limits(&mut self, i: &'ast RangeLimits) { - visit_range_limits(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_return_type(&mut self, i: &'ast ReturnType) { - visit_return_type(self, i) - } - #[cfg(feature = "full")] - fn visit_stmt(&mut self, i: &'ast Stmt) { - visit_stmt(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_trait_bound(&mut self, i: &'ast TraitBound) { - visit_trait_bound(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_trait_bound_modifier(&mut self, i: &'ast TraitBoundModifier) { - visit_trait_bound_modifier(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item(&mut self, i: &'ast TraitItem) { - visit_trait_item(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_const(&mut self, i: &'ast TraitItemConst) { - visit_trait_item_const(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_macro(&mut self, i: &'ast TraitItemMacro) { - visit_trait_item_macro(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_method(&mut self, i: &'ast TraitItemMethod) { - visit_trait_item_method(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_type(&mut self, i: &'ast TraitItemType) { - visit_trait_item_type(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_verbatim(&mut self, i: &'ast TraitItemVerbatim) { - visit_trait_item_verbatim(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type(&mut self, i: &'ast Type) { - visit_type(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_array(&mut self, i: &'ast TypeArray) { - visit_type_array(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_bare_fn(&mut self, i: &'ast TypeBareFn) { - visit_type_bare_fn(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_group(&mut self, i: &'ast TypeGroup) { - visit_type_group(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_impl_trait(&mut self, i: &'ast TypeImplTrait) { - visit_type_impl_trait(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_infer(&mut self, i: &'ast TypeInfer) { - visit_type_infer(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_macro(&mut self, i: &'ast TypeMacro) { - visit_type_macro(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_never(&mut self, i: &'ast TypeNever) { - visit_type_never(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_param(&mut self, i: &'ast TypeParam) { - visit_type_param(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_param_bound(&mut self, i: &'ast TypeParamBound) { - visit_type_param_bound(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_paren(&mut self, i: &'ast TypeParen) { - visit_type_paren(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_path(&mut self, i: &'ast TypePath) { - visit_type_path(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_ptr(&mut self, i: &'ast TypePtr) { - visit_type_ptr(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_reference(&mut self, i: &'ast TypeReference) { - visit_type_reference(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_slice(&mut self, i: &'ast TypeSlice) { - visit_type_slice(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_trait_object(&mut self, i: &'ast TypeTraitObject) { - visit_type_trait_object(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_tuple(&mut self, i: &'ast TypeTuple) { - visit_type_tuple(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_verbatim(&mut self, i: &'ast TypeVerbatim) { - visit_type_verbatim(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_un_op(&mut self, i: &'ast UnOp) { - visit_un_op(self, i) - } - #[cfg(feature = "full")] - fn visit_use_glob(&mut self, i: &'ast UseGlob) { - visit_use_glob(self, i) - } - #[cfg(feature = "full")] - fn visit_use_group(&mut self, i: &'ast UseGroup) { - visit_use_group(self, i) - } - #[cfg(feature = "full")] - fn visit_use_name(&mut self, i: &'ast UseName) { - visit_use_name(self, i) - } - #[cfg(feature = "full")] - fn visit_use_path(&mut self, i: &'ast UsePath) { - visit_use_path(self, i) - } - #[cfg(feature = "full")] - fn visit_use_rename(&mut self, i: &'ast UseRename) { - visit_use_rename(self, i) - } - #[cfg(feature = "full")] - fn visit_use_tree(&mut self, i: &'ast UseTree) { - visit_use_tree(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_variant(&mut self, i: &'ast Variant) { - visit_variant(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_vis_crate(&mut self, i: &'ast VisCrate) { - visit_vis_crate(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_vis_public(&mut self, i: &'ast VisPublic) { - visit_vis_public(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_vis_restricted(&mut self, i: &'ast VisRestricted) { - visit_vis_restricted(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_visibility(&mut self, i: &'ast Visibility) { - visit_visibility(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_where_clause(&mut self, i: &'ast WhereClause) { - visit_where_clause(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_where_predicate(&mut self, i: &'ast WherePredicate) { - visit_where_predicate(self, i) - } - fn visit_span(&mut self, i: &'ast Span) { - visit_span(self, i) - } - fn visit_ident(&mut self, i: &'ast Ident) { - visit_ident(self, i) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_abi<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Abi) { - tokens_helper(_visitor, &_i.extern_token.span); - if let Some(ref it) = _i.name { - _visitor.visit_lit_str(it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_angle_bracketed_generic_arguments<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast AngleBracketedGenericArguments, -) { - if let Some(ref it) = _i.colon2_token { - tokens_helper(_visitor, &it.spans) - }; - tokens_helper(_visitor, &_i.lt_token.spans); - for el in Punctuated::pairs(&_i.args) { - let it = el.value(); - _visitor.visit_generic_argument(it) - } - tokens_helper(_visitor, &_i.gt_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_arg_captured<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ArgCaptured) { - _visitor.visit_pat(&_i.pat); - tokens_helper(_visitor, &_i.colon_token.spans); - _visitor.visit_type(&_i.ty); -} -#[cfg(feature = "full")] -pub fn visit_arg_self<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ArgSelf) { - if let Some(ref it) = _i.mutability { - tokens_helper(_visitor, &it.span) - }; - tokens_helper(_visitor, &_i.self_token.span); -} -#[cfg(feature = "full")] -pub fn visit_arg_self_ref<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ArgSelfRef) { - tokens_helper(_visitor, &_i.and_token.spans); - if let Some(ref it) = _i.lifetime { - _visitor.visit_lifetime(it) - }; - if let Some(ref it) = _i.mutability { - tokens_helper(_visitor, &it.span) - }; - tokens_helper(_visitor, &_i.self_token.span); -} -#[cfg(feature = "full")] -pub fn visit_arm<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Arm) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.leading_vert { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.pats) { - let it = el.value(); - _visitor.visit_pat(it) - } - if let Some(ref it) = _i.guard { - tokens_helper(_visitor, &(it).0.span); - _visitor.visit_expr(&*(it).1); - }; - tokens_helper(_visitor, &_i.fat_arrow_token.spans); - _visitor.visit_expr(&*_i.body); - if let Some(ref it) = _i.comma { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_attr_style<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast AttrStyle) { - match *_i { - AttrStyle::Outer => {} - AttrStyle::Inner(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_attribute<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Attribute) { - tokens_helper(_visitor, &_i.pound_token.spans); - _visitor.visit_attr_style(&_i.style); - tokens_helper(_visitor, &_i.bracket_token.span); - _visitor.visit_path(&_i.path); - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_bare_fn_arg<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast BareFnArg) { - if let Some(ref it) = _i.name { - _visitor.visit_bare_fn_arg_name(&(it).0); - tokens_helper(_visitor, &(it).1.spans); - }; - _visitor.visit_type(&_i.ty); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_bare_fn_arg_name<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast BareFnArgName, -) { - match *_i { - BareFnArgName::Named(ref _binding_0) => { - _visitor.visit_ident(_binding_0); - } - BareFnArgName::Wild(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_bin_op<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast BinOp) { - match *_i { - BinOp::Add(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Sub(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Mul(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Div(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Rem(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::And(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Or(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::BitXor(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::BitAnd(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::BitOr(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Shl(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Shr(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Eq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Lt(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Le(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Ne(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Ge(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::Gt(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::AddEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::SubEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::MulEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::DivEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::RemEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::BitXorEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::BitAndEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::BitOrEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::ShlEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - BinOp::ShrEq(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_binding<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Binding) { - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_type(&_i.ty); -} -#[cfg(feature = "full")] -pub fn visit_block<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Block) { - tokens_helper(_visitor, &_i.brace_token.span); - for it in &_i.stmts { - _visitor.visit_stmt(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_bound_lifetimes<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast BoundLifetimes, -) { - tokens_helper(_visitor, &_i.for_token.span); - tokens_helper(_visitor, &_i.lt_token.spans); - for el in Punctuated::pairs(&_i.lifetimes) { - let it = el.value(); - _visitor.visit_lifetime_def(it) - } - tokens_helper(_visitor, &_i.gt_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_const_param<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ConstParam) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.const_token.span); - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.colon_token.spans); - _visitor.visit_type(&_i.ty); - if let Some(ref it) = _i.eq_token { - tokens_helper(_visitor, &it.spans) - }; - if let Some(ref it) = _i.default { - _visitor.visit_expr(it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_constraint<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Constraint) { - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.colon_token.spans); - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } -} -#[cfg(feature = "derive")] -pub fn visit_data<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Data) { - match *_i { - Data::Struct(ref _binding_0) => { - _visitor.visit_data_struct(_binding_0); - } - Data::Enum(ref _binding_0) => { - _visitor.visit_data_enum(_binding_0); - } - Data::Union(ref _binding_0) => { - _visitor.visit_data_union(_binding_0); - } - } -} -#[cfg(feature = "derive")] -pub fn visit_data_enum<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast DataEnum) { - tokens_helper(_visitor, &_i.enum_token.span); - tokens_helper(_visitor, &_i.brace_token.span); - for el in Punctuated::pairs(&_i.variants) { - let it = el.value(); - _visitor.visit_variant(it) - } -} -#[cfg(feature = "derive")] -pub fn visit_data_struct<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast DataStruct) { - tokens_helper(_visitor, &_i.struct_token.span); - _visitor.visit_fields(&_i.fields); - if let Some(ref it) = _i.semi_token { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(feature = "derive")] -pub fn visit_data_union<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast DataUnion) { - tokens_helper(_visitor, &_i.union_token.span); - _visitor.visit_fields_named(&_i.fields); -} -#[cfg(feature = "derive")] -pub fn visit_derive_input<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast DeriveInput) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - _visitor.visit_data(&_i.data); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Expr) { - match *_i { - Expr::Box(ref _binding_0) => { - full!(_visitor.visit_expr_box(_binding_0)); - } - Expr::InPlace(ref _binding_0) => { - full!(_visitor.visit_expr_in_place(_binding_0)); - } - Expr::Array(ref _binding_0) => { - full!(_visitor.visit_expr_array(_binding_0)); - } - Expr::Call(ref _binding_0) => { - _visitor.visit_expr_call(_binding_0); - } - Expr::MethodCall(ref _binding_0) => { - full!(_visitor.visit_expr_method_call(_binding_0)); - } - Expr::Tuple(ref _binding_0) => { - full!(_visitor.visit_expr_tuple(_binding_0)); - } - Expr::Binary(ref _binding_0) => { - _visitor.visit_expr_binary(_binding_0); - } - Expr::Unary(ref _binding_0) => { - _visitor.visit_expr_unary(_binding_0); - } - Expr::Lit(ref _binding_0) => { - _visitor.visit_expr_lit(_binding_0); - } - Expr::Cast(ref _binding_0) => { - _visitor.visit_expr_cast(_binding_0); - } - Expr::Type(ref _binding_0) => { - full!(_visitor.visit_expr_type(_binding_0)); - } - Expr::Let(ref _binding_0) => { - full!(_visitor.visit_expr_let(_binding_0)); - } - Expr::If(ref _binding_0) => { - full!(_visitor.visit_expr_if(_binding_0)); - } - Expr::While(ref _binding_0) => { - full!(_visitor.visit_expr_while(_binding_0)); - } - Expr::ForLoop(ref _binding_0) => { - full!(_visitor.visit_expr_for_loop(_binding_0)); - } - Expr::Loop(ref _binding_0) => { - full!(_visitor.visit_expr_loop(_binding_0)); - } - Expr::Match(ref _binding_0) => { - full!(_visitor.visit_expr_match(_binding_0)); - } - Expr::Closure(ref _binding_0) => { - full!(_visitor.visit_expr_closure(_binding_0)); - } - Expr::Unsafe(ref _binding_0) => { - full!(_visitor.visit_expr_unsafe(_binding_0)); - } - Expr::Block(ref _binding_0) => { - full!(_visitor.visit_expr_block(_binding_0)); - } - Expr::Assign(ref _binding_0) => { - full!(_visitor.visit_expr_assign(_binding_0)); - } - Expr::AssignOp(ref _binding_0) => { - full!(_visitor.visit_expr_assign_op(_binding_0)); - } - Expr::Field(ref _binding_0) => { - _visitor.visit_expr_field(_binding_0); - } - Expr::Index(ref _binding_0) => { - _visitor.visit_expr_index(_binding_0); - } - Expr::Range(ref _binding_0) => { - full!(_visitor.visit_expr_range(_binding_0)); - } - Expr::Path(ref _binding_0) => { - _visitor.visit_expr_path(_binding_0); - } - Expr::Reference(ref _binding_0) => { - full!(_visitor.visit_expr_reference(_binding_0)); - } - Expr::Break(ref _binding_0) => { - full!(_visitor.visit_expr_break(_binding_0)); - } - Expr::Continue(ref _binding_0) => { - full!(_visitor.visit_expr_continue(_binding_0)); - } - Expr::Return(ref _binding_0) => { - full!(_visitor.visit_expr_return(_binding_0)); - } - Expr::Macro(ref _binding_0) => { - full!(_visitor.visit_expr_macro(_binding_0)); - } - Expr::Struct(ref _binding_0) => { - full!(_visitor.visit_expr_struct(_binding_0)); - } - Expr::Repeat(ref _binding_0) => { - full!(_visitor.visit_expr_repeat(_binding_0)); - } - Expr::Paren(ref _binding_0) => { - _visitor.visit_expr_paren(_binding_0); - } - Expr::Group(ref _binding_0) => { - full!(_visitor.visit_expr_group(_binding_0)); - } - Expr::Try(ref _binding_0) => { - full!(_visitor.visit_expr_try(_binding_0)); - } - Expr::Async(ref _binding_0) => { - full!(_visitor.visit_expr_async(_binding_0)); - } - Expr::TryBlock(ref _binding_0) => { - full!(_visitor.visit_expr_try_block(_binding_0)); - } - Expr::Yield(ref _binding_0) => { - full!(_visitor.visit_expr_yield(_binding_0)); - } - Expr::Verbatim(ref _binding_0) => { - _visitor.visit_expr_verbatim(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_expr_array<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprArray) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.bracket_token.span); - for el in Punctuated::pairs(&_i.elems) { - let it = el.value(); - _visitor.visit_expr(it) - } -} -#[cfg(feature = "full")] -pub fn visit_expr_assign<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprAssign) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.left); - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_expr(&*_i.right); -} -#[cfg(feature = "full")] -pub fn visit_expr_assign_op<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ExprAssignOp, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.left); - _visitor.visit_bin_op(&_i.op); - _visitor.visit_expr(&*_i.right); -} -#[cfg(feature = "full")] -pub fn visit_expr_async<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprAsync) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.async_token.span); - if let Some(ref it) = _i.capture { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_block(&_i.block); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_binary<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprBinary) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.left); - _visitor.visit_bin_op(&_i.op); - _visitor.visit_expr(&*_i.right); -} -#[cfg(feature = "full")] -pub fn visit_expr_block<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprBlock) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.label { - _visitor.visit_label(it) - }; - _visitor.visit_block(&_i.block); -} -#[cfg(feature = "full")] -pub fn visit_expr_box<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprBox) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.box_token.span); - _visitor.visit_expr(&*_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_expr_break<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprBreak) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.break_token.span); - if let Some(ref it) = _i.label { - _visitor.visit_lifetime(it) - }; - if let Some(ref it) = _i.expr { - _visitor.visit_expr(&**it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_call<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprCall) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.func); - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.args) { - let it = el.value(); - _visitor.visit_expr(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_cast<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprCast) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.expr); - tokens_helper(_visitor, &_i.as_token.span); - _visitor.visit_type(&*_i.ty); -} -#[cfg(feature = "full")] -pub fn visit_expr_closure<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprClosure) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.asyncness { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.movability { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.capture { - tokens_helper(_visitor, &it.span) - }; - tokens_helper(_visitor, &_i.or1_token.spans); - for el in Punctuated::pairs(&_i.inputs) { - let it = el.value(); - _visitor.visit_fn_arg(it) - } - tokens_helper(_visitor, &_i.or2_token.spans); - _visitor.visit_return_type(&_i.output); - _visitor.visit_expr(&*_i.body); -} -#[cfg(feature = "full")] -pub fn visit_expr_continue<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ExprContinue, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.continue_token.span); - if let Some(ref it) = _i.label { - _visitor.visit_lifetime(it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_field<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprField) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.base); - tokens_helper(_visitor, &_i.dot_token.spans); - _visitor.visit_member(&_i.member); -} -#[cfg(feature = "full")] -pub fn visit_expr_for_loop<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprForLoop) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.label { - _visitor.visit_label(it) - }; - tokens_helper(_visitor, &_i.for_token.span); - _visitor.visit_pat(&*_i.pat); - tokens_helper(_visitor, &_i.in_token.span); - _visitor.visit_expr(&*_i.expr); - _visitor.visit_block(&_i.body); -} -#[cfg(feature = "full")] -pub fn visit_expr_group<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprGroup) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.group_token.span); - _visitor.visit_expr(&*_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_expr_if<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprIf) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.if_token.span); - _visitor.visit_expr(&*_i.cond); - _visitor.visit_block(&_i.then_branch); - if let Some(ref it) = _i.else_branch { - tokens_helper(_visitor, &(it).0.span); - _visitor.visit_expr(&*(it).1); - }; -} -#[cfg(feature = "full")] -pub fn visit_expr_in_place<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprInPlace) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.place); - tokens_helper(_visitor, &_i.arrow_token.spans); - _visitor.visit_expr(&*_i.value); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_index<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprIndex) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.expr); - tokens_helper(_visitor, &_i.bracket_token.span); - _visitor.visit_expr(&*_i.index); -} -#[cfg(feature = "full")] -pub fn visit_expr_let<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprLet) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.let_token.span); - for el in Punctuated::pairs(&_i.pats) { - let it = el.value(); - _visitor.visit_pat(it) - } - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_expr(&*_i.expr); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_lit<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprLit) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_lit(&_i.lit); -} -#[cfg(feature = "full")] -pub fn visit_expr_loop<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprLoop) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.label { - _visitor.visit_label(it) - }; - tokens_helper(_visitor, &_i.loop_token.span); - _visitor.visit_block(&_i.body); -} -#[cfg(feature = "full")] -pub fn visit_expr_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprMacro) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_macro(&_i.mac); -} -#[cfg(feature = "full")] -pub fn visit_expr_match<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprMatch) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.match_token.span); - _visitor.visit_expr(&*_i.expr); - tokens_helper(_visitor, &_i.brace_token.span); - for it in &_i.arms { - _visitor.visit_arm(it) - } -} -#[cfg(feature = "full")] -pub fn visit_expr_method_call<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ExprMethodCall, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.receiver); - tokens_helper(_visitor, &_i.dot_token.spans); - _visitor.visit_ident(&_i.method); - if let Some(ref it) = _i.turbofish { - _visitor.visit_method_turbofish(it) - }; - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.args) { - let it = el.value(); - _visitor.visit_expr(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_paren<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprParen) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.paren_token.span); - _visitor.visit_expr(&*_i.expr); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprPath) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.qself { - _visitor.visit_qself(it) - }; - _visitor.visit_path(&_i.path); -} -#[cfg(feature = "full")] -pub fn visit_expr_range<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprRange) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.from { - _visitor.visit_expr(&**it) - }; - _visitor.visit_range_limits(&_i.limits); - if let Some(ref it) = _i.to { - _visitor.visit_expr(&**it) - }; -} -#[cfg(feature = "full")] -pub fn visit_expr_reference<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ExprReference, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.and_token.spans); - if let Some(ref it) = _i.mutability { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_expr(&*_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_expr_repeat<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprRepeat) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.bracket_token.span); - _visitor.visit_expr(&*_i.expr); - tokens_helper(_visitor, &_i.semi_token.spans); - _visitor.visit_expr(&*_i.len); -} -#[cfg(feature = "full")] -pub fn visit_expr_return<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprReturn) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.return_token.span); - if let Some(ref it) = _i.expr { - _visitor.visit_expr(&**it) - }; -} -#[cfg(feature = "full")] -pub fn visit_expr_struct<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprStruct) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_path(&_i.path); - tokens_helper(_visitor, &_i.brace_token.span); - for el in Punctuated::pairs(&_i.fields) { - let it = el.value(); - _visitor.visit_field_value(it) - } - if let Some(ref it) = _i.dot2_token { - tokens_helper(_visitor, &it.spans) - }; - if let Some(ref it) = _i.rest { - _visitor.visit_expr(&**it) - }; -} -#[cfg(feature = "full")] -pub fn visit_expr_try<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprTry) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.expr); - tokens_helper(_visitor, &_i.question_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_expr_try_block<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ExprTryBlock, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.try_token.span); - _visitor.visit_block(&_i.block); -} -#[cfg(feature = "full")] -pub fn visit_expr_tuple<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprTuple) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.elems) { - let it = el.value(); - _visitor.visit_expr(it) - } -} -#[cfg(feature = "full")] -pub fn visit_expr_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprType) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_expr(&*_i.expr); - tokens_helper(_visitor, &_i.colon_token.spans); - _visitor.visit_type(&*_i.ty); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_unary<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprUnary) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_un_op(&_i.op); - _visitor.visit_expr(&*_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_expr_unsafe<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprUnsafe) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.unsafe_token.span); - _visitor.visit_block(&_i.block); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_verbatim<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ExprVerbatim, -) { - skip!(_i.tts); -} -#[cfg(feature = "full")] -pub fn visit_expr_while<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprWhile) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.label { - _visitor.visit_label(it) - }; - tokens_helper(_visitor, &_i.while_token.span); - _visitor.visit_expr(&*_i.cond); - _visitor.visit_block(&_i.body); -} -#[cfg(feature = "full")] -pub fn visit_expr_yield<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprYield) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.yield_token.span); - if let Some(ref it) = _i.expr { - _visitor.visit_expr(&**it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_field<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Field) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - if let Some(ref it) = _i.ident { - _visitor.visit_ident(it) - }; - if let Some(ref it) = _i.colon_token { - tokens_helper(_visitor, &it.spans) - }; - _visitor.visit_type(&_i.ty); -} -#[cfg(feature = "full")] -pub fn visit_field_pat<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FieldPat) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_member(&_i.member); - if let Some(ref it) = _i.colon_token { - tokens_helper(_visitor, &it.spans) - }; - _visitor.visit_pat(&*_i.pat); -} -#[cfg(feature = "full")] -pub fn visit_field_value<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FieldValue) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_member(&_i.member); - if let Some(ref it) = _i.colon_token { - tokens_helper(_visitor, &it.spans) - }; - _visitor.visit_expr(&_i.expr); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_fields<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Fields) { - match *_i { - Fields::Named(ref _binding_0) => { - _visitor.visit_fields_named(_binding_0); - } - Fields::Unnamed(ref _binding_0) => { - _visitor.visit_fields_unnamed(_binding_0); - } - Fields::Unit => {} - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_fields_named<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FieldsNamed) { - tokens_helper(_visitor, &_i.brace_token.span); - for el in Punctuated::pairs(&_i.named) { - let it = el.value(); - _visitor.visit_field(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_fields_unnamed<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast FieldsUnnamed, -) { - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.unnamed) { - let it = el.value(); - _visitor.visit_field(it) - } -} -#[cfg(feature = "full")] -pub fn visit_file<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast File) { - skip!(_i.shebang); - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - for it in &_i.items { - _visitor.visit_item(it) - } -} -#[cfg(feature = "full")] -pub fn visit_fn_arg<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FnArg) { - match *_i { - FnArg::SelfRef(ref _binding_0) => { - _visitor.visit_arg_self_ref(_binding_0); - } - FnArg::SelfValue(ref _binding_0) => { - _visitor.visit_arg_self(_binding_0); - } - FnArg::Captured(ref _binding_0) => { - _visitor.visit_arg_captured(_binding_0); - } - FnArg::Inferred(ref _binding_0) => { - _visitor.visit_pat(_binding_0); - } - FnArg::Ignored(ref _binding_0) => { - _visitor.visit_type(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_fn_decl<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FnDecl) { - tokens_helper(_visitor, &_i.fn_token.span); - _visitor.visit_generics(&_i.generics); - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.inputs) { - let it = el.value(); - _visitor.visit_fn_arg(it) - } - if let Some(ref it) = _i.variadic { - tokens_helper(_visitor, &it.spans) - }; - _visitor.visit_return_type(&_i.output); -} -#[cfg(feature = "full")] -pub fn visit_foreign_item<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ForeignItem) { - match *_i { - ForeignItem::Fn(ref _binding_0) => { - _visitor.visit_foreign_item_fn(_binding_0); - } - ForeignItem::Static(ref _binding_0) => { - _visitor.visit_foreign_item_static(_binding_0); - } - ForeignItem::Type(ref _binding_0) => { - _visitor.visit_foreign_item_type(_binding_0); - } - ForeignItem::Macro(ref _binding_0) => { - _visitor.visit_foreign_item_macro(_binding_0); - } - ForeignItem::Verbatim(ref _binding_0) => { - _visitor.visit_foreign_item_verbatim(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_fn<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ForeignItemFn, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - _visitor.visit_ident(&_i.ident); - _visitor.visit_fn_decl(&*_i.decl); - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_macro<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ForeignItemMacro, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_macro(&_i.mac); - if let Some(ref it) = _i.semi_token { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_static<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ForeignItemStatic, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.static_token.span); - if let Some(ref it) = _i.mutability { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.colon_token.spans); - _visitor.visit_type(&*_i.ty); - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_type<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ForeignItemType, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.type_token.span); - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_verbatim<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ForeignItemVerbatim, -) { - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_generic_argument<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast GenericArgument, -) { - match *_i { - GenericArgument::Lifetime(ref _binding_0) => { - _visitor.visit_lifetime(_binding_0); - } - GenericArgument::Type(ref _binding_0) => { - _visitor.visit_type(_binding_0); - } - GenericArgument::Binding(ref _binding_0) => { - _visitor.visit_binding(_binding_0); - } - GenericArgument::Constraint(ref _binding_0) => { - _visitor.visit_constraint(_binding_0); - } - GenericArgument::Const(ref _binding_0) => { - _visitor.visit_expr(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_generic_method_argument<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast GenericMethodArgument, -) { - match *_i { - GenericMethodArgument::Type(ref _binding_0) => { - _visitor.visit_type(_binding_0); - } - GenericMethodArgument::Const(ref _binding_0) => { - _visitor.visit_expr(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_generic_param<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast GenericParam, -) { - match *_i { - GenericParam::Type(ref _binding_0) => { - _visitor.visit_type_param(_binding_0); - } - GenericParam::Lifetime(ref _binding_0) => { - _visitor.visit_lifetime_def(_binding_0); - } - GenericParam::Const(ref _binding_0) => { - _visitor.visit_const_param(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_generics<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Generics) { - if let Some(ref it) = _i.lt_token { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.params) { - let it = el.value(); - _visitor.visit_generic_param(it) - } - if let Some(ref it) = _i.gt_token { - tokens_helper(_visitor, &it.spans) - }; - if let Some(ref it) = _i.where_clause { - _visitor.visit_where_clause(it) - }; -} -#[cfg(feature = "full")] -pub fn visit_impl_item<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ImplItem) { - match *_i { - ImplItem::Const(ref _binding_0) => { - _visitor.visit_impl_item_const(_binding_0); - } - ImplItem::Method(ref _binding_0) => { - _visitor.visit_impl_item_method(_binding_0); - } - ImplItem::Type(ref _binding_0) => { - _visitor.visit_impl_item_type(_binding_0); - } - ImplItem::Existential(ref _binding_0) => { - _visitor.visit_impl_item_existential(_binding_0); - } - ImplItem::Macro(ref _binding_0) => { - _visitor.visit_impl_item_macro(_binding_0); - } - ImplItem::Verbatim(ref _binding_0) => { - _visitor.visit_impl_item_verbatim(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_impl_item_const<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ImplItemConst, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - if let Some(ref it) = _i.defaultness { - tokens_helper(_visitor, &it.span) - }; - tokens_helper(_visitor, &_i.const_token.span); - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.colon_token.spans); - _visitor.visit_type(&_i.ty); - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_expr(&_i.expr); - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_impl_item_existential<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ImplItemExistential, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.existential_token.span); - tokens_helper(_visitor, &_i.type_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - if let Some(ref it) = _i.colon_token { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_impl_item_macro<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ImplItemMacro, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_macro(&_i.mac); - if let Some(ref it) = _i.semi_token { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_impl_item_method<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ImplItemMethod, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - if let Some(ref it) = _i.defaultness { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_method_sig(&_i.sig); - _visitor.visit_block(&_i.block); -} -#[cfg(feature = "full")] -pub fn visit_impl_item_type<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ImplItemType, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - if let Some(ref it) = _i.defaultness { - tokens_helper(_visitor, &it.span) - }; - tokens_helper(_visitor, &_i.type_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_type(&_i.ty); - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_impl_item_verbatim<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ImplItemVerbatim, -) { - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_index<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Index) { - skip!(_i.index); - _visitor.visit_span(&_i.span); -} -#[cfg(feature = "full")] -pub fn visit_item<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Item) { - match *_i { - Item::ExternCrate(ref _binding_0) => { - _visitor.visit_item_extern_crate(_binding_0); - } - Item::Use(ref _binding_0) => { - _visitor.visit_item_use(_binding_0); - } - Item::Static(ref _binding_0) => { - _visitor.visit_item_static(_binding_0); - } - Item::Const(ref _binding_0) => { - _visitor.visit_item_const(_binding_0); - } - Item::Fn(ref _binding_0) => { - _visitor.visit_item_fn(_binding_0); - } - Item::Mod(ref _binding_0) => { - _visitor.visit_item_mod(_binding_0); - } - Item::ForeignMod(ref _binding_0) => { - _visitor.visit_item_foreign_mod(_binding_0); - } - Item::Type(ref _binding_0) => { - _visitor.visit_item_type(_binding_0); - } - Item::Existential(ref _binding_0) => { - _visitor.visit_item_existential(_binding_0); - } - Item::Struct(ref _binding_0) => { - _visitor.visit_item_struct(_binding_0); - } - Item::Enum(ref _binding_0) => { - _visitor.visit_item_enum(_binding_0); - } - Item::Union(ref _binding_0) => { - _visitor.visit_item_union(_binding_0); - } - Item::Trait(ref _binding_0) => { - _visitor.visit_item_trait(_binding_0); - } - Item::TraitAlias(ref _binding_0) => { - _visitor.visit_item_trait_alias(_binding_0); - } - Item::Impl(ref _binding_0) => { - _visitor.visit_item_impl(_binding_0); - } - Item::Macro(ref _binding_0) => { - _visitor.visit_item_macro(_binding_0); - } - Item::Macro2(ref _binding_0) => { - _visitor.visit_item_macro2(_binding_0); - } - Item::Verbatim(ref _binding_0) => { - _visitor.visit_item_verbatim(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_item_const<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemConst) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.const_token.span); - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.colon_token.spans); - _visitor.visit_type(&*_i.ty); - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_expr(&*_i.expr); - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_enum<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemEnum) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.enum_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - tokens_helper(_visitor, &_i.brace_token.span); - for el in Punctuated::pairs(&_i.variants) { - let it = el.value(); - _visitor.visit_variant(it) - } -} -#[cfg(feature = "full")] -pub fn visit_item_existential<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ItemExistential, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.existential_token.span); - tokens_helper(_visitor, &_i.type_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - if let Some(ref it) = _i.colon_token { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_extern_crate<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ItemExternCrate, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.extern_token.span); - tokens_helper(_visitor, &_i.crate_token.span); - _visitor.visit_ident(&_i.ident); - if let Some(ref it) = _i.rename { - tokens_helper(_visitor, &(it).0.span); - _visitor.visit_ident(&(it).1); - }; - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_fn<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemFn) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - if let Some(ref it) = _i.constness { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.asyncness { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.unsafety { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.abi { - _visitor.visit_abi(it) - }; - _visitor.visit_ident(&_i.ident); - _visitor.visit_fn_decl(&*_i.decl); - _visitor.visit_block(&*_i.block); -} -#[cfg(feature = "full")] -pub fn visit_item_foreign_mod<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ItemForeignMod, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_abi(&_i.abi); - tokens_helper(_visitor, &_i.brace_token.span); - for it in &_i.items { - _visitor.visit_foreign_item(it) - } -} -#[cfg(feature = "full")] -pub fn visit_item_impl<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemImpl) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.defaultness { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.unsafety { - tokens_helper(_visitor, &it.span) - }; - tokens_helper(_visitor, &_i.impl_token.span); - _visitor.visit_generics(&_i.generics); - if let Some(ref it) = _i.trait_ { - if let Some(ref it) = (it).0 { - tokens_helper(_visitor, &it.spans) - }; - _visitor.visit_path(&(it).1); - tokens_helper(_visitor, &(it).2.span); - }; - _visitor.visit_type(&*_i.self_ty); - tokens_helper(_visitor, &_i.brace_token.span); - for it in &_i.items { - _visitor.visit_impl_item(it) - } -} -#[cfg(feature = "full")] -pub fn visit_item_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemMacro) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - if let Some(ref it) = _i.ident { - _visitor.visit_ident(it) - }; - _visitor.visit_macro(&_i.mac); - if let Some(ref it) = _i.semi_token { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_item_macro2<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemMacro2) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.macro_token.span); - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.paren_token.span); - skip!(_i.args); - tokens_helper(_visitor, &_i.brace_token.span); - skip!(_i.body); -} -#[cfg(feature = "full")] -pub fn visit_item_mod<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemMod) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.mod_token.span); - _visitor.visit_ident(&_i.ident); - if let Some(ref it) = _i.content { - tokens_helper(_visitor, &(it).0.span); - for it in &(it).1 { - _visitor.visit_item(it) - } - }; - if let Some(ref it) = _i.semi { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_item_static<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemStatic) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.static_token.span); - if let Some(ref it) = _i.mutability { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.colon_token.spans); - _visitor.visit_type(&*_i.ty); - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_expr(&*_i.expr); - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_struct<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemStruct) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.struct_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - _visitor.visit_fields(&_i.fields); - if let Some(ref it) = _i.semi_token { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_item_trait<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemTrait) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - if let Some(ref it) = _i.unsafety { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.auto_token { - tokens_helper(_visitor, &it.span) - }; - tokens_helper(_visitor, &_i.trait_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - if let Some(ref it) = _i.colon_token { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.supertraits) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } - tokens_helper(_visitor, &_i.brace_token.span); - for it in &_i.items { - _visitor.visit_trait_item(it) - } -} -#[cfg(feature = "full")] -pub fn visit_item_trait_alias<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ItemTraitAlias, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.trait_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - tokens_helper(_visitor, &_i.eq_token.spans); - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemType) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.type_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_type(&*_i.ty); - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_union<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemUnion) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.union_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - _visitor.visit_fields_named(&_i.fields); -} -#[cfg(feature = "full")] -pub fn visit_item_use<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemUse) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_visibility(&_i.vis); - tokens_helper(_visitor, &_i.use_token.span); - if let Some(ref it) = _i.leading_colon { - tokens_helper(_visitor, &it.spans) - }; - _visitor.visit_use_tree(&_i.tree); - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_verbatim<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ItemVerbatim, -) { - skip!(_i.tts); -} -#[cfg(feature = "full")] -pub fn visit_label<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Label) { - _visitor.visit_lifetime(&_i.name); - tokens_helper(_visitor, &_i.colon_token.spans); -} -pub fn visit_lifetime<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Lifetime) { - _visitor.visit_span(&_i.apostrophe); - _visitor.visit_ident(&_i.ident); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lifetime_def<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LifetimeDef) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_lifetime(&_i.lifetime); - if let Some(ref it) = _i.colon_token { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_lifetime(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Lit) { - match *_i { - Lit::Str(ref _binding_0) => { - _visitor.visit_lit_str(_binding_0); - } - Lit::ByteStr(ref _binding_0) => { - _visitor.visit_lit_byte_str(_binding_0); - } - Lit::Byte(ref _binding_0) => { - _visitor.visit_lit_byte(_binding_0); - } - Lit::Char(ref _binding_0) => { - _visitor.visit_lit_char(_binding_0); - } - Lit::Int(ref _binding_0) => { - _visitor.visit_lit_int(_binding_0); - } - Lit::Float(ref _binding_0) => { - _visitor.visit_lit_float(_binding_0); - } - Lit::Bool(ref _binding_0) => { - _visitor.visit_lit_bool(_binding_0); - } - Lit::Verbatim(ref _binding_0) => { - _visitor.visit_lit_verbatim(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_bool<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitBool) { - skip!(_i.value); - _visitor.visit_span(&_i.span); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_byte<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitByte) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_byte_str<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitByteStr) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_char<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitChar) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_float<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitFloat) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_int<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitInt) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_str<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitStr) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitVerbatim) { - skip!(_i.token); -} -#[cfg(feature = "full")] -pub fn visit_local<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Local) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.let_token.span); - for el in Punctuated::pairs(&_i.pats) { - let it = el.value(); - _visitor.visit_pat(it) - } - if let Some(ref it) = _i.ty { - tokens_helper(_visitor, &(it).0.spans); - _visitor.visit_type(&*(it).1); - }; - if let Some(ref it) = _i.init { - tokens_helper(_visitor, &(it).0.spans); - _visitor.visit_expr(&*(it).1); - }; - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Macro) { - _visitor.visit_path(&_i.path); - tokens_helper(_visitor, &_i.bang_token.spans); - _visitor.visit_macro_delimiter(&_i.delimiter); - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_macro_delimiter<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast MacroDelimiter, -) { - match *_i { - MacroDelimiter::Paren(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.span); - } - MacroDelimiter::Brace(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.span); - } - MacroDelimiter::Bracket(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.span); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_member<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Member) { - match *_i { - Member::Named(ref _binding_0) => { - _visitor.visit_ident(_binding_0); - } - Member::Unnamed(ref _binding_0) => { - _visitor.visit_index(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_meta<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Meta) { - match *_i { - Meta::Word(ref _binding_0) => { - _visitor.visit_ident(_binding_0); - } - Meta::List(ref _binding_0) => { - _visitor.visit_meta_list(_binding_0); - } - Meta::NameValue(ref _binding_0) => { - _visitor.visit_meta_name_value(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_meta_list<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast MetaList) { - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.nested) { - let it = el.value(); - _visitor.visit_nested_meta(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_meta_name_value<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast MetaNameValue, -) { - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_lit(&_i.lit); -} -#[cfg(feature = "full")] -pub fn visit_method_sig<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast MethodSig) { - if let Some(ref it) = _i.constness { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.asyncness { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.unsafety { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.abi { - _visitor.visit_abi(it) - }; - _visitor.visit_ident(&_i.ident); - _visitor.visit_fn_decl(&_i.decl); -} -#[cfg(feature = "full")] -pub fn visit_method_turbofish<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast MethodTurbofish, -) { - tokens_helper(_visitor, &_i.colon2_token.spans); - tokens_helper(_visitor, &_i.lt_token.spans); - for el in Punctuated::pairs(&_i.args) { - let it = el.value(); - _visitor.visit_generic_method_argument(it) - } - tokens_helper(_visitor, &_i.gt_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_nested_meta<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast NestedMeta) { - match *_i { - NestedMeta::Meta(ref _binding_0) => { - _visitor.visit_meta(_binding_0); - } - NestedMeta::Literal(ref _binding_0) => { - _visitor.visit_lit(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_parenthesized_generic_arguments<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast ParenthesizedGenericArguments, -) { - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.inputs) { - let it = el.value(); - _visitor.visit_type(it) - } - _visitor.visit_return_type(&_i.output); -} -#[cfg(feature = "full")] -pub fn visit_pat<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Pat) { - match *_i { - Pat::Wild(ref _binding_0) => { - _visitor.visit_pat_wild(_binding_0); - } - Pat::Ident(ref _binding_0) => { - _visitor.visit_pat_ident(_binding_0); - } - Pat::Struct(ref _binding_0) => { - _visitor.visit_pat_struct(_binding_0); - } - Pat::TupleStruct(ref _binding_0) => { - _visitor.visit_pat_tuple_struct(_binding_0); - } - Pat::Path(ref _binding_0) => { - _visitor.visit_pat_path(_binding_0); - } - Pat::Tuple(ref _binding_0) => { - _visitor.visit_pat_tuple(_binding_0); - } - Pat::Box(ref _binding_0) => { - _visitor.visit_pat_box(_binding_0); - } - Pat::Ref(ref _binding_0) => { - _visitor.visit_pat_ref(_binding_0); - } - Pat::Lit(ref _binding_0) => { - _visitor.visit_pat_lit(_binding_0); - } - Pat::Range(ref _binding_0) => { - _visitor.visit_pat_range(_binding_0); - } - Pat::Slice(ref _binding_0) => { - _visitor.visit_pat_slice(_binding_0); - } - Pat::Macro(ref _binding_0) => { - _visitor.visit_pat_macro(_binding_0); - } - Pat::Verbatim(ref _binding_0) => { - _visitor.visit_pat_verbatim(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_pat_box<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatBox) { - tokens_helper(_visitor, &_i.box_token.span); - _visitor.visit_pat(&*_i.pat); -} -#[cfg(feature = "full")] -pub fn visit_pat_ident<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatIdent) { - if let Some(ref it) = _i.by_ref { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.mutability { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_ident(&_i.ident); - if let Some(ref it) = _i.subpat { - tokens_helper(_visitor, &(it).0.spans); - _visitor.visit_pat(&*(it).1); - }; -} -#[cfg(feature = "full")] -pub fn visit_pat_lit<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatLit) { - _visitor.visit_expr(&*_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_pat_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatMacro) { - _visitor.visit_macro(&_i.mac); -} -#[cfg(feature = "full")] -pub fn visit_pat_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatPath) { - if let Some(ref it) = _i.qself { - _visitor.visit_qself(it) - }; - _visitor.visit_path(&_i.path); -} -#[cfg(feature = "full")] -pub fn visit_pat_range<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatRange) { - _visitor.visit_expr(&*_i.lo); - _visitor.visit_range_limits(&_i.limits); - _visitor.visit_expr(&*_i.hi); -} -#[cfg(feature = "full")] -pub fn visit_pat_ref<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatRef) { - tokens_helper(_visitor, &_i.and_token.spans); - if let Some(ref it) = _i.mutability { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_pat(&*_i.pat); -} -#[cfg(feature = "full")] -pub fn visit_pat_slice<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatSlice) { - tokens_helper(_visitor, &_i.bracket_token.span); - for el in Punctuated::pairs(&_i.front) { - let it = el.value(); - _visitor.visit_pat(it) - } - if let Some(ref it) = _i.middle { - _visitor.visit_pat(&**it) - }; - if let Some(ref it) = _i.dot2_token { - tokens_helper(_visitor, &it.spans) - }; - if let Some(ref it) = _i.comma_token { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.back) { - let it = el.value(); - _visitor.visit_pat(it) - } -} -#[cfg(feature = "full")] -pub fn visit_pat_struct<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatStruct) { - _visitor.visit_path(&_i.path); - tokens_helper(_visitor, &_i.brace_token.span); - for el in Punctuated::pairs(&_i.fields) { - let it = el.value(); - _visitor.visit_field_pat(it) - } - if let Some(ref it) = _i.dot2_token { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_pat_tuple<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatTuple) { - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.front) { - let it = el.value(); - _visitor.visit_pat(it) - } - if let Some(ref it) = _i.dot2_token { - tokens_helper(_visitor, &it.spans) - }; - if let Some(ref it) = _i.comma_token { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.back) { - let it = el.value(); - _visitor.visit_pat(it) - } -} -#[cfg(feature = "full")] -pub fn visit_pat_tuple_struct<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast PatTupleStruct, -) { - _visitor.visit_path(&_i.path); - _visitor.visit_pat_tuple(&_i.pat); -} -#[cfg(feature = "full")] -pub fn visit_pat_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatVerbatim) { - skip!(_i.tts); -} -#[cfg(feature = "full")] -pub fn visit_pat_wild<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatWild) { - tokens_helper(_visitor, &_i.underscore_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Path) { - if let Some(ref it) = _i.leading_colon { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.segments) { - let it = el.value(); - _visitor.visit_path_segment(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_path_arguments<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast PathArguments, -) { - match *_i { - PathArguments::None => {} - PathArguments::AngleBracketed(ref _binding_0) => { - _visitor.visit_angle_bracketed_generic_arguments(_binding_0); - } - PathArguments::Parenthesized(ref _binding_0) => { - _visitor.visit_parenthesized_generic_arguments(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_path_segment<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PathSegment) { - _visitor.visit_ident(&_i.ident); - _visitor.visit_path_arguments(&_i.arguments); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_predicate_eq<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PredicateEq) { - _visitor.visit_type(&_i.lhs_ty); - tokens_helper(_visitor, &_i.eq_token.spans); - _visitor.visit_type(&_i.rhs_ty); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_predicate_lifetime<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast PredicateLifetime, -) { - _visitor.visit_lifetime(&_i.lifetime); - tokens_helper(_visitor, &_i.colon_token.spans); - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_lifetime(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_predicate_type<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast PredicateType, -) { - if let Some(ref it) = _i.lifetimes { - _visitor.visit_bound_lifetimes(it) - }; - _visitor.visit_type(&_i.bounded_ty); - tokens_helper(_visitor, &_i.colon_token.spans); - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_qself<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast QSelf) { - tokens_helper(_visitor, &_i.lt_token.spans); - _visitor.visit_type(&*_i.ty); - skip!(_i.position); - if let Some(ref it) = _i.as_token { - tokens_helper(_visitor, &it.span) - }; - tokens_helper(_visitor, &_i.gt_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_range_limits<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast RangeLimits) { - match *_i { - RangeLimits::HalfOpen(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - RangeLimits::Closed(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_return_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ReturnType) { - match *_i { - ReturnType::Default => {} - ReturnType::Type(ref _binding_0, ref _binding_1) => { - tokens_helper(_visitor, &_binding_0.spans); - _visitor.visit_type(&**_binding_1); - } - } -} -#[cfg(feature = "full")] -pub fn visit_stmt<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Stmt) { - match *_i { - Stmt::Local(ref _binding_0) => { - _visitor.visit_local(_binding_0); - } - Stmt::Item(ref _binding_0) => { - _visitor.visit_item(_binding_0); - } - Stmt::Expr(ref _binding_0) => { - _visitor.visit_expr(_binding_0); - } - Stmt::Semi(ref _binding_0, ref _binding_1) => { - _visitor.visit_expr(_binding_0); - tokens_helper(_visitor, &_binding_1.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_trait_bound<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitBound) { - if let Some(ref it) = _i.paren_token { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_trait_bound_modifier(&_i.modifier); - if let Some(ref it) = _i.lifetimes { - _visitor.visit_bound_lifetimes(it) - }; - _visitor.visit_path(&_i.path); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_trait_bound_modifier<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TraitBoundModifier, -) { - match *_i { - TraitBoundModifier::None => {} - TraitBoundModifier::Maybe(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - } -} -#[cfg(feature = "full")] -pub fn visit_trait_item<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitItem) { - match *_i { - TraitItem::Const(ref _binding_0) => { - _visitor.visit_trait_item_const(_binding_0); - } - TraitItem::Method(ref _binding_0) => { - _visitor.visit_trait_item_method(_binding_0); - } - TraitItem::Type(ref _binding_0) => { - _visitor.visit_trait_item_type(_binding_0); - } - TraitItem::Macro(ref _binding_0) => { - _visitor.visit_trait_item_macro(_binding_0); - } - TraitItem::Verbatim(ref _binding_0) => { - _visitor.visit_trait_item_verbatim(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_trait_item_const<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TraitItemConst, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.const_token.span); - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.colon_token.spans); - _visitor.visit_type(&_i.ty); - if let Some(ref it) = _i.default { - tokens_helper(_visitor, &(it).0.spans); - _visitor.visit_expr(&(it).1); - }; - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_trait_item_macro<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TraitItemMacro, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_macro(&_i.mac); - if let Some(ref it) = _i.semi_token { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_trait_item_method<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TraitItemMethod, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_method_sig(&_i.sig); - if let Some(ref it) = _i.default { - _visitor.visit_block(it) - }; - if let Some(ref it) = _i.semi_token { - tokens_helper(_visitor, &it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_trait_item_type<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TraitItemType, -) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - tokens_helper(_visitor, &_i.type_token.span); - _visitor.visit_ident(&_i.ident); - _visitor.visit_generics(&_i.generics); - if let Some(ref it) = _i.colon_token { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } - if let Some(ref it) = _i.default { - tokens_helper(_visitor, &(it).0.spans); - _visitor.visit_type(&(it).1); - }; - tokens_helper(_visitor, &_i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_trait_item_verbatim<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TraitItemVerbatim, -) { - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Type) { - match *_i { - Type::Slice(ref _binding_0) => { - _visitor.visit_type_slice(_binding_0); - } - Type::Array(ref _binding_0) => { - _visitor.visit_type_array(_binding_0); - } - Type::Ptr(ref _binding_0) => { - _visitor.visit_type_ptr(_binding_0); - } - Type::Reference(ref _binding_0) => { - _visitor.visit_type_reference(_binding_0); - } - Type::BareFn(ref _binding_0) => { - _visitor.visit_type_bare_fn(_binding_0); - } - Type::Never(ref _binding_0) => { - _visitor.visit_type_never(_binding_0); - } - Type::Tuple(ref _binding_0) => { - _visitor.visit_type_tuple(_binding_0); - } - Type::Path(ref _binding_0) => { - _visitor.visit_type_path(_binding_0); - } - Type::TraitObject(ref _binding_0) => { - _visitor.visit_type_trait_object(_binding_0); - } - Type::ImplTrait(ref _binding_0) => { - _visitor.visit_type_impl_trait(_binding_0); - } - Type::Paren(ref _binding_0) => { - _visitor.visit_type_paren(_binding_0); - } - Type::Group(ref _binding_0) => { - _visitor.visit_type_group(_binding_0); - } - Type::Infer(ref _binding_0) => { - _visitor.visit_type_infer(_binding_0); - } - Type::Macro(ref _binding_0) => { - _visitor.visit_type_macro(_binding_0); - } - Type::Verbatim(ref _binding_0) => { - _visitor.visit_type_verbatim(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_array<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeArray) { - tokens_helper(_visitor, &_i.bracket_token.span); - _visitor.visit_type(&*_i.elem); - tokens_helper(_visitor, &_i.semi_token.spans); - _visitor.visit_expr(&_i.len); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_bare_fn<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeBareFn) { - if let Some(ref it) = _i.lifetimes { - _visitor.visit_bound_lifetimes(it) - }; - if let Some(ref it) = _i.unsafety { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.abi { - _visitor.visit_abi(it) - }; - tokens_helper(_visitor, &_i.fn_token.span); - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.inputs) { - let it = el.value(); - _visitor.visit_bare_fn_arg(it) - } - if let Some(ref it) = _i.variadic { - tokens_helper(_visitor, &it.spans) - }; - _visitor.visit_return_type(&_i.output); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_group<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeGroup) { - tokens_helper(_visitor, &_i.group_token.span); - _visitor.visit_type(&*_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_impl_trait<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TypeImplTrait, -) { - tokens_helper(_visitor, &_i.impl_token.span); - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_infer<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeInfer) { - tokens_helper(_visitor, &_i.underscore_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeMacro) { - _visitor.visit_macro(&_i.mac); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_never<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeNever) { - tokens_helper(_visitor, &_i.bang_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_param<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeParam) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_ident(&_i.ident); - if let Some(ref it) = _i.colon_token { - tokens_helper(_visitor, &it.spans) - }; - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } - if let Some(ref it) = _i.eq_token { - tokens_helper(_visitor, &it.spans) - }; - if let Some(ref it) = _i.default { - _visitor.visit_type(it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_param_bound<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TypeParamBound, -) { - match *_i { - TypeParamBound::Trait(ref _binding_0) => { - _visitor.visit_trait_bound(_binding_0); - } - TypeParamBound::Lifetime(ref _binding_0) => { - _visitor.visit_lifetime(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_paren<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeParen) { - tokens_helper(_visitor, &_i.paren_token.span); - _visitor.visit_type(&*_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypePath) { - if let Some(ref it) = _i.qself { - _visitor.visit_qself(it) - }; - _visitor.visit_path(&_i.path); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_ptr<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypePtr) { - tokens_helper(_visitor, &_i.star_token.spans); - if let Some(ref it) = _i.const_token { - tokens_helper(_visitor, &it.span) - }; - if let Some(ref it) = _i.mutability { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_type(&*_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_reference<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TypeReference, -) { - tokens_helper(_visitor, &_i.and_token.spans); - if let Some(ref it) = _i.lifetime { - _visitor.visit_lifetime(it) - }; - if let Some(ref it) = _i.mutability { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_type(&*_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_slice<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeSlice) { - tokens_helper(_visitor, &_i.bracket_token.span); - _visitor.visit_type(&*_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_trait_object<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TypeTraitObject, -) { - if let Some(ref it) = _i.dyn_token { - tokens_helper(_visitor, &it.span) - }; - for el in Punctuated::pairs(&_i.bounds) { - let it = el.value(); - _visitor.visit_type_param_bound(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_tuple<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeTuple) { - tokens_helper(_visitor, &_i.paren_token.span); - for el in Punctuated::pairs(&_i.elems) { - let it = el.value(); - _visitor.visit_type(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_verbatim<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast TypeVerbatim, -) { - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_un_op<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UnOp) { - match *_i { - UnOp::Deref(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - UnOp::Not(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - UnOp::Neg(ref _binding_0) => { - tokens_helper(_visitor, &_binding_0.spans); - } - } -} -#[cfg(feature = "full")] -pub fn visit_use_glob<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseGlob) { - tokens_helper(_visitor, &_i.star_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_use_group<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseGroup) { - tokens_helper(_visitor, &_i.brace_token.span); - for el in Punctuated::pairs(&_i.items) { - let it = el.value(); - _visitor.visit_use_tree(it) - } -} -#[cfg(feature = "full")] -pub fn visit_use_name<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseName) { - _visitor.visit_ident(&_i.ident); -} -#[cfg(feature = "full")] -pub fn visit_use_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UsePath) { - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.colon2_token.spans); - _visitor.visit_use_tree(&*_i.tree); -} -#[cfg(feature = "full")] -pub fn visit_use_rename<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseRename) { - _visitor.visit_ident(&_i.ident); - tokens_helper(_visitor, &_i.as_token.span); - _visitor.visit_ident(&_i.rename); -} -#[cfg(feature = "full")] -pub fn visit_use_tree<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseTree) { - match *_i { - UseTree::Path(ref _binding_0) => { - _visitor.visit_use_path(_binding_0); - } - UseTree::Name(ref _binding_0) => { - _visitor.visit_use_name(_binding_0); - } - UseTree::Rename(ref _binding_0) => { - _visitor.visit_use_rename(_binding_0); - } - UseTree::Glob(ref _binding_0) => { - _visitor.visit_use_glob(_binding_0); - } - UseTree::Group(ref _binding_0) => { - _visitor.visit_use_group(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_variant<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Variant) { - for it in &_i.attrs { - _visitor.visit_attribute(it) - } - _visitor.visit_ident(&_i.ident); - _visitor.visit_fields(&_i.fields); - if let Some(ref it) = _i.discriminant { - tokens_helper(_visitor, &(it).0.spans); - _visitor.visit_expr(&(it).1); - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_vis_crate<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast VisCrate) { - tokens_helper(_visitor, &_i.crate_token.span); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_vis_public<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast VisPublic) { - tokens_helper(_visitor, &_i.pub_token.span); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_vis_restricted<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast VisRestricted, -) { - tokens_helper(_visitor, &_i.pub_token.span); - tokens_helper(_visitor, &_i.paren_token.span); - if let Some(ref it) = _i.in_token { - tokens_helper(_visitor, &it.span) - }; - _visitor.visit_path(&*_i.path); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_visibility<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Visibility) { - match *_i { - Visibility::Public(ref _binding_0) => { - _visitor.visit_vis_public(_binding_0); - } - Visibility::Crate(ref _binding_0) => { - _visitor.visit_vis_crate(_binding_0); - } - Visibility::Restricted(ref _binding_0) => { - _visitor.visit_vis_restricted(_binding_0); - } - Visibility::Inherited => {} - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_where_clause<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast WhereClause) { - tokens_helper(_visitor, &_i.where_token.span); - for el in Punctuated::pairs(&_i.predicates) { - let it = el.value(); - _visitor.visit_where_predicate(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_where_predicate<'ast, V: Visit<'ast> + ?Sized>( - _visitor: &mut V, - _i: &'ast WherePredicate, -) { - match *_i { - WherePredicate::Type(ref _binding_0) => { - _visitor.visit_predicate_type(_binding_0); - } - WherePredicate::Lifetime(ref _binding_0) => { - _visitor.visit_predicate_lifetime(_binding_0); - } - WherePredicate::Eq(ref _binding_0) => { - _visitor.visit_predicate_eq(_binding_0); - } - } -} -pub fn visit_span<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Span) {} -pub fn visit_ident<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Ident) {} diff --git a/0.15.42/src/gen/visit_mut.rs b/0.15.42/src/gen/visit_mut.rs deleted file mode 100644 index d12071a0..00000000 --- a/0.15.42/src/gen/visit_mut.rs +++ /dev/null @@ -1,3279 +0,0 @@ -// This file is @generated by syn-internal-codegen. -// It is not intended for manual editing. - -#[cfg(any(feature = "full", feature = "derive"))] -use gen::helper::visit_mut::*; -use proc_macro2::Span; -#[cfg(any(feature = "full", feature = "derive"))] -use punctuated::Punctuated; -use *; -#[cfg(feature = "full")] -macro_rules! full { - ($e:expr) => { - $e - }; -} -#[cfg(all(feature = "derive", not(feature = "full")))] -macro_rules! full { - ($e:expr) => { - unreachable!() - }; -} -#[cfg(any(feature = "full", feature = "derive"))] -macro_rules! skip { - ($($tt:tt)*) => {}; -} -/// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in -/// place. -/// -/// See the [module documentation] for details. -/// -/// [module documentation]: self -/// -/// *This trait is available if Syn is built with the `"visit-mut"` feature.* -pub trait VisitMut { - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_abi_mut(&mut self, i: &mut Abi) { - visit_abi_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_angle_bracketed_generic_arguments_mut( - &mut self, - i: &mut AngleBracketedGenericArguments, - ) { - visit_angle_bracketed_generic_arguments_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_arg_captured_mut(&mut self, i: &mut ArgCaptured) { - visit_arg_captured_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_arg_self_mut(&mut self, i: &mut ArgSelf) { - visit_arg_self_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_arg_self_ref_mut(&mut self, i: &mut ArgSelfRef) { - visit_arg_self_ref_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_arm_mut(&mut self, i: &mut Arm) { - visit_arm_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_attr_style_mut(&mut self, i: &mut AttrStyle) { - visit_attr_style_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_attribute_mut(&mut self, i: &mut Attribute) { - visit_attribute_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_bare_fn_arg_mut(&mut self, i: &mut BareFnArg) { - visit_bare_fn_arg_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_bare_fn_arg_name_mut(&mut self, i: &mut BareFnArgName) { - visit_bare_fn_arg_name_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_bin_op_mut(&mut self, i: &mut BinOp) { - visit_bin_op_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_binding_mut(&mut self, i: &mut Binding) { - visit_binding_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_block_mut(&mut self, i: &mut Block) { - visit_block_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_bound_lifetimes_mut(&mut self, i: &mut BoundLifetimes) { - visit_bound_lifetimes_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_const_param_mut(&mut self, i: &mut ConstParam) { - visit_const_param_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_constraint_mut(&mut self, i: &mut Constraint) { - visit_constraint_mut(self, i) - } - #[cfg(feature = "derive")] - fn visit_data_mut(&mut self, i: &mut Data) { - visit_data_mut(self, i) - } - #[cfg(feature = "derive")] - fn visit_data_enum_mut(&mut self, i: &mut DataEnum) { - visit_data_enum_mut(self, i) - } - #[cfg(feature = "derive")] - fn visit_data_struct_mut(&mut self, i: &mut DataStruct) { - visit_data_struct_mut(self, i) - } - #[cfg(feature = "derive")] - fn visit_data_union_mut(&mut self, i: &mut DataUnion) { - visit_data_union_mut(self, i) - } - #[cfg(feature = "derive")] - fn visit_derive_input_mut(&mut self, i: &mut DeriveInput) { - visit_derive_input_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_mut(&mut self, i: &mut Expr) { - visit_expr_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_array_mut(&mut self, i: &mut ExprArray) { - visit_expr_array_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_assign_mut(&mut self, i: &mut ExprAssign) { - visit_expr_assign_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_assign_op_mut(&mut self, i: &mut ExprAssignOp) { - visit_expr_assign_op_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_async_mut(&mut self, i: &mut ExprAsync) { - visit_expr_async_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_binary_mut(&mut self, i: &mut ExprBinary) { - visit_expr_binary_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_block_mut(&mut self, i: &mut ExprBlock) { - visit_expr_block_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_box_mut(&mut self, i: &mut ExprBox) { - visit_expr_box_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_break_mut(&mut self, i: &mut ExprBreak) { - visit_expr_break_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_call_mut(&mut self, i: &mut ExprCall) { - visit_expr_call_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_cast_mut(&mut self, i: &mut ExprCast) { - visit_expr_cast_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_closure_mut(&mut self, i: &mut ExprClosure) { - visit_expr_closure_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_continue_mut(&mut self, i: &mut ExprContinue) { - visit_expr_continue_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_field_mut(&mut self, i: &mut ExprField) { - visit_expr_field_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_for_loop_mut(&mut self, i: &mut ExprForLoop) { - visit_expr_for_loop_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_group_mut(&mut self, i: &mut ExprGroup) { - visit_expr_group_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_if_mut(&mut self, i: &mut ExprIf) { - visit_expr_if_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_in_place_mut(&mut self, i: &mut ExprInPlace) { - visit_expr_in_place_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_index_mut(&mut self, i: &mut ExprIndex) { - visit_expr_index_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_let_mut(&mut self, i: &mut ExprLet) { - visit_expr_let_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_lit_mut(&mut self, i: &mut ExprLit) { - visit_expr_lit_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_loop_mut(&mut self, i: &mut ExprLoop) { - visit_expr_loop_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_macro_mut(&mut self, i: &mut ExprMacro) { - visit_expr_macro_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_match_mut(&mut self, i: &mut ExprMatch) { - visit_expr_match_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_method_call_mut(&mut self, i: &mut ExprMethodCall) { - visit_expr_method_call_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_paren_mut(&mut self, i: &mut ExprParen) { - visit_expr_paren_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_path_mut(&mut self, i: &mut ExprPath) { - visit_expr_path_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_range_mut(&mut self, i: &mut ExprRange) { - visit_expr_range_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_reference_mut(&mut self, i: &mut ExprReference) { - visit_expr_reference_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_repeat_mut(&mut self, i: &mut ExprRepeat) { - visit_expr_repeat_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_return_mut(&mut self, i: &mut ExprReturn) { - visit_expr_return_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_struct_mut(&mut self, i: &mut ExprStruct) { - visit_expr_struct_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_try_mut(&mut self, i: &mut ExprTry) { - visit_expr_try_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_try_block_mut(&mut self, i: &mut ExprTryBlock) { - visit_expr_try_block_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_tuple_mut(&mut self, i: &mut ExprTuple) { - visit_expr_tuple_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_type_mut(&mut self, i: &mut ExprType) { - visit_expr_type_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_unary_mut(&mut self, i: &mut ExprUnary) { - visit_expr_unary_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_unsafe_mut(&mut self, i: &mut ExprUnsafe) { - visit_expr_unsafe_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_expr_verbatim_mut(&mut self, i: &mut ExprVerbatim) { - visit_expr_verbatim_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_while_mut(&mut self, i: &mut ExprWhile) { - visit_expr_while_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_expr_yield_mut(&mut self, i: &mut ExprYield) { - visit_expr_yield_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_field_mut(&mut self, i: &mut Field) { - visit_field_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_field_pat_mut(&mut self, i: &mut FieldPat) { - visit_field_pat_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_field_value_mut(&mut self, i: &mut FieldValue) { - visit_field_value_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_fields_mut(&mut self, i: &mut Fields) { - visit_fields_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_fields_named_mut(&mut self, i: &mut FieldsNamed) { - visit_fields_named_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_fields_unnamed_mut(&mut self, i: &mut FieldsUnnamed) { - visit_fields_unnamed_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_file_mut(&mut self, i: &mut File) { - visit_file_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_fn_arg_mut(&mut self, i: &mut FnArg) { - visit_fn_arg_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_fn_decl_mut(&mut self, i: &mut FnDecl) { - visit_fn_decl_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_mut(&mut self, i: &mut ForeignItem) { - visit_foreign_item_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_fn_mut(&mut self, i: &mut ForeignItemFn) { - visit_foreign_item_fn_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_macro_mut(&mut self, i: &mut ForeignItemMacro) { - visit_foreign_item_macro_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_static_mut(&mut self, i: &mut ForeignItemStatic) { - visit_foreign_item_static_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_type_mut(&mut self, i: &mut ForeignItemType) { - visit_foreign_item_type_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_foreign_item_verbatim_mut(&mut self, i: &mut ForeignItemVerbatim) { - visit_foreign_item_verbatim_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_generic_argument_mut(&mut self, i: &mut GenericArgument) { - visit_generic_argument_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_generic_method_argument_mut(&mut self, i: &mut GenericMethodArgument) { - visit_generic_method_argument_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_generic_param_mut(&mut self, i: &mut GenericParam) { - visit_generic_param_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_generics_mut(&mut self, i: &mut Generics) { - visit_generics_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_mut(&mut self, i: &mut ImplItem) { - visit_impl_item_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_const_mut(&mut self, i: &mut ImplItemConst) { - visit_impl_item_const_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_existential_mut(&mut self, i: &mut ImplItemExistential) { - visit_impl_item_existential_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_macro_mut(&mut self, i: &mut ImplItemMacro) { - visit_impl_item_macro_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_method_mut(&mut self, i: &mut ImplItemMethod) { - visit_impl_item_method_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_type_mut(&mut self, i: &mut ImplItemType) { - visit_impl_item_type_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_impl_item_verbatim_mut(&mut self, i: &mut ImplItemVerbatim) { - visit_impl_item_verbatim_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_index_mut(&mut self, i: &mut Index) { - visit_index_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_mut(&mut self, i: &mut Item) { - visit_item_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_const_mut(&mut self, i: &mut ItemConst) { - visit_item_const_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_enum_mut(&mut self, i: &mut ItemEnum) { - visit_item_enum_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_existential_mut(&mut self, i: &mut ItemExistential) { - visit_item_existential_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_extern_crate_mut(&mut self, i: &mut ItemExternCrate) { - visit_item_extern_crate_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_fn_mut(&mut self, i: &mut ItemFn) { - visit_item_fn_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_foreign_mod_mut(&mut self, i: &mut ItemForeignMod) { - visit_item_foreign_mod_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_impl_mut(&mut self, i: &mut ItemImpl) { - visit_item_impl_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_macro_mut(&mut self, i: &mut ItemMacro) { - visit_item_macro_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_macro2_mut(&mut self, i: &mut ItemMacro2) { - visit_item_macro2_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_mod_mut(&mut self, i: &mut ItemMod) { - visit_item_mod_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_static_mut(&mut self, i: &mut ItemStatic) { - visit_item_static_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_struct_mut(&mut self, i: &mut ItemStruct) { - visit_item_struct_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_trait_mut(&mut self, i: &mut ItemTrait) { - visit_item_trait_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_trait_alias_mut(&mut self, i: &mut ItemTraitAlias) { - visit_item_trait_alias_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_type_mut(&mut self, i: &mut ItemType) { - visit_item_type_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_union_mut(&mut self, i: &mut ItemUnion) { - visit_item_union_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_use_mut(&mut self, i: &mut ItemUse) { - visit_item_use_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_item_verbatim_mut(&mut self, i: &mut ItemVerbatim) { - visit_item_verbatim_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_label_mut(&mut self, i: &mut Label) { - visit_label_mut(self, i) - } - fn visit_lifetime_mut(&mut self, i: &mut Lifetime) { - visit_lifetime_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lifetime_def_mut(&mut self, i: &mut LifetimeDef) { - visit_lifetime_def_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_mut(&mut self, i: &mut Lit) { - visit_lit_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_bool_mut(&mut self, i: &mut LitBool) { - visit_lit_bool_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_byte_mut(&mut self, i: &mut LitByte) { - visit_lit_byte_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_byte_str_mut(&mut self, i: &mut LitByteStr) { - visit_lit_byte_str_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_char_mut(&mut self, i: &mut LitChar) { - visit_lit_char_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_float_mut(&mut self, i: &mut LitFloat) { - visit_lit_float_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_int_mut(&mut self, i: &mut LitInt) { - visit_lit_int_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_str_mut(&mut self, i: &mut LitStr) { - visit_lit_str_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_lit_verbatim_mut(&mut self, i: &mut LitVerbatim) { - visit_lit_verbatim_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_local_mut(&mut self, i: &mut Local) { - visit_local_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_macro_mut(&mut self, i: &mut Macro) { - visit_macro_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_macro_delimiter_mut(&mut self, i: &mut MacroDelimiter) { - visit_macro_delimiter_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_member_mut(&mut self, i: &mut Member) { - visit_member_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_meta_mut(&mut self, i: &mut Meta) { - visit_meta_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_meta_list_mut(&mut self, i: &mut MetaList) { - visit_meta_list_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_meta_name_value_mut(&mut self, i: &mut MetaNameValue) { - visit_meta_name_value_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_method_sig_mut(&mut self, i: &mut MethodSig) { - visit_method_sig_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_method_turbofish_mut(&mut self, i: &mut MethodTurbofish) { - visit_method_turbofish_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_nested_meta_mut(&mut self, i: &mut NestedMeta) { - visit_nested_meta_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_parenthesized_generic_arguments_mut(&mut self, i: &mut ParenthesizedGenericArguments) { - visit_parenthesized_generic_arguments_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_mut(&mut self, i: &mut Pat) { - visit_pat_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_box_mut(&mut self, i: &mut PatBox) { - visit_pat_box_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_ident_mut(&mut self, i: &mut PatIdent) { - visit_pat_ident_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_lit_mut(&mut self, i: &mut PatLit) { - visit_pat_lit_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_macro_mut(&mut self, i: &mut PatMacro) { - visit_pat_macro_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_path_mut(&mut self, i: &mut PatPath) { - visit_pat_path_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_range_mut(&mut self, i: &mut PatRange) { - visit_pat_range_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_ref_mut(&mut self, i: &mut PatRef) { - visit_pat_ref_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_slice_mut(&mut self, i: &mut PatSlice) { - visit_pat_slice_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_struct_mut(&mut self, i: &mut PatStruct) { - visit_pat_struct_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_tuple_mut(&mut self, i: &mut PatTuple) { - visit_pat_tuple_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_tuple_struct_mut(&mut self, i: &mut PatTupleStruct) { - visit_pat_tuple_struct_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_verbatim_mut(&mut self, i: &mut PatVerbatim) { - visit_pat_verbatim_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_pat_wild_mut(&mut self, i: &mut PatWild) { - visit_pat_wild_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_path_mut(&mut self, i: &mut Path) { - visit_path_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_path_arguments_mut(&mut self, i: &mut PathArguments) { - visit_path_arguments_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_path_segment_mut(&mut self, i: &mut PathSegment) { - visit_path_segment_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_predicate_eq_mut(&mut self, i: &mut PredicateEq) { - visit_predicate_eq_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_predicate_lifetime_mut(&mut self, i: &mut PredicateLifetime) { - visit_predicate_lifetime_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_predicate_type_mut(&mut self, i: &mut PredicateType) { - visit_predicate_type_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_qself_mut(&mut self, i: &mut QSelf) { - visit_qself_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_range_limits_mut(&mut self, i: &mut RangeLimits) { - visit_range_limits_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_return_type_mut(&mut self, i: &mut ReturnType) { - visit_return_type_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_stmt_mut(&mut self, i: &mut Stmt) { - visit_stmt_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_trait_bound_mut(&mut self, i: &mut TraitBound) { - visit_trait_bound_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_trait_bound_modifier_mut(&mut self, i: &mut TraitBoundModifier) { - visit_trait_bound_modifier_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_mut(&mut self, i: &mut TraitItem) { - visit_trait_item_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_const_mut(&mut self, i: &mut TraitItemConst) { - visit_trait_item_const_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_macro_mut(&mut self, i: &mut TraitItemMacro) { - visit_trait_item_macro_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_method_mut(&mut self, i: &mut TraitItemMethod) { - visit_trait_item_method_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_type_mut(&mut self, i: &mut TraitItemType) { - visit_trait_item_type_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_trait_item_verbatim_mut(&mut self, i: &mut TraitItemVerbatim) { - visit_trait_item_verbatim_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_mut(&mut self, i: &mut Type) { - visit_type_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_array_mut(&mut self, i: &mut TypeArray) { - visit_type_array_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_bare_fn_mut(&mut self, i: &mut TypeBareFn) { - visit_type_bare_fn_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_group_mut(&mut self, i: &mut TypeGroup) { - visit_type_group_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_impl_trait_mut(&mut self, i: &mut TypeImplTrait) { - visit_type_impl_trait_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_infer_mut(&mut self, i: &mut TypeInfer) { - visit_type_infer_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_macro_mut(&mut self, i: &mut TypeMacro) { - visit_type_macro_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_never_mut(&mut self, i: &mut TypeNever) { - visit_type_never_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_param_mut(&mut self, i: &mut TypeParam) { - visit_type_param_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_param_bound_mut(&mut self, i: &mut TypeParamBound) { - visit_type_param_bound_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_paren_mut(&mut self, i: &mut TypeParen) { - visit_type_paren_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_path_mut(&mut self, i: &mut TypePath) { - visit_type_path_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_ptr_mut(&mut self, i: &mut TypePtr) { - visit_type_ptr_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_reference_mut(&mut self, i: &mut TypeReference) { - visit_type_reference_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_slice_mut(&mut self, i: &mut TypeSlice) { - visit_type_slice_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_trait_object_mut(&mut self, i: &mut TypeTraitObject) { - visit_type_trait_object_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_tuple_mut(&mut self, i: &mut TypeTuple) { - visit_type_tuple_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_type_verbatim_mut(&mut self, i: &mut TypeVerbatim) { - visit_type_verbatim_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_un_op_mut(&mut self, i: &mut UnOp) { - visit_un_op_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_use_glob_mut(&mut self, i: &mut UseGlob) { - visit_use_glob_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_use_group_mut(&mut self, i: &mut UseGroup) { - visit_use_group_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_use_name_mut(&mut self, i: &mut UseName) { - visit_use_name_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_use_path_mut(&mut self, i: &mut UsePath) { - visit_use_path_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_use_rename_mut(&mut self, i: &mut UseRename) { - visit_use_rename_mut(self, i) - } - #[cfg(feature = "full")] - fn visit_use_tree_mut(&mut self, i: &mut UseTree) { - visit_use_tree_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_variant_mut(&mut self, i: &mut Variant) { - visit_variant_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_vis_crate_mut(&mut self, i: &mut VisCrate) { - visit_vis_crate_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_vis_public_mut(&mut self, i: &mut VisPublic) { - visit_vis_public_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_vis_restricted_mut(&mut self, i: &mut VisRestricted) { - visit_vis_restricted_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_visibility_mut(&mut self, i: &mut Visibility) { - visit_visibility_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_where_clause_mut(&mut self, i: &mut WhereClause) { - visit_where_clause_mut(self, i) - } - #[cfg(any(feature = "derive", feature = "full"))] - fn visit_where_predicate_mut(&mut self, i: &mut WherePredicate) { - visit_where_predicate_mut(self, i) - } - fn visit_span_mut(&mut self, i: &mut Span) { - visit_span_mut(self, i) - } - fn visit_ident_mut(&mut self, i: &mut Ident) { - visit_ident_mut(self, i) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_abi_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Abi) { - tokens_helper(_visitor, &mut _i.extern_token.span); - if let Some(ref mut it) = _i.name { - _visitor.visit_lit_str_mut(it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_angle_bracketed_generic_arguments_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut AngleBracketedGenericArguments, -) { - if let Some(ref mut it) = _i.colon2_token { - tokens_helper(_visitor, &mut it.spans) - }; - tokens_helper(_visitor, &mut _i.lt_token.spans); - for mut el in Punctuated::pairs_mut(&mut _i.args) { - let it = el.value_mut(); - _visitor.visit_generic_argument_mut(it) - } - tokens_helper(_visitor, &mut _i.gt_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_arg_captured_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ArgCaptured) { - _visitor.visit_pat_mut(&mut _i.pat); - tokens_helper(_visitor, &mut _i.colon_token.spans); - _visitor.visit_type_mut(&mut _i.ty); -} -#[cfg(feature = "full")] -pub fn visit_arg_self_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ArgSelf) { - if let Some(ref mut it) = _i.mutability { - tokens_helper(_visitor, &mut it.span) - }; - tokens_helper(_visitor, &mut _i.self_token.span); -} -#[cfg(feature = "full")] -pub fn visit_arg_self_ref_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ArgSelfRef) { - tokens_helper(_visitor, &mut _i.and_token.spans); - if let Some(ref mut it) = _i.lifetime { - _visitor.visit_lifetime_mut(it) - }; - if let Some(ref mut it) = _i.mutability { - tokens_helper(_visitor, &mut it.span) - }; - tokens_helper(_visitor, &mut _i.self_token.span); -} -#[cfg(feature = "full")] -pub fn visit_arm_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Arm) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.leading_vert { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.pats) { - let it = el.value_mut(); - _visitor.visit_pat_mut(it) - } - if let Some(ref mut it) = _i.guard { - tokens_helper(_visitor, &mut (it).0.span); - _visitor.visit_expr_mut(&mut *(it).1); - }; - tokens_helper(_visitor, &mut _i.fat_arrow_token.spans); - _visitor.visit_expr_mut(&mut *_i.body); - if let Some(ref mut it) = _i.comma { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_attr_style_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut AttrStyle) { - match *_i { - AttrStyle::Outer => {} - AttrStyle::Inner(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_attribute_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Attribute) { - tokens_helper(_visitor, &mut _i.pound_token.spans); - _visitor.visit_attr_style_mut(&mut _i.style); - tokens_helper(_visitor, &mut _i.bracket_token.span); - _visitor.visit_path_mut(&mut _i.path); - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_bare_fn_arg_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut BareFnArg) { - if let Some(ref mut it) = _i.name { - _visitor.visit_bare_fn_arg_name_mut(&mut (it).0); - tokens_helper(_visitor, &mut (it).1.spans); - }; - _visitor.visit_type_mut(&mut _i.ty); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_bare_fn_arg_name_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut BareFnArgName) { - match *_i { - BareFnArgName::Named(ref mut _binding_0) => { - _visitor.visit_ident_mut(_binding_0); - } - BareFnArgName::Wild(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_bin_op_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut BinOp) { - match *_i { - BinOp::Add(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Sub(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Mul(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Div(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Rem(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::And(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Or(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::BitXor(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::BitAnd(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::BitOr(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Shl(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Shr(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Eq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Lt(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Le(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Ne(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Ge(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::Gt(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::AddEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::SubEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::MulEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::DivEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::RemEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::BitXorEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::BitAndEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::BitOrEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::ShlEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - BinOp::ShrEq(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_binding_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Binding) { - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_type_mut(&mut _i.ty); -} -#[cfg(feature = "full")] -pub fn visit_block_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Block) { - tokens_helper(_visitor, &mut _i.brace_token.span); - for it in &mut _i.stmts { - _visitor.visit_stmt_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_bound_lifetimes_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut BoundLifetimes) { - tokens_helper(_visitor, &mut _i.for_token.span); - tokens_helper(_visitor, &mut _i.lt_token.spans); - for mut el in Punctuated::pairs_mut(&mut _i.lifetimes) { - let it = el.value_mut(); - _visitor.visit_lifetime_def_mut(it) - } - tokens_helper(_visitor, &mut _i.gt_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_const_param_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ConstParam) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.const_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.colon_token.spans); - _visitor.visit_type_mut(&mut _i.ty); - if let Some(ref mut it) = _i.eq_token { - tokens_helper(_visitor, &mut it.spans) - }; - if let Some(ref mut it) = _i.default { - _visitor.visit_expr_mut(it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_constraint_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Constraint) { - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.colon_token.spans); - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } -} -#[cfg(feature = "derive")] -pub fn visit_data_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Data) { - match *_i { - Data::Struct(ref mut _binding_0) => { - _visitor.visit_data_struct_mut(_binding_0); - } - Data::Enum(ref mut _binding_0) => { - _visitor.visit_data_enum_mut(_binding_0); - } - Data::Union(ref mut _binding_0) => { - _visitor.visit_data_union_mut(_binding_0); - } - } -} -#[cfg(feature = "derive")] -pub fn visit_data_enum_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut DataEnum) { - tokens_helper(_visitor, &mut _i.enum_token.span); - tokens_helper(_visitor, &mut _i.brace_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.variants) { - let it = el.value_mut(); - _visitor.visit_variant_mut(it) - } -} -#[cfg(feature = "derive")] -pub fn visit_data_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut DataStruct) { - tokens_helper(_visitor, &mut _i.struct_token.span); - _visitor.visit_fields_mut(&mut _i.fields); - if let Some(ref mut it) = _i.semi_token { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(feature = "derive")] -pub fn visit_data_union_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut DataUnion) { - tokens_helper(_visitor, &mut _i.union_token.span); - _visitor.visit_fields_named_mut(&mut _i.fields); -} -#[cfg(feature = "derive")] -pub fn visit_derive_input_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut DeriveInput) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - _visitor.visit_data_mut(&mut _i.data); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Expr) { - match *_i { - Expr::Box(ref mut _binding_0) => { - full!(_visitor.visit_expr_box_mut(_binding_0)); - } - Expr::InPlace(ref mut _binding_0) => { - full!(_visitor.visit_expr_in_place_mut(_binding_0)); - } - Expr::Array(ref mut _binding_0) => { - full!(_visitor.visit_expr_array_mut(_binding_0)); - } - Expr::Call(ref mut _binding_0) => { - _visitor.visit_expr_call_mut(_binding_0); - } - Expr::MethodCall(ref mut _binding_0) => { - full!(_visitor.visit_expr_method_call_mut(_binding_0)); - } - Expr::Tuple(ref mut _binding_0) => { - full!(_visitor.visit_expr_tuple_mut(_binding_0)); - } - Expr::Binary(ref mut _binding_0) => { - _visitor.visit_expr_binary_mut(_binding_0); - } - Expr::Unary(ref mut _binding_0) => { - _visitor.visit_expr_unary_mut(_binding_0); - } - Expr::Lit(ref mut _binding_0) => { - _visitor.visit_expr_lit_mut(_binding_0); - } - Expr::Cast(ref mut _binding_0) => { - _visitor.visit_expr_cast_mut(_binding_0); - } - Expr::Type(ref mut _binding_0) => { - full!(_visitor.visit_expr_type_mut(_binding_0)); - } - Expr::Let(ref mut _binding_0) => { - full!(_visitor.visit_expr_let_mut(_binding_0)); - } - Expr::If(ref mut _binding_0) => { - full!(_visitor.visit_expr_if_mut(_binding_0)); - } - Expr::While(ref mut _binding_0) => { - full!(_visitor.visit_expr_while_mut(_binding_0)); - } - Expr::ForLoop(ref mut _binding_0) => { - full!(_visitor.visit_expr_for_loop_mut(_binding_0)); - } - Expr::Loop(ref mut _binding_0) => { - full!(_visitor.visit_expr_loop_mut(_binding_0)); - } - Expr::Match(ref mut _binding_0) => { - full!(_visitor.visit_expr_match_mut(_binding_0)); - } - Expr::Closure(ref mut _binding_0) => { - full!(_visitor.visit_expr_closure_mut(_binding_0)); - } - Expr::Unsafe(ref mut _binding_0) => { - full!(_visitor.visit_expr_unsafe_mut(_binding_0)); - } - Expr::Block(ref mut _binding_0) => { - full!(_visitor.visit_expr_block_mut(_binding_0)); - } - Expr::Assign(ref mut _binding_0) => { - full!(_visitor.visit_expr_assign_mut(_binding_0)); - } - Expr::AssignOp(ref mut _binding_0) => { - full!(_visitor.visit_expr_assign_op_mut(_binding_0)); - } - Expr::Field(ref mut _binding_0) => { - _visitor.visit_expr_field_mut(_binding_0); - } - Expr::Index(ref mut _binding_0) => { - _visitor.visit_expr_index_mut(_binding_0); - } - Expr::Range(ref mut _binding_0) => { - full!(_visitor.visit_expr_range_mut(_binding_0)); - } - Expr::Path(ref mut _binding_0) => { - _visitor.visit_expr_path_mut(_binding_0); - } - Expr::Reference(ref mut _binding_0) => { - full!(_visitor.visit_expr_reference_mut(_binding_0)); - } - Expr::Break(ref mut _binding_0) => { - full!(_visitor.visit_expr_break_mut(_binding_0)); - } - Expr::Continue(ref mut _binding_0) => { - full!(_visitor.visit_expr_continue_mut(_binding_0)); - } - Expr::Return(ref mut _binding_0) => { - full!(_visitor.visit_expr_return_mut(_binding_0)); - } - Expr::Macro(ref mut _binding_0) => { - full!(_visitor.visit_expr_macro_mut(_binding_0)); - } - Expr::Struct(ref mut _binding_0) => { - full!(_visitor.visit_expr_struct_mut(_binding_0)); - } - Expr::Repeat(ref mut _binding_0) => { - full!(_visitor.visit_expr_repeat_mut(_binding_0)); - } - Expr::Paren(ref mut _binding_0) => { - _visitor.visit_expr_paren_mut(_binding_0); - } - Expr::Group(ref mut _binding_0) => { - full!(_visitor.visit_expr_group_mut(_binding_0)); - } - Expr::Try(ref mut _binding_0) => { - full!(_visitor.visit_expr_try_mut(_binding_0)); - } - Expr::Async(ref mut _binding_0) => { - full!(_visitor.visit_expr_async_mut(_binding_0)); - } - Expr::TryBlock(ref mut _binding_0) => { - full!(_visitor.visit_expr_try_block_mut(_binding_0)); - } - Expr::Yield(ref mut _binding_0) => { - full!(_visitor.visit_expr_yield_mut(_binding_0)); - } - Expr::Verbatim(ref mut _binding_0) => { - _visitor.visit_expr_verbatim_mut(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_expr_array_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprArray) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.bracket_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.elems) { - let it = el.value_mut(); - _visitor.visit_expr_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_expr_assign_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprAssign) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.left); - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_expr_mut(&mut *_i.right); -} -#[cfg(feature = "full")] -pub fn visit_expr_assign_op_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprAssignOp) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.left); - _visitor.visit_bin_op_mut(&mut _i.op); - _visitor.visit_expr_mut(&mut *_i.right); -} -#[cfg(feature = "full")] -pub fn visit_expr_async_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprAsync) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.async_token.span); - if let Some(ref mut it) = _i.capture { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_block_mut(&mut _i.block); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_binary_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprBinary) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.left); - _visitor.visit_bin_op_mut(&mut _i.op); - _visitor.visit_expr_mut(&mut *_i.right); -} -#[cfg(feature = "full")] -pub fn visit_expr_block_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprBlock) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.label { - _visitor.visit_label_mut(it) - }; - _visitor.visit_block_mut(&mut _i.block); -} -#[cfg(feature = "full")] -pub fn visit_expr_box_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprBox) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.box_token.span); - _visitor.visit_expr_mut(&mut *_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_expr_break_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprBreak) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.break_token.span); - if let Some(ref mut it) = _i.label { - _visitor.visit_lifetime_mut(it) - }; - if let Some(ref mut it) = _i.expr { - _visitor.visit_expr_mut(&mut **it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_call_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprCall) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.func); - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.args) { - let it = el.value_mut(); - _visitor.visit_expr_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_cast_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprCast) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.expr); - tokens_helper(_visitor, &mut _i.as_token.span); - _visitor.visit_type_mut(&mut *_i.ty); -} -#[cfg(feature = "full")] -pub fn visit_expr_closure_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprClosure) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.asyncness { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.movability { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.capture { - tokens_helper(_visitor, &mut it.span) - }; - tokens_helper(_visitor, &mut _i.or1_token.spans); - for mut el in Punctuated::pairs_mut(&mut _i.inputs) { - let it = el.value_mut(); - _visitor.visit_fn_arg_mut(it) - } - tokens_helper(_visitor, &mut _i.or2_token.spans); - _visitor.visit_return_type_mut(&mut _i.output); - _visitor.visit_expr_mut(&mut *_i.body); -} -#[cfg(feature = "full")] -pub fn visit_expr_continue_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprContinue) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.continue_token.span); - if let Some(ref mut it) = _i.label { - _visitor.visit_lifetime_mut(it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_field_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprField) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.base); - tokens_helper(_visitor, &mut _i.dot_token.spans); - _visitor.visit_member_mut(&mut _i.member); -} -#[cfg(feature = "full")] -pub fn visit_expr_for_loop_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprForLoop) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.label { - _visitor.visit_label_mut(it) - }; - tokens_helper(_visitor, &mut _i.for_token.span); - _visitor.visit_pat_mut(&mut *_i.pat); - tokens_helper(_visitor, &mut _i.in_token.span); - _visitor.visit_expr_mut(&mut *_i.expr); - _visitor.visit_block_mut(&mut _i.body); -} -#[cfg(feature = "full")] -pub fn visit_expr_group_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprGroup) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.group_token.span); - _visitor.visit_expr_mut(&mut *_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_expr_if_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprIf) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.if_token.span); - _visitor.visit_expr_mut(&mut *_i.cond); - _visitor.visit_block_mut(&mut _i.then_branch); - if let Some(ref mut it) = _i.else_branch { - tokens_helper(_visitor, &mut (it).0.span); - _visitor.visit_expr_mut(&mut *(it).1); - }; -} -#[cfg(feature = "full")] -pub fn visit_expr_in_place_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprInPlace) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.place); - tokens_helper(_visitor, &mut _i.arrow_token.spans); - _visitor.visit_expr_mut(&mut *_i.value); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_index_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprIndex) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.expr); - tokens_helper(_visitor, &mut _i.bracket_token.span); - _visitor.visit_expr_mut(&mut *_i.index); -} -#[cfg(feature = "full")] -pub fn visit_expr_let_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprLet) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.let_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.pats) { - let it = el.value_mut(); - _visitor.visit_pat_mut(it) - } - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_expr_mut(&mut *_i.expr); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_lit_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprLit) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_lit_mut(&mut _i.lit); -} -#[cfg(feature = "full")] -pub fn visit_expr_loop_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprLoop) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.label { - _visitor.visit_label_mut(it) - }; - tokens_helper(_visitor, &mut _i.loop_token.span); - _visitor.visit_block_mut(&mut _i.body); -} -#[cfg(feature = "full")] -pub fn visit_expr_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprMacro) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_macro_mut(&mut _i.mac); -} -#[cfg(feature = "full")] -pub fn visit_expr_match_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprMatch) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.match_token.span); - _visitor.visit_expr_mut(&mut *_i.expr); - tokens_helper(_visitor, &mut _i.brace_token.span); - for it in &mut _i.arms { - _visitor.visit_arm_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_expr_method_call_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprMethodCall) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.receiver); - tokens_helper(_visitor, &mut _i.dot_token.spans); - _visitor.visit_ident_mut(&mut _i.method); - if let Some(ref mut it) = _i.turbofish { - _visitor.visit_method_turbofish_mut(it) - }; - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.args) { - let it = el.value_mut(); - _visitor.visit_expr_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_paren_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprParen) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.paren_token.span); - _visitor.visit_expr_mut(&mut *_i.expr); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprPath) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.qself { - _visitor.visit_qself_mut(it) - }; - _visitor.visit_path_mut(&mut _i.path); -} -#[cfg(feature = "full")] -pub fn visit_expr_range_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprRange) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.from { - _visitor.visit_expr_mut(&mut **it) - }; - _visitor.visit_range_limits_mut(&mut _i.limits); - if let Some(ref mut it) = _i.to { - _visitor.visit_expr_mut(&mut **it) - }; -} -#[cfg(feature = "full")] -pub fn visit_expr_reference_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprReference) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.and_token.spans); - if let Some(ref mut it) = _i.mutability { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_expr_mut(&mut *_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_expr_repeat_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprRepeat) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.bracket_token.span); - _visitor.visit_expr_mut(&mut *_i.expr); - tokens_helper(_visitor, &mut _i.semi_token.spans); - _visitor.visit_expr_mut(&mut *_i.len); -} -#[cfg(feature = "full")] -pub fn visit_expr_return_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprReturn) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.return_token.span); - if let Some(ref mut it) = _i.expr { - _visitor.visit_expr_mut(&mut **it) - }; -} -#[cfg(feature = "full")] -pub fn visit_expr_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprStruct) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_path_mut(&mut _i.path); - tokens_helper(_visitor, &mut _i.brace_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.fields) { - let it = el.value_mut(); - _visitor.visit_field_value_mut(it) - } - if let Some(ref mut it) = _i.dot2_token { - tokens_helper(_visitor, &mut it.spans) - }; - if let Some(ref mut it) = _i.rest { - _visitor.visit_expr_mut(&mut **it) - }; -} -#[cfg(feature = "full")] -pub fn visit_expr_try_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprTry) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.expr); - tokens_helper(_visitor, &mut _i.question_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_expr_try_block_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprTryBlock) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.try_token.span); - _visitor.visit_block_mut(&mut _i.block); -} -#[cfg(feature = "full")] -pub fn visit_expr_tuple_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprTuple) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.elems) { - let it = el.value_mut(); - _visitor.visit_expr_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_expr_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprType) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_expr_mut(&mut *_i.expr); - tokens_helper(_visitor, &mut _i.colon_token.spans); - _visitor.visit_type_mut(&mut *_i.ty); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_unary_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprUnary) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_un_op_mut(&mut _i.op); - _visitor.visit_expr_mut(&mut *_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_expr_unsafe_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprUnsafe) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.unsafe_token.span); - _visitor.visit_block_mut(&mut _i.block); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_expr_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprVerbatim) { - skip!(_i.tts); -} -#[cfg(feature = "full")] -pub fn visit_expr_while_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprWhile) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.label { - _visitor.visit_label_mut(it) - }; - tokens_helper(_visitor, &mut _i.while_token.span); - _visitor.visit_expr_mut(&mut *_i.cond); - _visitor.visit_block_mut(&mut _i.body); -} -#[cfg(feature = "full")] -pub fn visit_expr_yield_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprYield) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.yield_token.span); - if let Some(ref mut it) = _i.expr { - _visitor.visit_expr_mut(&mut **it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_field_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Field) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - if let Some(ref mut it) = _i.ident { - _visitor.visit_ident_mut(it) - }; - if let Some(ref mut it) = _i.colon_token { - tokens_helper(_visitor, &mut it.spans) - }; - _visitor.visit_type_mut(&mut _i.ty); -} -#[cfg(feature = "full")] -pub fn visit_field_pat_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FieldPat) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_member_mut(&mut _i.member); - if let Some(ref mut it) = _i.colon_token { - tokens_helper(_visitor, &mut it.spans) - }; - _visitor.visit_pat_mut(&mut *_i.pat); -} -#[cfg(feature = "full")] -pub fn visit_field_value_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FieldValue) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_member_mut(&mut _i.member); - if let Some(ref mut it) = _i.colon_token { - tokens_helper(_visitor, &mut it.spans) - }; - _visitor.visit_expr_mut(&mut _i.expr); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_fields_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Fields) { - match *_i { - Fields::Named(ref mut _binding_0) => { - _visitor.visit_fields_named_mut(_binding_0); - } - Fields::Unnamed(ref mut _binding_0) => { - _visitor.visit_fields_unnamed_mut(_binding_0); - } - Fields::Unit => {} - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_fields_named_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FieldsNamed) { - tokens_helper(_visitor, &mut _i.brace_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.named) { - let it = el.value_mut(); - _visitor.visit_field_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_fields_unnamed_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FieldsUnnamed) { - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.unnamed) { - let it = el.value_mut(); - _visitor.visit_field_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_file_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut File) { - skip!(_i.shebang); - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - for it in &mut _i.items { - _visitor.visit_item_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_fn_arg_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FnArg) { - match *_i { - FnArg::SelfRef(ref mut _binding_0) => { - _visitor.visit_arg_self_ref_mut(_binding_0); - } - FnArg::SelfValue(ref mut _binding_0) => { - _visitor.visit_arg_self_mut(_binding_0); - } - FnArg::Captured(ref mut _binding_0) => { - _visitor.visit_arg_captured_mut(_binding_0); - } - FnArg::Inferred(ref mut _binding_0) => { - _visitor.visit_pat_mut(_binding_0); - } - FnArg::Ignored(ref mut _binding_0) => { - _visitor.visit_type_mut(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_fn_decl_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FnDecl) { - tokens_helper(_visitor, &mut _i.fn_token.span); - _visitor.visit_generics_mut(&mut _i.generics); - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.inputs) { - let it = el.value_mut(); - _visitor.visit_fn_arg_mut(it) - } - if let Some(ref mut it) = _i.variadic { - tokens_helper(_visitor, &mut it.spans) - }; - _visitor.visit_return_type_mut(&mut _i.output); -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ForeignItem) { - match *_i { - ForeignItem::Fn(ref mut _binding_0) => { - _visitor.visit_foreign_item_fn_mut(_binding_0); - } - ForeignItem::Static(ref mut _binding_0) => { - _visitor.visit_foreign_item_static_mut(_binding_0); - } - ForeignItem::Type(ref mut _binding_0) => { - _visitor.visit_foreign_item_type_mut(_binding_0); - } - ForeignItem::Macro(ref mut _binding_0) => { - _visitor.visit_foreign_item_macro_mut(_binding_0); - } - ForeignItem::Verbatim(ref mut _binding_0) => { - _visitor.visit_foreign_item_verbatim_mut(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_fn_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ForeignItemFn) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_fn_decl_mut(&mut *_i.decl); - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_macro_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut ForeignItemMacro, -) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_macro_mut(&mut _i.mac); - if let Some(ref mut it) = _i.semi_token { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_static_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut ForeignItemStatic, -) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.static_token.span); - if let Some(ref mut it) = _i.mutability { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.colon_token.spans); - _visitor.visit_type_mut(&mut *_i.ty); - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_type_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut ForeignItemType, -) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.type_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_foreign_item_verbatim_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut ForeignItemVerbatim, -) { - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_generic_argument_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut GenericArgument, -) { - match *_i { - GenericArgument::Lifetime(ref mut _binding_0) => { - _visitor.visit_lifetime_mut(_binding_0); - } - GenericArgument::Type(ref mut _binding_0) => { - _visitor.visit_type_mut(_binding_0); - } - GenericArgument::Binding(ref mut _binding_0) => { - _visitor.visit_binding_mut(_binding_0); - } - GenericArgument::Constraint(ref mut _binding_0) => { - _visitor.visit_constraint_mut(_binding_0); - } - GenericArgument::Const(ref mut _binding_0) => { - _visitor.visit_expr_mut(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_generic_method_argument_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut GenericMethodArgument, -) { - match *_i { - GenericMethodArgument::Type(ref mut _binding_0) => { - _visitor.visit_type_mut(_binding_0); - } - GenericMethodArgument::Const(ref mut _binding_0) => { - _visitor.visit_expr_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_generic_param_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut GenericParam) { - match *_i { - GenericParam::Type(ref mut _binding_0) => { - _visitor.visit_type_param_mut(_binding_0); - } - GenericParam::Lifetime(ref mut _binding_0) => { - _visitor.visit_lifetime_def_mut(_binding_0); - } - GenericParam::Const(ref mut _binding_0) => { - _visitor.visit_const_param_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_generics_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Generics) { - if let Some(ref mut it) = _i.lt_token { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.params) { - let it = el.value_mut(); - _visitor.visit_generic_param_mut(it) - } - if let Some(ref mut it) = _i.gt_token { - tokens_helper(_visitor, &mut it.spans) - }; - if let Some(ref mut it) = _i.where_clause { - _visitor.visit_where_clause_mut(it) - }; -} -#[cfg(feature = "full")] -pub fn visit_impl_item_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItem) { - match *_i { - ImplItem::Const(ref mut _binding_0) => { - _visitor.visit_impl_item_const_mut(_binding_0); - } - ImplItem::Method(ref mut _binding_0) => { - _visitor.visit_impl_item_method_mut(_binding_0); - } - ImplItem::Type(ref mut _binding_0) => { - _visitor.visit_impl_item_type_mut(_binding_0); - } - ImplItem::Existential(ref mut _binding_0) => { - _visitor.visit_impl_item_existential_mut(_binding_0); - } - ImplItem::Macro(ref mut _binding_0) => { - _visitor.visit_impl_item_macro_mut(_binding_0); - } - ImplItem::Verbatim(ref mut _binding_0) => { - _visitor.visit_impl_item_verbatim_mut(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_impl_item_const_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItemConst) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - if let Some(ref mut it) = _i.defaultness { - tokens_helper(_visitor, &mut it.span) - }; - tokens_helper(_visitor, &mut _i.const_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.colon_token.spans); - _visitor.visit_type_mut(&mut _i.ty); - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_expr_mut(&mut _i.expr); - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_impl_item_existential_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut ImplItemExistential, -) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.existential_token.span); - tokens_helper(_visitor, &mut _i.type_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - if let Some(ref mut it) = _i.colon_token { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_impl_item_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItemMacro) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_macro_mut(&mut _i.mac); - if let Some(ref mut it) = _i.semi_token { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_impl_item_method_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItemMethod) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - if let Some(ref mut it) = _i.defaultness { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_method_sig_mut(&mut _i.sig); - _visitor.visit_block_mut(&mut _i.block); -} -#[cfg(feature = "full")] -pub fn visit_impl_item_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItemType) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - if let Some(ref mut it) = _i.defaultness { - tokens_helper(_visitor, &mut it.span) - }; - tokens_helper(_visitor, &mut _i.type_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_type_mut(&mut _i.ty); - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_impl_item_verbatim_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut ImplItemVerbatim, -) { - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_index_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Index) { - skip!(_i.index); - _visitor.visit_span_mut(&mut _i.span); -} -#[cfg(feature = "full")] -pub fn visit_item_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Item) { - match *_i { - Item::ExternCrate(ref mut _binding_0) => { - _visitor.visit_item_extern_crate_mut(_binding_0); - } - Item::Use(ref mut _binding_0) => { - _visitor.visit_item_use_mut(_binding_0); - } - Item::Static(ref mut _binding_0) => { - _visitor.visit_item_static_mut(_binding_0); - } - Item::Const(ref mut _binding_0) => { - _visitor.visit_item_const_mut(_binding_0); - } - Item::Fn(ref mut _binding_0) => { - _visitor.visit_item_fn_mut(_binding_0); - } - Item::Mod(ref mut _binding_0) => { - _visitor.visit_item_mod_mut(_binding_0); - } - Item::ForeignMod(ref mut _binding_0) => { - _visitor.visit_item_foreign_mod_mut(_binding_0); - } - Item::Type(ref mut _binding_0) => { - _visitor.visit_item_type_mut(_binding_0); - } - Item::Existential(ref mut _binding_0) => { - _visitor.visit_item_existential_mut(_binding_0); - } - Item::Struct(ref mut _binding_0) => { - _visitor.visit_item_struct_mut(_binding_0); - } - Item::Enum(ref mut _binding_0) => { - _visitor.visit_item_enum_mut(_binding_0); - } - Item::Union(ref mut _binding_0) => { - _visitor.visit_item_union_mut(_binding_0); - } - Item::Trait(ref mut _binding_0) => { - _visitor.visit_item_trait_mut(_binding_0); - } - Item::TraitAlias(ref mut _binding_0) => { - _visitor.visit_item_trait_alias_mut(_binding_0); - } - Item::Impl(ref mut _binding_0) => { - _visitor.visit_item_impl_mut(_binding_0); - } - Item::Macro(ref mut _binding_0) => { - _visitor.visit_item_macro_mut(_binding_0); - } - Item::Macro2(ref mut _binding_0) => { - _visitor.visit_item_macro2_mut(_binding_0); - } - Item::Verbatim(ref mut _binding_0) => { - _visitor.visit_item_verbatim_mut(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_item_const_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemConst) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.const_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.colon_token.spans); - _visitor.visit_type_mut(&mut *_i.ty); - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_expr_mut(&mut *_i.expr); - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_enum_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemEnum) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.enum_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - tokens_helper(_visitor, &mut _i.brace_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.variants) { - let it = el.value_mut(); - _visitor.visit_variant_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_item_existential_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut ItemExistential, -) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.existential_token.span); - tokens_helper(_visitor, &mut _i.type_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - if let Some(ref mut it) = _i.colon_token { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_extern_crate_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut ItemExternCrate, -) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.extern_token.span); - tokens_helper(_visitor, &mut _i.crate_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - if let Some(ref mut it) = _i.rename { - tokens_helper(_visitor, &mut (it).0.span); - _visitor.visit_ident_mut(&mut (it).1); - }; - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_fn_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemFn) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - if let Some(ref mut it) = _i.constness { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.asyncness { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.unsafety { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.abi { - _visitor.visit_abi_mut(it) - }; - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_fn_decl_mut(&mut *_i.decl); - _visitor.visit_block_mut(&mut *_i.block); -} -#[cfg(feature = "full")] -pub fn visit_item_foreign_mod_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemForeignMod) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_abi_mut(&mut _i.abi); - tokens_helper(_visitor, &mut _i.brace_token.span); - for it in &mut _i.items { - _visitor.visit_foreign_item_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_item_impl_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemImpl) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.defaultness { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.unsafety { - tokens_helper(_visitor, &mut it.span) - }; - tokens_helper(_visitor, &mut _i.impl_token.span); - _visitor.visit_generics_mut(&mut _i.generics); - if let Some(ref mut it) = _i.trait_ { - if let Some(ref mut it) = (it).0 { - tokens_helper(_visitor, &mut it.spans) - }; - _visitor.visit_path_mut(&mut (it).1); - tokens_helper(_visitor, &mut (it).2.span); - }; - _visitor.visit_type_mut(&mut *_i.self_ty); - tokens_helper(_visitor, &mut _i.brace_token.span); - for it in &mut _i.items { - _visitor.visit_impl_item_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_item_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemMacro) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - if let Some(ref mut it) = _i.ident { - _visitor.visit_ident_mut(it) - }; - _visitor.visit_macro_mut(&mut _i.mac); - if let Some(ref mut it) = _i.semi_token { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_item_macro2_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemMacro2) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.macro_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.paren_token.span); - skip!(_i.args); - tokens_helper(_visitor, &mut _i.brace_token.span); - skip!(_i.body); -} -#[cfg(feature = "full")] -pub fn visit_item_mod_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemMod) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.mod_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - if let Some(ref mut it) = _i.content { - tokens_helper(_visitor, &mut (it).0.span); - for it in &mut (it).1 { - _visitor.visit_item_mut(it) - } - }; - if let Some(ref mut it) = _i.semi { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_item_static_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemStatic) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.static_token.span); - if let Some(ref mut it) = _i.mutability { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.colon_token.spans); - _visitor.visit_type_mut(&mut *_i.ty); - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_expr_mut(&mut *_i.expr); - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemStruct) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.struct_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - _visitor.visit_fields_mut(&mut _i.fields); - if let Some(ref mut it) = _i.semi_token { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_item_trait_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemTrait) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - if let Some(ref mut it) = _i.unsafety { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.auto_token { - tokens_helper(_visitor, &mut it.span) - }; - tokens_helper(_visitor, &mut _i.trait_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - if let Some(ref mut it) = _i.colon_token { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.supertraits) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } - tokens_helper(_visitor, &mut _i.brace_token.span); - for it in &mut _i.items { - _visitor.visit_trait_item_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_item_trait_alias_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemTraitAlias) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.trait_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - tokens_helper(_visitor, &mut _i.eq_token.spans); - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemType) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.type_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_type_mut(&mut *_i.ty); - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_union_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemUnion) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.union_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - _visitor.visit_fields_named_mut(&mut _i.fields); -} -#[cfg(feature = "full")] -pub fn visit_item_use_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemUse) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_visibility_mut(&mut _i.vis); - tokens_helper(_visitor, &mut _i.use_token.span); - if let Some(ref mut it) = _i.leading_colon { - tokens_helper(_visitor, &mut it.spans) - }; - _visitor.visit_use_tree_mut(&mut _i.tree); - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_item_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemVerbatim) { - skip!(_i.tts); -} -#[cfg(feature = "full")] -pub fn visit_label_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Label) { - _visitor.visit_lifetime_mut(&mut _i.name); - tokens_helper(_visitor, &mut _i.colon_token.spans); -} -pub fn visit_lifetime_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Lifetime) { - _visitor.visit_span_mut(&mut _i.apostrophe); - _visitor.visit_ident_mut(&mut _i.ident); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lifetime_def_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LifetimeDef) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_lifetime_mut(&mut _i.lifetime); - if let Some(ref mut it) = _i.colon_token { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_lifetime_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Lit) { - match *_i { - Lit::Str(ref mut _binding_0) => { - _visitor.visit_lit_str_mut(_binding_0); - } - Lit::ByteStr(ref mut _binding_0) => { - _visitor.visit_lit_byte_str_mut(_binding_0); - } - Lit::Byte(ref mut _binding_0) => { - _visitor.visit_lit_byte_mut(_binding_0); - } - Lit::Char(ref mut _binding_0) => { - _visitor.visit_lit_char_mut(_binding_0); - } - Lit::Int(ref mut _binding_0) => { - _visitor.visit_lit_int_mut(_binding_0); - } - Lit::Float(ref mut _binding_0) => { - _visitor.visit_lit_float_mut(_binding_0); - } - Lit::Bool(ref mut _binding_0) => { - _visitor.visit_lit_bool_mut(_binding_0); - } - Lit::Verbatim(ref mut _binding_0) => { - _visitor.visit_lit_verbatim_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_bool_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitBool) { - skip!(_i.value); - _visitor.visit_span_mut(&mut _i.span); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_byte_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitByte) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_byte_str_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitByteStr) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_char_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitChar) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_float_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitFloat) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_int_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitInt) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_str_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitStr) {} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_lit_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitVerbatim) { - skip!(_i.token); -} -#[cfg(feature = "full")] -pub fn visit_local_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Local) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.let_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.pats) { - let it = el.value_mut(); - _visitor.visit_pat_mut(it) - } - if let Some(ref mut it) = _i.ty { - tokens_helper(_visitor, &mut (it).0.spans); - _visitor.visit_type_mut(&mut *(it).1); - }; - if let Some(ref mut it) = _i.init { - tokens_helper(_visitor, &mut (it).0.spans); - _visitor.visit_expr_mut(&mut *(it).1); - }; - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Macro) { - _visitor.visit_path_mut(&mut _i.path); - tokens_helper(_visitor, &mut _i.bang_token.spans); - _visitor.visit_macro_delimiter_mut(&mut _i.delimiter); - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_macro_delimiter_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut MacroDelimiter) { - match *_i { - MacroDelimiter::Paren(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.span); - } - MacroDelimiter::Brace(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.span); - } - MacroDelimiter::Bracket(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.span); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_member_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Member) { - match *_i { - Member::Named(ref mut _binding_0) => { - _visitor.visit_ident_mut(_binding_0); - } - Member::Unnamed(ref mut _binding_0) => { - _visitor.visit_index_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_meta_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Meta) { - match *_i { - Meta::Word(ref mut _binding_0) => { - _visitor.visit_ident_mut(_binding_0); - } - Meta::List(ref mut _binding_0) => { - _visitor.visit_meta_list_mut(_binding_0); - } - Meta::NameValue(ref mut _binding_0) => { - _visitor.visit_meta_name_value_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_meta_list_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut MetaList) { - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.nested) { - let it = el.value_mut(); - _visitor.visit_nested_meta_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_meta_name_value_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut MetaNameValue) { - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_lit_mut(&mut _i.lit); -} -#[cfg(feature = "full")] -pub fn visit_method_sig_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut MethodSig) { - if let Some(ref mut it) = _i.constness { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.asyncness { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.unsafety { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.abi { - _visitor.visit_abi_mut(it) - }; - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_fn_decl_mut(&mut _i.decl); -} -#[cfg(feature = "full")] -pub fn visit_method_turbofish_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut MethodTurbofish, -) { - tokens_helper(_visitor, &mut _i.colon2_token.spans); - tokens_helper(_visitor, &mut _i.lt_token.spans); - for mut el in Punctuated::pairs_mut(&mut _i.args) { - let it = el.value_mut(); - _visitor.visit_generic_method_argument_mut(it) - } - tokens_helper(_visitor, &mut _i.gt_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_nested_meta_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut NestedMeta) { - match *_i { - NestedMeta::Meta(ref mut _binding_0) => { - _visitor.visit_meta_mut(_binding_0); - } - NestedMeta::Literal(ref mut _binding_0) => { - _visitor.visit_lit_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_parenthesized_generic_arguments_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut ParenthesizedGenericArguments, -) { - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.inputs) { - let it = el.value_mut(); - _visitor.visit_type_mut(it) - } - _visitor.visit_return_type_mut(&mut _i.output); -} -#[cfg(feature = "full")] -pub fn visit_pat_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Pat) { - match *_i { - Pat::Wild(ref mut _binding_0) => { - _visitor.visit_pat_wild_mut(_binding_0); - } - Pat::Ident(ref mut _binding_0) => { - _visitor.visit_pat_ident_mut(_binding_0); - } - Pat::Struct(ref mut _binding_0) => { - _visitor.visit_pat_struct_mut(_binding_0); - } - Pat::TupleStruct(ref mut _binding_0) => { - _visitor.visit_pat_tuple_struct_mut(_binding_0); - } - Pat::Path(ref mut _binding_0) => { - _visitor.visit_pat_path_mut(_binding_0); - } - Pat::Tuple(ref mut _binding_0) => { - _visitor.visit_pat_tuple_mut(_binding_0); - } - Pat::Box(ref mut _binding_0) => { - _visitor.visit_pat_box_mut(_binding_0); - } - Pat::Ref(ref mut _binding_0) => { - _visitor.visit_pat_ref_mut(_binding_0); - } - Pat::Lit(ref mut _binding_0) => { - _visitor.visit_pat_lit_mut(_binding_0); - } - Pat::Range(ref mut _binding_0) => { - _visitor.visit_pat_range_mut(_binding_0); - } - Pat::Slice(ref mut _binding_0) => { - _visitor.visit_pat_slice_mut(_binding_0); - } - Pat::Macro(ref mut _binding_0) => { - _visitor.visit_pat_macro_mut(_binding_0); - } - Pat::Verbatim(ref mut _binding_0) => { - _visitor.visit_pat_verbatim_mut(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_pat_box_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatBox) { - tokens_helper(_visitor, &mut _i.box_token.span); - _visitor.visit_pat_mut(&mut *_i.pat); -} -#[cfg(feature = "full")] -pub fn visit_pat_ident_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatIdent) { - if let Some(ref mut it) = _i.by_ref { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.mutability { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_ident_mut(&mut _i.ident); - if let Some(ref mut it) = _i.subpat { - tokens_helper(_visitor, &mut (it).0.spans); - _visitor.visit_pat_mut(&mut *(it).1); - }; -} -#[cfg(feature = "full")] -pub fn visit_pat_lit_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatLit) { - _visitor.visit_expr_mut(&mut *_i.expr); -} -#[cfg(feature = "full")] -pub fn visit_pat_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatMacro) { - _visitor.visit_macro_mut(&mut _i.mac); -} -#[cfg(feature = "full")] -pub fn visit_pat_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatPath) { - if let Some(ref mut it) = _i.qself { - _visitor.visit_qself_mut(it) - }; - _visitor.visit_path_mut(&mut _i.path); -} -#[cfg(feature = "full")] -pub fn visit_pat_range_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatRange) { - _visitor.visit_expr_mut(&mut *_i.lo); - _visitor.visit_range_limits_mut(&mut _i.limits); - _visitor.visit_expr_mut(&mut *_i.hi); -} -#[cfg(feature = "full")] -pub fn visit_pat_ref_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatRef) { - tokens_helper(_visitor, &mut _i.and_token.spans); - if let Some(ref mut it) = _i.mutability { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_pat_mut(&mut *_i.pat); -} -#[cfg(feature = "full")] -pub fn visit_pat_slice_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatSlice) { - tokens_helper(_visitor, &mut _i.bracket_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.front) { - let it = el.value_mut(); - _visitor.visit_pat_mut(it) - } - if let Some(ref mut it) = _i.middle { - _visitor.visit_pat_mut(&mut **it) - }; - if let Some(ref mut it) = _i.dot2_token { - tokens_helper(_visitor, &mut it.spans) - }; - if let Some(ref mut it) = _i.comma_token { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.back) { - let it = el.value_mut(); - _visitor.visit_pat_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_pat_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatStruct) { - _visitor.visit_path_mut(&mut _i.path); - tokens_helper(_visitor, &mut _i.brace_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.fields) { - let it = el.value_mut(); - _visitor.visit_field_pat_mut(it) - } - if let Some(ref mut it) = _i.dot2_token { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_pat_tuple_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatTuple) { - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.front) { - let it = el.value_mut(); - _visitor.visit_pat_mut(it) - } - if let Some(ref mut it) = _i.dot2_token { - tokens_helper(_visitor, &mut it.spans) - }; - if let Some(ref mut it) = _i.comma_token { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.back) { - let it = el.value_mut(); - _visitor.visit_pat_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_pat_tuple_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatTupleStruct) { - _visitor.visit_path_mut(&mut _i.path); - _visitor.visit_pat_tuple_mut(&mut _i.pat); -} -#[cfg(feature = "full")] -pub fn visit_pat_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatVerbatim) { - skip!(_i.tts); -} -#[cfg(feature = "full")] -pub fn visit_pat_wild_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatWild) { - tokens_helper(_visitor, &mut _i.underscore_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Path) { - if let Some(ref mut it) = _i.leading_colon { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.segments) { - let it = el.value_mut(); - _visitor.visit_path_segment_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_path_arguments_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PathArguments) { - match *_i { - PathArguments::None => {} - PathArguments::AngleBracketed(ref mut _binding_0) => { - _visitor.visit_angle_bracketed_generic_arguments_mut(_binding_0); - } - PathArguments::Parenthesized(ref mut _binding_0) => { - _visitor.visit_parenthesized_generic_arguments_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_path_segment_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PathSegment) { - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_path_arguments_mut(&mut _i.arguments); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_predicate_eq_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PredicateEq) { - _visitor.visit_type_mut(&mut _i.lhs_ty); - tokens_helper(_visitor, &mut _i.eq_token.spans); - _visitor.visit_type_mut(&mut _i.rhs_ty); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_predicate_lifetime_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut PredicateLifetime, -) { - _visitor.visit_lifetime_mut(&mut _i.lifetime); - tokens_helper(_visitor, &mut _i.colon_token.spans); - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_lifetime_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_predicate_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PredicateType) { - if let Some(ref mut it) = _i.lifetimes { - _visitor.visit_bound_lifetimes_mut(it) - }; - _visitor.visit_type_mut(&mut _i.bounded_ty); - tokens_helper(_visitor, &mut _i.colon_token.spans); - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_qself_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut QSelf) { - tokens_helper(_visitor, &mut _i.lt_token.spans); - _visitor.visit_type_mut(&mut *_i.ty); - skip!(_i.position); - if let Some(ref mut it) = _i.as_token { - tokens_helper(_visitor, &mut it.span) - }; - tokens_helper(_visitor, &mut _i.gt_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_range_limits_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut RangeLimits) { - match *_i { - RangeLimits::HalfOpen(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - RangeLimits::Closed(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_return_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ReturnType) { - match *_i { - ReturnType::Default => {} - ReturnType::Type(ref mut _binding_0, ref mut _binding_1) => { - tokens_helper(_visitor, &mut _binding_0.spans); - _visitor.visit_type_mut(&mut **_binding_1); - } - } -} -#[cfg(feature = "full")] -pub fn visit_stmt_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Stmt) { - match *_i { - Stmt::Local(ref mut _binding_0) => { - _visitor.visit_local_mut(_binding_0); - } - Stmt::Item(ref mut _binding_0) => { - _visitor.visit_item_mut(_binding_0); - } - Stmt::Expr(ref mut _binding_0) => { - _visitor.visit_expr_mut(_binding_0); - } - Stmt::Semi(ref mut _binding_0, ref mut _binding_1) => { - _visitor.visit_expr_mut(_binding_0); - tokens_helper(_visitor, &mut _binding_1.spans); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_trait_bound_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitBound) { - if let Some(ref mut it) = _i.paren_token { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_trait_bound_modifier_mut(&mut _i.modifier); - if let Some(ref mut it) = _i.lifetimes { - _visitor.visit_bound_lifetimes_mut(it) - }; - _visitor.visit_path_mut(&mut _i.path); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_trait_bound_modifier_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut TraitBoundModifier, -) { - match *_i { - TraitBoundModifier::None => {} - TraitBoundModifier::Maybe(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - } -} -#[cfg(feature = "full")] -pub fn visit_trait_item_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItem) { - match *_i { - TraitItem::Const(ref mut _binding_0) => { - _visitor.visit_trait_item_const_mut(_binding_0); - } - TraitItem::Method(ref mut _binding_0) => { - _visitor.visit_trait_item_method_mut(_binding_0); - } - TraitItem::Type(ref mut _binding_0) => { - _visitor.visit_trait_item_type_mut(_binding_0); - } - TraitItem::Macro(ref mut _binding_0) => { - _visitor.visit_trait_item_macro_mut(_binding_0); - } - TraitItem::Verbatim(ref mut _binding_0) => { - _visitor.visit_trait_item_verbatim_mut(_binding_0); - } - } -} -#[cfg(feature = "full")] -pub fn visit_trait_item_const_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItemConst) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.const_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.colon_token.spans); - _visitor.visit_type_mut(&mut _i.ty); - if let Some(ref mut it) = _i.default { - tokens_helper(_visitor, &mut (it).0.spans); - _visitor.visit_expr_mut(&mut (it).1); - }; - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_trait_item_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItemMacro) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_macro_mut(&mut _i.mac); - if let Some(ref mut it) = _i.semi_token { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_trait_item_method_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut TraitItemMethod, -) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_method_sig_mut(&mut _i.sig); - if let Some(ref mut it) = _i.default { - _visitor.visit_block_mut(it) - }; - if let Some(ref mut it) = _i.semi_token { - tokens_helper(_visitor, &mut it.spans) - }; -} -#[cfg(feature = "full")] -pub fn visit_trait_item_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItemType) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - tokens_helper(_visitor, &mut _i.type_token.span); - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_generics_mut(&mut _i.generics); - if let Some(ref mut it) = _i.colon_token { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } - if let Some(ref mut it) = _i.default { - tokens_helper(_visitor, &mut (it).0.spans); - _visitor.visit_type_mut(&mut (it).1); - }; - tokens_helper(_visitor, &mut _i.semi_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_trait_item_verbatim_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut TraitItemVerbatim, -) { - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Type) { - match *_i { - Type::Slice(ref mut _binding_0) => { - _visitor.visit_type_slice_mut(_binding_0); - } - Type::Array(ref mut _binding_0) => { - _visitor.visit_type_array_mut(_binding_0); - } - Type::Ptr(ref mut _binding_0) => { - _visitor.visit_type_ptr_mut(_binding_0); - } - Type::Reference(ref mut _binding_0) => { - _visitor.visit_type_reference_mut(_binding_0); - } - Type::BareFn(ref mut _binding_0) => { - _visitor.visit_type_bare_fn_mut(_binding_0); - } - Type::Never(ref mut _binding_0) => { - _visitor.visit_type_never_mut(_binding_0); - } - Type::Tuple(ref mut _binding_0) => { - _visitor.visit_type_tuple_mut(_binding_0); - } - Type::Path(ref mut _binding_0) => { - _visitor.visit_type_path_mut(_binding_0); - } - Type::TraitObject(ref mut _binding_0) => { - _visitor.visit_type_trait_object_mut(_binding_0); - } - Type::ImplTrait(ref mut _binding_0) => { - _visitor.visit_type_impl_trait_mut(_binding_0); - } - Type::Paren(ref mut _binding_0) => { - _visitor.visit_type_paren_mut(_binding_0); - } - Type::Group(ref mut _binding_0) => { - _visitor.visit_type_group_mut(_binding_0); - } - Type::Infer(ref mut _binding_0) => { - _visitor.visit_type_infer_mut(_binding_0); - } - Type::Macro(ref mut _binding_0) => { - _visitor.visit_type_macro_mut(_binding_0); - } - Type::Verbatim(ref mut _binding_0) => { - _visitor.visit_type_verbatim_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_array_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeArray) { - tokens_helper(_visitor, &mut _i.bracket_token.span); - _visitor.visit_type_mut(&mut *_i.elem); - tokens_helper(_visitor, &mut _i.semi_token.spans); - _visitor.visit_expr_mut(&mut _i.len); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_bare_fn_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeBareFn) { - if let Some(ref mut it) = _i.lifetimes { - _visitor.visit_bound_lifetimes_mut(it) - }; - if let Some(ref mut it) = _i.unsafety { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.abi { - _visitor.visit_abi_mut(it) - }; - tokens_helper(_visitor, &mut _i.fn_token.span); - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.inputs) { - let it = el.value_mut(); - _visitor.visit_bare_fn_arg_mut(it) - } - if let Some(ref mut it) = _i.variadic { - tokens_helper(_visitor, &mut it.spans) - }; - _visitor.visit_return_type_mut(&mut _i.output); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_group_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeGroup) { - tokens_helper(_visitor, &mut _i.group_token.span); - _visitor.visit_type_mut(&mut *_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_impl_trait_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeImplTrait) { - tokens_helper(_visitor, &mut _i.impl_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_infer_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeInfer) { - tokens_helper(_visitor, &mut _i.underscore_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeMacro) { - _visitor.visit_macro_mut(&mut _i.mac); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_never_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeNever) { - tokens_helper(_visitor, &mut _i.bang_token.spans); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_param_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeParam) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_ident_mut(&mut _i.ident); - if let Some(ref mut it) = _i.colon_token { - tokens_helper(_visitor, &mut it.spans) - }; - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } - if let Some(ref mut it) = _i.eq_token { - tokens_helper(_visitor, &mut it.spans) - }; - if let Some(ref mut it) = _i.default { - _visitor.visit_type_mut(it) - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_param_bound_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeParamBound) { - match *_i { - TypeParamBound::Trait(ref mut _binding_0) => { - _visitor.visit_trait_bound_mut(_binding_0); - } - TypeParamBound::Lifetime(ref mut _binding_0) => { - _visitor.visit_lifetime_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_paren_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeParen) { - tokens_helper(_visitor, &mut _i.paren_token.span); - _visitor.visit_type_mut(&mut *_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypePath) { - if let Some(ref mut it) = _i.qself { - _visitor.visit_qself_mut(it) - }; - _visitor.visit_path_mut(&mut _i.path); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_ptr_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypePtr) { - tokens_helper(_visitor, &mut _i.star_token.spans); - if let Some(ref mut it) = _i.const_token { - tokens_helper(_visitor, &mut it.span) - }; - if let Some(ref mut it) = _i.mutability { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_type_mut(&mut *_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_reference_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeReference) { - tokens_helper(_visitor, &mut _i.and_token.spans); - if let Some(ref mut it) = _i.lifetime { - _visitor.visit_lifetime_mut(it) - }; - if let Some(ref mut it) = _i.mutability { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_type_mut(&mut *_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_slice_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeSlice) { - tokens_helper(_visitor, &mut _i.bracket_token.span); - _visitor.visit_type_mut(&mut *_i.elem); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_trait_object_mut<V: VisitMut + ?Sized>( - _visitor: &mut V, - _i: &mut TypeTraitObject, -) { - if let Some(ref mut it) = _i.dyn_token { - tokens_helper(_visitor, &mut it.span) - }; - for mut el in Punctuated::pairs_mut(&mut _i.bounds) { - let it = el.value_mut(); - _visitor.visit_type_param_bound_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_tuple_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeTuple) { - tokens_helper(_visitor, &mut _i.paren_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.elems) { - let it = el.value_mut(); - _visitor.visit_type_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_type_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeVerbatim) { - skip!(_i.tts); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_un_op_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UnOp) { - match *_i { - UnOp::Deref(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - UnOp::Not(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - UnOp::Neg(ref mut _binding_0) => { - tokens_helper(_visitor, &mut _binding_0.spans); - } - } -} -#[cfg(feature = "full")] -pub fn visit_use_glob_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseGlob) { - tokens_helper(_visitor, &mut _i.star_token.spans); -} -#[cfg(feature = "full")] -pub fn visit_use_group_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseGroup) { - tokens_helper(_visitor, &mut _i.brace_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.items) { - let it = el.value_mut(); - _visitor.visit_use_tree_mut(it) - } -} -#[cfg(feature = "full")] -pub fn visit_use_name_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseName) { - _visitor.visit_ident_mut(&mut _i.ident); -} -#[cfg(feature = "full")] -pub fn visit_use_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UsePath) { - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.colon2_token.spans); - _visitor.visit_use_tree_mut(&mut *_i.tree); -} -#[cfg(feature = "full")] -pub fn visit_use_rename_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseRename) { - _visitor.visit_ident_mut(&mut _i.ident); - tokens_helper(_visitor, &mut _i.as_token.span); - _visitor.visit_ident_mut(&mut _i.rename); -} -#[cfg(feature = "full")] -pub fn visit_use_tree_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseTree) { - match *_i { - UseTree::Path(ref mut _binding_0) => { - _visitor.visit_use_path_mut(_binding_0); - } - UseTree::Name(ref mut _binding_0) => { - _visitor.visit_use_name_mut(_binding_0); - } - UseTree::Rename(ref mut _binding_0) => { - _visitor.visit_use_rename_mut(_binding_0); - } - UseTree::Glob(ref mut _binding_0) => { - _visitor.visit_use_glob_mut(_binding_0); - } - UseTree::Group(ref mut _binding_0) => { - _visitor.visit_use_group_mut(_binding_0); - } - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_variant_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Variant) { - for it in &mut _i.attrs { - _visitor.visit_attribute_mut(it) - } - _visitor.visit_ident_mut(&mut _i.ident); - _visitor.visit_fields_mut(&mut _i.fields); - if let Some(ref mut it) = _i.discriminant { - tokens_helper(_visitor, &mut (it).0.spans); - _visitor.visit_expr_mut(&mut (it).1); - }; -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_vis_crate_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut VisCrate) { - tokens_helper(_visitor, &mut _i.crate_token.span); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_vis_public_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut VisPublic) { - tokens_helper(_visitor, &mut _i.pub_token.span); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_vis_restricted_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut VisRestricted) { - tokens_helper(_visitor, &mut _i.pub_token.span); - tokens_helper(_visitor, &mut _i.paren_token.span); - if let Some(ref mut it) = _i.in_token { - tokens_helper(_visitor, &mut it.span) - }; - _visitor.visit_path_mut(&mut *_i.path); -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_visibility_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Visibility) { - match *_i { - Visibility::Public(ref mut _binding_0) => { - _visitor.visit_vis_public_mut(_binding_0); - } - Visibility::Crate(ref mut _binding_0) => { - _visitor.visit_vis_crate_mut(_binding_0); - } - Visibility::Restricted(ref mut _binding_0) => { - _visitor.visit_vis_restricted_mut(_binding_0); - } - Visibility::Inherited => {} - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_where_clause_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut WhereClause) { - tokens_helper(_visitor, &mut _i.where_token.span); - for mut el in Punctuated::pairs_mut(&mut _i.predicates) { - let it = el.value_mut(); - _visitor.visit_where_predicate_mut(it) - } -} -#[cfg(any(feature = "derive", feature = "full"))] -pub fn visit_where_predicate_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut WherePredicate) { - match *_i { - WherePredicate::Type(ref mut _binding_0) => { - _visitor.visit_predicate_type_mut(_binding_0); - } - WherePredicate::Lifetime(ref mut _binding_0) => { - _visitor.visit_predicate_lifetime_mut(_binding_0); - } - WherePredicate::Eq(ref mut _binding_0) => { - _visitor.visit_predicate_eq_mut(_binding_0); - } - } -} -pub fn visit_span_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Span) {} -pub fn visit_ident_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Ident) {} diff --git a/0.15.42/src/gen_helper.rs b/0.15.42/src/gen_helper.rs deleted file mode 100644 index b15b42be..00000000 --- a/0.15.42/src/gen_helper.rs +++ /dev/null @@ -1,154 +0,0 @@ -#[cfg(feature = "fold")] -pub mod fold { - use fold::Fold; - use proc_macro2::Span; - use punctuated::{Pair, Punctuated}; - - pub trait FoldHelper { - type Item; - fn lift<F>(self, f: F) -> Self - where - F: FnMut(Self::Item) -> Self::Item; - } - - impl<T> FoldHelper for Vec<T> { - type Item = T; - fn lift<F>(self, f: F) -> Self - where - F: FnMut(Self::Item) -> Self::Item, - { - self.into_iter().map(f).collect() - } - } - - impl<T, U> FoldHelper for Punctuated<T, U> { - type Item = T; - fn lift<F>(self, mut f: F) -> Self - where - F: FnMut(Self::Item) -> Self::Item, - { - self.into_pairs() - .map(Pair::into_tuple) - .map(|(t, u)| Pair::new(f(t), u)) - .collect() - } - } - - pub fn tokens_helper<F: Fold + ?Sized, S: Spans>(folder: &mut F, spans: &S) -> S { - spans.fold(folder) - } - - pub trait Spans { - fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self; - } - - impl Spans for Span { - fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { - folder.fold_span(*self) - } - } - - impl Spans for [Span; 1] { - fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { - [folder.fold_span(self[0])] - } - } - - impl Spans for [Span; 2] { - fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { - [folder.fold_span(self[0]), folder.fold_span(self[1])] - } - } - - impl Spans for [Span; 3] { - fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { - [ - folder.fold_span(self[0]), - folder.fold_span(self[1]), - folder.fold_span(self[2]), - ] - } - } -} - -#[cfg(feature = "visit")] -pub mod visit { - use proc_macro2::Span; - use visit::Visit; - - pub fn tokens_helper<'ast, V: Visit<'ast> + ?Sized, S: Spans>(visitor: &mut V, spans: &'ast S) { - spans.visit(visitor); - } - - pub trait Spans { - fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V); - } - - impl Spans for Span { - fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { - visitor.visit_span(self); - } - } - - impl Spans for [Span; 1] { - fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { - visitor.visit_span(&self[0]); - } - } - - impl Spans for [Span; 2] { - fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { - visitor.visit_span(&self[0]); - visitor.visit_span(&self[1]); - } - } - - impl Spans for [Span; 3] { - fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { - visitor.visit_span(&self[0]); - visitor.visit_span(&self[1]); - visitor.visit_span(&self[2]); - } - } -} - -#[cfg(feature = "visit-mut")] -pub mod visit_mut { - use proc_macro2::Span; - use visit_mut::VisitMut; - - pub fn tokens_helper<V: VisitMut + ?Sized, S: Spans>(visitor: &mut V, spans: &mut S) { - spans.visit_mut(visitor); - } - - pub trait Spans { - fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V); - } - - impl Spans for Span { - fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { - visitor.visit_span_mut(self); - } - } - - impl Spans for [Span; 1] { - fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { - visitor.visit_span_mut(&mut self[0]); - } - } - - impl Spans for [Span; 2] { - fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { - visitor.visit_span_mut(&mut self[0]); - visitor.visit_span_mut(&mut self[1]); - } - } - - impl Spans for [Span; 3] { - fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { - visitor.visit_span_mut(&mut self[0]); - visitor.visit_span_mut(&mut self[1]); - visitor.visit_span_mut(&mut self[2]); - } - } -} diff --git a/0.15.42/src/generics.rs b/0.15.42/src/generics.rs deleted file mode 100644 index d9d652df..00000000 --- a/0.15.42/src/generics.rs +++ /dev/null @@ -1,1132 +0,0 @@ -use super::*; -use punctuated::{Iter, IterMut, Punctuated}; - -ast_struct! { - /// Lifetimes and type parameters attached to a declaration of a function, - /// enum, trait, etc. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - #[derive(Default)] - pub struct Generics { - pub lt_token: Option<Token![<]>, - pub params: Punctuated<GenericParam, Token![,]>, - pub gt_token: Option<Token![>]>, - pub where_clause: Option<WhereClause>, - } -} - -ast_enum_of_structs! { - /// A generic type parameter, lifetime, or const generic: `T: Into<String>`, - /// `'a: 'b`, `const LEN: usize`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum GenericParam { - /// A generic type parameter: `T: Into<String>`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Type(TypeParam { - pub attrs: Vec<Attribute>, - pub ident: Ident, - pub colon_token: Option<Token![:]>, - pub bounds: Punctuated<TypeParamBound, Token![+]>, - pub eq_token: Option<Token![=]>, - pub default: Option<Type>, - }), - - /// A lifetime definition: `'a: 'b + 'c + 'd`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Lifetime(LifetimeDef { - pub attrs: Vec<Attribute>, - pub lifetime: Lifetime, - pub colon_token: Option<Token![:]>, - pub bounds: Punctuated<Lifetime, Token![+]>, - }), - - /// A const generic parameter: `const LENGTH: usize`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Const(ConstParam { - pub attrs: Vec<Attribute>, - pub const_token: Token![const], - pub ident: Ident, - pub colon_token: Token![:], - pub ty: Type, - pub eq_token: Option<Token![=]>, - pub default: Option<Expr>, - }), - } -} - -impl Generics { - /// Returns an - /// <code - /// style="padding-right:0;">Iterator<Item = &</code><a - /// href="struct.TypeParam.html"><code - /// style="padding-left:0;padding-right:0;">TypeParam</code></a><code - /// style="padding-left:0;">></code> - /// over the type parameters in `self.params`. - pub fn type_params(&self) -> TypeParams { - TypeParams(self.params.iter()) - } - - /// Returns an - /// <code - /// style="padding-right:0;">Iterator<Item = &mut </code><a - /// href="struct.TypeParam.html"><code - /// style="padding-left:0;padding-right:0;">TypeParam</code></a><code - /// style="padding-left:0;">></code> - /// over the type parameters in `self.params`. - pub fn type_params_mut(&mut self) -> TypeParamsMut { - TypeParamsMut(self.params.iter_mut()) - } - - /// Returns an - /// <code - /// style="padding-right:0;">Iterator<Item = &</code><a - /// href="struct.LifetimeDef.html"><code - /// style="padding-left:0;padding-right:0;">LifetimeDef</code></a><code - /// style="padding-left:0;">></code> - /// over the lifetime parameters in `self.params`. - pub fn lifetimes(&self) -> Lifetimes { - Lifetimes(self.params.iter()) - } - - /// Returns an - /// <code - /// style="padding-right:0;">Iterator<Item = &mut </code><a - /// href="struct.LifetimeDef.html"><code - /// style="padding-left:0;padding-right:0;">LifetimeDef</code></a><code - /// style="padding-left:0;">></code> - /// over the lifetime parameters in `self.params`. - pub fn lifetimes_mut(&mut self) -> LifetimesMut { - LifetimesMut(self.params.iter_mut()) - } - - /// Returns an - /// <code - /// style="padding-right:0;">Iterator<Item = &</code><a - /// href="struct.ConstParam.html"><code - /// style="padding-left:0;padding-right:0;">ConstParam</code></a><code - /// style="padding-left:0;">></code> - /// over the constant parameters in `self.params`. - pub fn const_params(&self) -> ConstParams { - ConstParams(self.params.iter()) - } - - /// Returns an - /// <code - /// style="padding-right:0;">Iterator<Item = &mut </code><a - /// href="struct.ConstParam.html"><code - /// style="padding-left:0;padding-right:0;">ConstParam</code></a><code - /// style="padding-left:0;">></code> - /// over the constant parameters in `self.params`. - pub fn const_params_mut(&mut self) -> ConstParamsMut { - ConstParamsMut(self.params.iter_mut()) - } - - /// Initializes an empty `where`-clause if there is not one present already. - pub fn make_where_clause(&mut self) -> &mut WhereClause { - // This is Option::get_or_insert_with in Rust 1.20. - if self.where_clause.is_none() { - self.where_clause = Some(WhereClause { - where_token: <Token![where]>::default(), - predicates: Punctuated::new(), - }); - } - match self.where_clause { - Some(ref mut where_clause) => where_clause, - None => unreachable!(), - } - } -} - -pub struct TypeParams<'a>(Iter<'a, GenericParam>); - -impl<'a> Iterator for TypeParams<'a> { - type Item = &'a TypeParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Type(ref type_param) = *next { - Some(type_param) - } else { - self.next() - } - } -} - -pub struct TypeParamsMut<'a>(IterMut<'a, GenericParam>); - -impl<'a> Iterator for TypeParamsMut<'a> { - type Item = &'a mut TypeParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Type(ref mut type_param) = *next { - Some(type_param) - } else { - self.next() - } - } -} - -pub struct Lifetimes<'a>(Iter<'a, GenericParam>); - -impl<'a> Iterator for Lifetimes<'a> { - type Item = &'a LifetimeDef; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Lifetime(ref lifetime) = *next { - Some(lifetime) - } else { - self.next() - } - } -} - -pub struct LifetimesMut<'a>(IterMut<'a, GenericParam>); - -impl<'a> Iterator for LifetimesMut<'a> { - type Item = &'a mut LifetimeDef; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Lifetime(ref mut lifetime) = *next { - Some(lifetime) - } else { - self.next() - } - } -} - -pub struct ConstParams<'a>(Iter<'a, GenericParam>); - -impl<'a> Iterator for ConstParams<'a> { - type Item = &'a ConstParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Const(ref const_param) = *next { - Some(const_param) - } else { - self.next() - } - } -} - -pub struct ConstParamsMut<'a>(IterMut<'a, GenericParam>); - -impl<'a> Iterator for ConstParamsMut<'a> { - type Item = &'a mut ConstParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Const(ref mut const_param) = *next { - Some(const_param) - } else { - self.next() - } - } -} - -/// Returned by `Generics::split_for_impl`. -/// -/// *This type is available if Syn is built with the `"derive"` or `"full"` -/// feature and the `"printing"` feature.* -#[cfg(feature = "printing")] -#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] -#[cfg_attr(feature = "clone-impls", derive(Clone))] -pub struct ImplGenerics<'a>(&'a Generics); - -/// Returned by `Generics::split_for_impl`. -/// -/// *This type is available if Syn is built with the `"derive"` or `"full"` -/// feature and the `"printing"` feature.* -#[cfg(feature = "printing")] -#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] -#[cfg_attr(feature = "clone-impls", derive(Clone))] -pub struct TypeGenerics<'a>(&'a Generics); - -/// Returned by `TypeGenerics::as_turbofish`. -/// -/// *This type is available if Syn is built with the `"derive"` or `"full"` -/// feature and the `"printing"` feature.* -#[cfg(feature = "printing")] -#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] -#[cfg_attr(feature = "clone-impls", derive(Clone))] -pub struct Turbofish<'a>(&'a Generics); - -#[cfg(feature = "printing")] -impl Generics { - /// Split a type's generics into the pieces required for impl'ing a trait - /// for that type. - /// - /// ```edition2018 - /// # use proc_macro2::{Span, Ident}; - /// # use quote::quote; - /// # - /// # fn main() { - /// # let generics: syn::Generics = Default::default(); - /// # let name = Ident::new("MyType", Span::call_site()); - /// # - /// let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); - /// quote! { - /// impl #impl_generics MyTrait for #name #ty_generics #where_clause { - /// // ... - /// } - /// } - /// # ; - /// # } - /// ``` - /// - /// *This method is available if Syn is built with the `"derive"` or - /// `"full"` feature and the `"printing"` feature.* - pub fn split_for_impl(&self) -> (ImplGenerics, TypeGenerics, Option<&WhereClause>) { - ( - ImplGenerics(self), - TypeGenerics(self), - self.where_clause.as_ref(), - ) - } -} - -#[cfg(feature = "printing")] -impl<'a> TypeGenerics<'a> { - /// Turn a type's generics like `<X, Y>` into a turbofish like `::<X, Y>`. - /// - /// *This method is available if Syn is built with the `"derive"` or - /// `"full"` feature and the `"printing"` feature.* - pub fn as_turbofish(&self) -> Turbofish { - Turbofish(self.0) - } -} - -ast_struct! { - /// A set of bound lifetimes: `for<'a, 'b, 'c>`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - #[derive(Default)] - pub struct BoundLifetimes { - pub for_token: Token![for], - pub lt_token: Token![<], - pub lifetimes: Punctuated<LifetimeDef, Token![,]>, - pub gt_token: Token![>], - } -} - -impl LifetimeDef { - pub fn new(lifetime: Lifetime) -> Self { - LifetimeDef { - attrs: Vec::new(), - lifetime: lifetime, - colon_token: None, - bounds: Punctuated::new(), - } - } -} - -impl From<Ident> for TypeParam { - fn from(ident: Ident) -> Self { - TypeParam { - attrs: vec![], - ident: ident, - colon_token: None, - bounds: Punctuated::new(), - eq_token: None, - default: None, - } - } -} - -ast_enum_of_structs! { - /// A trait or lifetime used as a bound on a type parameter. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum TypeParamBound { - pub Trait(TraitBound), - pub Lifetime(Lifetime), - } -} - -ast_struct! { - /// A trait used as a bound on a type parameter. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct TraitBound { - pub paren_token: Option<token::Paren>, - pub modifier: TraitBoundModifier, - /// The `for<'a>` in `for<'a> Foo<&'a T>` - pub lifetimes: Option<BoundLifetimes>, - /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>` - pub path: Path, - } -} - -ast_enum! { - /// A modifier on a trait bound, currently only used for the `?` in - /// `?Sized`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - #[cfg_attr(feature = "clone-impls", derive(Copy))] - pub enum TraitBoundModifier { - None, - Maybe(Token![?]), - } -} - -ast_struct! { - /// A `where` clause in a definition: `where T: Deserialize<'de>, D: - /// 'static`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct WhereClause { - pub where_token: Token![where], - pub predicates: Punctuated<WherePredicate, Token![,]>, - } -} - -ast_enum_of_structs! { - /// A single predicate in a `where` clause: `T: Deserialize<'de>`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum WherePredicate { - /// A type predicate in a `where` clause: `for<'c> Foo<'c>: Trait<'c>`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Type(PredicateType { - /// Any lifetimes from a `for` binding - pub lifetimes: Option<BoundLifetimes>, - /// The type being bounded - pub bounded_ty: Type, - pub colon_token: Token![:], - /// Trait and lifetime bounds (`Clone+Send+'static`) - pub bounds: Punctuated<TypeParamBound, Token![+]>, - }), - - /// A lifetime predicate in a `where` clause: `'a: 'b + 'c`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Lifetime(PredicateLifetime { - pub lifetime: Lifetime, - pub colon_token: Token![:], - pub bounds: Punctuated<Lifetime, Token![+]>, - }), - - /// An equality predicate in a `where` clause (unsupported). - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Eq(PredicateEq { - pub lhs_ty: Type, - pub eq_token: Token![=], - pub rhs_ty: Type, - }), - } -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use parse::{Parse, ParseStream, Result}; - - impl Parse for Generics { - fn parse(input: ParseStream) -> Result<Self> { - if !input.peek(Token![<]) { - return Ok(Generics::default()); - } - - let lt_token: Token![<] = input.parse()?; - - let mut params = Punctuated::new(); - let mut allow_lifetime_param = true; - let mut allow_type_param = true; - loop { - if input.peek(Token![>]) { - break; - } - - let attrs = input.call(Attribute::parse_outer)?; - let lookahead = input.lookahead1(); - if allow_lifetime_param && lookahead.peek(Lifetime) { - params.push_value(GenericParam::Lifetime(LifetimeDef { - attrs: attrs, - ..input.parse()? - })); - } else if allow_type_param && lookahead.peek(Ident) { - allow_lifetime_param = false; - params.push_value(GenericParam::Type(TypeParam { - attrs: attrs, - ..input.parse()? - })); - } else if lookahead.peek(Token![const]) { - allow_lifetime_param = false; - allow_type_param = false; - params.push_value(GenericParam::Const(ConstParam { - attrs: attrs, - ..input.parse()? - })); - } else { - return Err(lookahead.error()); - } - - if input.peek(Token![>]) { - break; - } - let punct = input.parse()?; - params.push_punct(punct); - } - - let gt_token: Token![>] = input.parse()?; - - Ok(Generics { - lt_token: Some(lt_token), - params: params, - gt_token: Some(gt_token), - where_clause: None, - }) - } - } - - impl Parse for GenericParam { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - - let lookahead = input.lookahead1(); - if lookahead.peek(Ident) { - Ok(GenericParam::Type(TypeParam { - attrs: attrs, - ..input.parse()? - })) - } else if lookahead.peek(Lifetime) { - Ok(GenericParam::Lifetime(LifetimeDef { - attrs: attrs, - ..input.parse()? - })) - } else if lookahead.peek(Token![const]) { - Ok(GenericParam::Const(ConstParam { - attrs: attrs, - ..input.parse()? - })) - } else { - Err(lookahead.error()) - } - } - } - - impl Parse for LifetimeDef { - fn parse(input: ParseStream) -> Result<Self> { - let has_colon; - Ok(LifetimeDef { - attrs: input.call(Attribute::parse_outer)?, - lifetime: input.parse()?, - colon_token: { - if input.peek(Token![:]) { - has_colon = true; - Some(input.parse()?) - } else { - has_colon = false; - None - } - }, - bounds: { - let mut bounds = Punctuated::new(); - if has_colon { - loop { - if input.peek(Token![,]) || input.peek(Token![>]) { - break; - } - let value = input.parse()?; - bounds.push_value(value); - if !input.peek(Token![+]) { - break; - } - let punct = input.parse()?; - bounds.push_punct(punct); - } - } - bounds - }, - }) - } - } - - impl Parse for BoundLifetimes { - fn parse(input: ParseStream) -> Result<Self> { - Ok(BoundLifetimes { - for_token: input.parse()?, - lt_token: input.parse()?, - lifetimes: { - let mut lifetimes = Punctuated::new(); - while !input.peek(Token![>]) { - lifetimes.push_value(input.parse()?); - if input.peek(Token![>]) { - break; - } - lifetimes.push_punct(input.parse()?); - } - lifetimes - }, - gt_token: input.parse()?, - }) - } - } - - impl Parse for Option<BoundLifetimes> { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Token![for]) { - input.parse().map(Some) - } else { - Ok(None) - } - } - } - - impl Parse for TypeParam { - fn parse(input: ParseStream) -> Result<Self> { - let has_colon; - let has_default; - Ok(TypeParam { - attrs: input.call(Attribute::parse_outer)?, - ident: input.parse()?, - colon_token: { - if input.peek(Token![:]) { - has_colon = true; - Some(input.parse()?) - } else { - has_colon = false; - None - } - }, - bounds: { - let mut bounds = Punctuated::new(); - if has_colon { - loop { - if input.peek(Token![,]) - || input.peek(Token![>]) - || input.peek(Token![=]) - { - break; - } - let value = input.parse()?; - bounds.push_value(value); - if !input.peek(Token![+]) { - break; - } - let punct = input.parse()?; - bounds.push_punct(punct); - } - } - bounds - }, - eq_token: { - if input.peek(Token![=]) { - has_default = true; - Some(input.parse()?) - } else { - has_default = false; - None - } - }, - default: { - if has_default { - Some(input.parse()?) - } else { - None - } - }, - }) - } - } - - impl Parse for TypeParamBound { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Lifetime) { - return input.parse().map(TypeParamBound::Lifetime); - } - - if input.peek(token::Paren) { - let content; - let paren_token = parenthesized!(content in input); - let mut bound: TraitBound = content.parse()?; - bound.paren_token = Some(paren_token); - return Ok(TypeParamBound::Trait(bound)); - } - - input.parse().map(TypeParamBound::Trait) - } - } - - impl Parse for TraitBound { - fn parse(input: ParseStream) -> Result<Self> { - let modifier: TraitBoundModifier = input.parse()?; - let lifetimes: Option<BoundLifetimes> = input.parse()?; - - let mut path: Path = input.parse()?; - if path.segments.last().unwrap().value().arguments.is_empty() - && input.peek(token::Paren) - { - let parenthesized = PathArguments::Parenthesized(input.parse()?); - path.segments.last_mut().unwrap().value_mut().arguments = parenthesized; - } - - Ok(TraitBound { - paren_token: None, - modifier: modifier, - lifetimes: lifetimes, - path: path, - }) - } - } - - impl Parse for TraitBoundModifier { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Token![?]) { - input.parse().map(TraitBoundModifier::Maybe) - } else { - Ok(TraitBoundModifier::None) - } - } - } - - impl Parse for ConstParam { - fn parse(input: ParseStream) -> Result<Self> { - let mut default = None; - Ok(ConstParam { - attrs: input.call(Attribute::parse_outer)?, - const_token: input.parse()?, - ident: input.parse()?, - colon_token: input.parse()?, - ty: input.parse()?, - eq_token: { - if input.peek(Token![=]) { - let eq_token = input.parse()?; - default = Some(input.parse::<Expr>()?); - Some(eq_token) - } else { - None - } - }, - default: default, - }) - } - } - - impl Parse for WhereClause { - fn parse(input: ParseStream) -> Result<Self> { - Ok(WhereClause { - where_token: input.parse()?, - predicates: { - let mut predicates = Punctuated::new(); - loop { - if input.is_empty() - || input.peek(token::Brace) - || input.peek(Token![,]) - || input.peek(Token![;]) - || input.peek(Token![:]) && !input.peek(Token![::]) - || input.peek(Token![=]) - { - break; - } - let value = input.parse()?; - predicates.push_value(value); - if !input.peek(Token![,]) { - break; - } - let punct = input.parse()?; - predicates.push_punct(punct); - } - predicates - }, - }) - } - } - - impl Parse for Option<WhereClause> { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Token![where]) { - input.parse().map(Some) - } else { - Ok(None) - } - } - } - - impl Parse for WherePredicate { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Lifetime) && input.peek2(Token![:]) { - Ok(WherePredicate::Lifetime(PredicateLifetime { - lifetime: input.parse()?, - colon_token: input.parse()?, - bounds: { - let mut bounds = Punctuated::new(); - loop { - if input.is_empty() - || input.peek(token::Brace) - || input.peek(Token![,]) - || input.peek(Token![;]) - || input.peek(Token![:]) - || input.peek(Token![=]) - { - break; - } - let value = input.parse()?; - bounds.push_value(value); - if !input.peek(Token![+]) { - break; - } - let punct = input.parse()?; - bounds.push_punct(punct); - } - bounds - }, - })) - } else { - Ok(WherePredicate::Type(PredicateType { - lifetimes: input.parse()?, - bounded_ty: input.parse()?, - colon_token: input.parse()?, - bounds: { - let mut bounds = Punctuated::new(); - loop { - if input.is_empty() - || input.peek(token::Brace) - || input.peek(Token![,]) - || input.peek(Token![;]) - || input.peek(Token![:]) && !input.peek(Token![::]) - || input.peek(Token![=]) - { - break; - } - let value = input.parse()?; - bounds.push_value(value); - if !input.peek(Token![+]) { - break; - } - let punct = input.parse()?; - bounds.push_punct(punct); - } - bounds - }, - })) - } - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - - use proc_macro2::TokenStream; - use quote::{ToTokens, TokenStreamExt}; - - use attr::FilterAttrs; - use print::TokensOrDefault; - - impl ToTokens for Generics { - fn to_tokens(&self, tokens: &mut TokenStream) { - if self.params.is_empty() { - return; - } - - TokensOrDefault(&self.lt_token).to_tokens(tokens); - - // Print lifetimes before types and consts, regardless of their - // order in self.params. - // - // TODO: ordering rules for const parameters vs type parameters have - // not been settled yet. https://github.com/rust-lang/rust/issues/44580 - let mut trailing_or_empty = true; - for param in self.params.pairs() { - if let GenericParam::Lifetime(_) = **param.value() { - param.to_tokens(tokens); - trailing_or_empty = param.punct().is_some(); - } - } - for param in self.params.pairs() { - match **param.value() { - GenericParam::Type(_) | GenericParam::Const(_) => { - if !trailing_or_empty { - <Token![,]>::default().to_tokens(tokens); - trailing_or_empty = true; - } - param.to_tokens(tokens); - } - GenericParam::Lifetime(_) => {} - } - } - - TokensOrDefault(&self.gt_token).to_tokens(tokens); - } - } - - impl<'a> ToTokens for ImplGenerics<'a> { - fn to_tokens(&self, tokens: &mut TokenStream) { - if self.0.params.is_empty() { - return; - } - - TokensOrDefault(&self.0.lt_token).to_tokens(tokens); - - // Print lifetimes before types and consts, regardless of their - // order in self.params. - // - // TODO: ordering rules for const parameters vs type parameters have - // not been settled yet. https://github.com/rust-lang/rust/issues/44580 - let mut trailing_or_empty = true; - for param in self.0.params.pairs() { - if let GenericParam::Lifetime(_) = **param.value() { - param.to_tokens(tokens); - trailing_or_empty = param.punct().is_some(); - } - } - for param in self.0.params.pairs() { - if let GenericParam::Lifetime(_) = **param.value() { - continue; - } - if !trailing_or_empty { - <Token![,]>::default().to_tokens(tokens); - trailing_or_empty = true; - } - match **param.value() { - GenericParam::Lifetime(_) => unreachable!(), - GenericParam::Type(ref param) => { - // Leave off the type parameter defaults - tokens.append_all(param.attrs.outer()); - param.ident.to_tokens(tokens); - if !param.bounds.is_empty() { - TokensOrDefault(¶m.colon_token).to_tokens(tokens); - param.bounds.to_tokens(tokens); - } - } - GenericParam::Const(ref param) => { - // Leave off the const parameter defaults - tokens.append_all(param.attrs.outer()); - param.const_token.to_tokens(tokens); - param.ident.to_tokens(tokens); - param.colon_token.to_tokens(tokens); - param.ty.to_tokens(tokens); - } - } - param.punct().to_tokens(tokens); - } - - TokensOrDefault(&self.0.gt_token).to_tokens(tokens); - } - } - - impl<'a> ToTokens for TypeGenerics<'a> { - fn to_tokens(&self, tokens: &mut TokenStream) { - if self.0.params.is_empty() { - return; - } - - TokensOrDefault(&self.0.lt_token).to_tokens(tokens); - - // Print lifetimes before types and consts, regardless of their - // order in self.params. - // - // TODO: ordering rules for const parameters vs type parameters have - // not been settled yet. https://github.com/rust-lang/rust/issues/44580 - let mut trailing_or_empty = true; - for param in self.0.params.pairs() { - if let GenericParam::Lifetime(ref def) = **param.value() { - // Leave off the lifetime bounds and attributes - def.lifetime.to_tokens(tokens); - param.punct().to_tokens(tokens); - trailing_or_empty = param.punct().is_some(); - } - } - for param in self.0.params.pairs() { - if let GenericParam::Lifetime(_) = **param.value() { - continue; - } - if !trailing_or_empty { - <Token![,]>::default().to_tokens(tokens); - trailing_or_empty = true; - } - match **param.value() { - GenericParam::Lifetime(_) => unreachable!(), - GenericParam::Type(ref param) => { - // Leave off the type parameter defaults - param.ident.to_tokens(tokens); - } - GenericParam::Const(ref param) => { - // Leave off the const parameter defaults - param.ident.to_tokens(tokens); - } - } - param.punct().to_tokens(tokens); - } - - TokensOrDefault(&self.0.gt_token).to_tokens(tokens); - } - } - - impl<'a> ToTokens for Turbofish<'a> { - fn to_tokens(&self, tokens: &mut TokenStream) { - if !self.0.params.is_empty() { - <Token![::]>::default().to_tokens(tokens); - TypeGenerics(self.0).to_tokens(tokens); - } - } - } - - impl ToTokens for BoundLifetimes { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.for_token.to_tokens(tokens); - self.lt_token.to_tokens(tokens); - self.lifetimes.to_tokens(tokens); - self.gt_token.to_tokens(tokens); - } - } - - impl ToTokens for LifetimeDef { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.lifetime.to_tokens(tokens); - if !self.bounds.is_empty() { - TokensOrDefault(&self.colon_token).to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - } - } - - impl ToTokens for TypeParam { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.ident.to_tokens(tokens); - if !self.bounds.is_empty() { - TokensOrDefault(&self.colon_token).to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - if self.default.is_some() { - TokensOrDefault(&self.eq_token).to_tokens(tokens); - self.default.to_tokens(tokens); - } - } - } - - impl ToTokens for TraitBound { - fn to_tokens(&self, tokens: &mut TokenStream) { - let to_tokens = |tokens: &mut TokenStream| { - self.modifier.to_tokens(tokens); - self.lifetimes.to_tokens(tokens); - self.path.to_tokens(tokens); - }; - match self.paren_token { - Some(ref paren) => paren.surround(tokens, to_tokens), - None => to_tokens(tokens), - } - } - } - - impl ToTokens for TraitBoundModifier { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - TraitBoundModifier::None => {} - TraitBoundModifier::Maybe(ref t) => t.to_tokens(tokens), - } - } - } - - impl ToTokens for ConstParam { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.const_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - if self.default.is_some() { - TokensOrDefault(&self.eq_token).to_tokens(tokens); - self.default.to_tokens(tokens); - } - } - } - - impl ToTokens for WhereClause { - fn to_tokens(&self, tokens: &mut TokenStream) { - if !self.predicates.is_empty() { - self.where_token.to_tokens(tokens); - self.predicates.to_tokens(tokens); - } - } - } - - impl ToTokens for PredicateType { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.lifetimes.to_tokens(tokens); - self.bounded_ty.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - } - - impl ToTokens for PredicateLifetime { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.lifetime.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - } - - impl ToTokens for PredicateEq { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.lhs_ty.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.rhs_ty.to_tokens(tokens); - } - } -} diff --git a/0.15.42/src/group.rs b/0.15.42/src/group.rs deleted file mode 100644 index f0ad7b4c..00000000 --- a/0.15.42/src/group.rs +++ /dev/null @@ -1,286 +0,0 @@ -use proc_macro2::{Delimiter, Span}; - -use error::Result; -use parse::ParseBuffer; -use private; -use token; - -// Not public API. -#[doc(hidden)] -pub struct Parens<'a> { - pub token: token::Paren, - pub content: ParseBuffer<'a>, -} - -// Not public API. -#[doc(hidden)] -pub struct Braces<'a> { - pub token: token::Brace, - pub content: ParseBuffer<'a>, -} - -// Not public API. -#[doc(hidden)] -pub struct Brackets<'a> { - pub token: token::Bracket, - pub content: ParseBuffer<'a>, -} - -// Not public API. -#[cfg(any(feature = "full", feature = "derive"))] -#[doc(hidden)] -pub struct Group<'a> { - pub token: token::Group, - pub content: ParseBuffer<'a>, -} - -// Not public API. -#[doc(hidden)] -pub fn parse_parens<'a>(input: &ParseBuffer<'a>) -> Result<Parens<'a>> { - parse_delimited(input, Delimiter::Parenthesis).map(|(span, content)| Parens { - token: token::Paren(span), - content: content, - }) -} - -// Not public API. -#[doc(hidden)] -pub fn parse_braces<'a>(input: &ParseBuffer<'a>) -> Result<Braces<'a>> { - parse_delimited(input, Delimiter::Brace).map(|(span, content)| Braces { - token: token::Brace(span), - content: content, - }) -} - -// Not public API. -#[doc(hidden)] -pub fn parse_brackets<'a>(input: &ParseBuffer<'a>) -> Result<Brackets<'a>> { - parse_delimited(input, Delimiter::Bracket).map(|(span, content)| Brackets { - token: token::Bracket(span), - content: content, - }) -} - -#[cfg(any(feature = "full", feature = "derive"))] -impl private { - pub fn parse_group<'a>(input: &ParseBuffer<'a>) -> Result<Group<'a>> { - parse_delimited(input, Delimiter::None).map(|(span, content)| Group { - token: token::Group(span), - content: content, - }) - } -} - -fn parse_delimited<'a>( - input: &ParseBuffer<'a>, - delimiter: Delimiter, -) -> Result<(Span, ParseBuffer<'a>)> { - input.step(|cursor| { - if let Some((content, span, rest)) = cursor.group(delimiter) { - #[cfg(procmacro2_semver_exempt)] - let scope = private::close_span_of_group(*cursor); - #[cfg(not(procmacro2_semver_exempt))] - let scope = span; - let nested = private::advance_step_cursor(cursor, content); - let unexpected = private::get_unexpected(input); - let content = private::new_parse_buffer(scope, nested, unexpected); - Ok(((span, content), rest)) - } else { - let message = match delimiter { - Delimiter::Parenthesis => "expected parentheses", - Delimiter::Brace => "expected curly braces", - Delimiter::Bracket => "expected square brackets", - Delimiter::None => "expected invisible group", - }; - Err(cursor.error(message)) - } - }) -} - -/// Parse a set of parentheses and expose their content to subsequent parsers. -/// -/// # Example -/// -/// ```edition2018 -/// # use quote::quote; -/// # -/// use syn::{parenthesized, token, Ident, Result, Token, Type}; -/// use syn::parse::{Parse, ParseStream}; -/// use syn::punctuated::Punctuated; -/// -/// // Parse a simplified tuple struct syntax like: -/// // -/// // struct S(A, B); -/// struct TupleStruct { -/// struct_token: Token![struct], -/// ident: Ident, -/// paren_token: token::Paren, -/// fields: Punctuated<Type, Token![,]>, -/// semi_token: Token![;], -/// } -/// -/// impl Parse for TupleStruct { -/// fn parse(input: ParseStream) -> Result<Self> { -/// let content; -/// Ok(TupleStruct { -/// struct_token: input.parse()?, -/// ident: input.parse()?, -/// paren_token: parenthesized!(content in input), -/// fields: content.parse_terminated(Type::parse)?, -/// semi_token: input.parse()?, -/// }) -/// } -/// } -/// # -/// # fn main() { -/// # let input = quote! { -/// # struct S(A, B); -/// # }; -/// # syn::parse2::<TupleStruct>(input).unwrap(); -/// # } -/// ``` -#[macro_export] -macro_rules! parenthesized { - ($content:ident in $cursor:expr) => { - match $crate::group::parse_parens(&$cursor) { - $crate::export::Ok(parens) => { - $content = parens.content; - parens.token - } - $crate::export::Err(error) => { - return $crate::export::Err(error); - } - } - }; -} - -/// Parse a set of curly braces and expose their content to subsequent parsers. -/// -/// # Example -/// -/// ```edition2018 -/// # use quote::quote; -/// # -/// use syn::{braced, token, Ident, Result, Token, Type}; -/// use syn::parse::{Parse, ParseStream}; -/// use syn::punctuated::Punctuated; -/// -/// // Parse a simplified struct syntax like: -/// // -/// // struct S { -/// // a: A, -/// // b: B, -/// // } -/// struct Struct { -/// struct_token: Token![struct], -/// ident: Ident, -/// brace_token: token::Brace, -/// fields: Punctuated<Field, Token![,]>, -/// } -/// -/// struct Field { -/// name: Ident, -/// colon_token: Token![:], -/// ty: Type, -/// } -/// -/// impl Parse for Struct { -/// fn parse(input: ParseStream) -> Result<Self> { -/// let content; -/// Ok(Struct { -/// struct_token: input.parse()?, -/// ident: input.parse()?, -/// brace_token: braced!(content in input), -/// fields: content.parse_terminated(Field::parse)?, -/// }) -/// } -/// } -/// -/// impl Parse for Field { -/// fn parse(input: ParseStream) -> Result<Self> { -/// Ok(Field { -/// name: input.parse()?, -/// colon_token: input.parse()?, -/// ty: input.parse()?, -/// }) -/// } -/// } -/// # -/// # fn main() { -/// # let input = quote! { -/// # struct S { -/// # a: A, -/// # b: B, -/// # } -/// # }; -/// # syn::parse2::<Struct>(input).unwrap(); -/// # } -/// ``` -#[macro_export] -macro_rules! braced { - ($content:ident in $cursor:expr) => { - match $crate::group::parse_braces(&$cursor) { - $crate::export::Ok(braces) => { - $content = braces.content; - braces.token - } - $crate::export::Err(error) => { - return $crate::export::Err(error); - } - } - }; -} - -/// Parse a set of square brackets and expose their content to subsequent -/// parsers. -/// -/// # Example -/// -/// ```edition2018 -/// # use quote::quote; -/// # -/// use proc_macro2::TokenStream; -/// use syn::{bracketed, token, Result, Token}; -/// use syn::parse::{Parse, ParseStream}; -/// -/// // Parse an outer attribute like: -/// // -/// // #[repr(C, packed)] -/// struct OuterAttribute { -/// pound_token: Token![#], -/// bracket_token: token::Bracket, -/// content: TokenStream, -/// } -/// -/// impl Parse for OuterAttribute { -/// fn parse(input: ParseStream) -> Result<Self> { -/// let content; -/// Ok(OuterAttribute { -/// pound_token: input.parse()?, -/// bracket_token: bracketed!(content in input), -/// content: content.parse()?, -/// }) -/// } -/// } -/// # -/// # fn main() { -/// # let input = quote! { -/// # #[repr(C, packed)] -/// # }; -/// # syn::parse2::<OuterAttribute>(input).unwrap(); -/// # } -/// ``` -#[macro_export] -macro_rules! bracketed { - ($content:ident in $cursor:expr) => { - match $crate::group::parse_brackets(&$cursor) { - $crate::export::Ok(brackets) => { - $content = brackets.content; - brackets.token - } - $crate::export::Err(error) => { - return $crate::export::Err(error); - } - } - }; -} diff --git a/0.15.42/src/ident.rs b/0.15.42/src/ident.rs deleted file mode 100644 index 41279aee..00000000 --- a/0.15.42/src/ident.rs +++ /dev/null @@ -1,100 +0,0 @@ -#[cfg(feature = "parsing")] -use buffer::Cursor; -#[cfg(feature = "parsing")] -use parse::{Parse, ParseStream, Result}; -#[cfg(feature = "parsing")] -use token::Token; -#[cfg(feature = "parsing")] -use {lookahead, private}; - -pub use proc_macro2::Ident; - -#[cfg(feature = "parsing")] -#[doc(hidden)] -#[allow(non_snake_case)] -pub fn Ident(marker: lookahead::TokenMarker) -> Ident { - match marker {} -} - -#[cfg(feature = "parsing")] -fn accept_as_ident(ident: &Ident) -> bool { - match ident.to_string().as_str() { - "_" | - // Based on https://doc.rust-lang.org/grammar.html#keywords - // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md - // and https://github.com/rust-lang/rfcs/blob/master/text/2420-unreserve-proc.md - "abstract" | "as" | "become" | "box" | "break" | "const" | "continue" | - "crate" | "do" | "else" | "enum" | "extern" | "false" | "final" | "fn" | - "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match" | - "mod" | "move" | "mut" | "override" | "priv" | "pub" | "ref" | - "return" | "Self" | "self" | "static" | "struct" | "super" | "trait" | - "true" | "type" | "typeof" | "unsafe" | "unsized" | "use" | "virtual" | - "where" | "while" | "yield" => false, - _ => true, - } -} - -#[cfg(feature = "parsing")] -impl Parse for Ident { - fn parse(input: ParseStream) -> Result<Self> { - input.step(|cursor| { - if let Some((ident, rest)) = cursor.ident() { - if accept_as_ident(&ident) { - return Ok((ident, rest)); - } - } - Err(cursor.error("expected identifier")) - }) - } -} - -#[cfg(feature = "parsing")] -impl Token for Ident { - fn peek(cursor: Cursor) -> bool { - if let Some((ident, _rest)) = cursor.ident() { - accept_as_ident(&ident) - } else { - false - } - } - - fn display() -> &'static str { - "identifier" - } -} - -macro_rules! ident_from_token { - ($token:ident) => { - impl From<Token![$token]> for Ident { - fn from(token: Token![$token]) -> Ident { - Ident::new(stringify!($token), token.span) - } - } - }; -} - -ident_from_token!(self); -ident_from_token!(Self); -ident_from_token!(super); -ident_from_token!(crate); -ident_from_token!(extern); - -impl From<Token![_]> for Ident { - fn from(token: Token![_]) -> Ident { - Ident::new("_", token.span) - } -} - -#[cfg(feature = "parsing")] -impl private { - #[cfg(syn_can_use_associated_constants)] - pub fn peek_any_ident(input: ParseStream) -> bool { - use ext::IdentExt; - input.peek(Ident::peek_any) - } - - #[cfg(not(syn_can_use_associated_constants))] - pub fn peek_any_ident(input: ParseStream) -> bool { - input.cursor().ident().is_some() - } -} diff --git a/0.15.42/src/item.rs b/0.15.42/src/item.rs deleted file mode 100644 index 06346578..00000000 --- a/0.15.42/src/item.rs +++ /dev/null @@ -1,2771 +0,0 @@ -use super::*; -use derive::{Data, DeriveInput}; -use proc_macro2::TokenStream; -use punctuated::Punctuated; -use token::{Brace, Paren}; - -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; -#[cfg(feature = "extra-traits")] -use tt::TokenStreamHelper; - -ast_enum_of_structs! { - /// Things that can appear directly inside of a module or scope. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Item { - /// An `extern crate` item: `extern crate serde`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub ExternCrate(ItemExternCrate { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub extern_token: Token![extern], - pub crate_token: Token![crate], - pub ident: Ident, - pub rename: Option<(Token![as], Ident)>, - pub semi_token: Token![;], - }), - - /// A use declaration: `use std::collections::HashMap`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Use(ItemUse { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub use_token: Token![use], - pub leading_colon: Option<Token![::]>, - pub tree: UseTree, - pub semi_token: Token![;], - }), - - /// A static item: `static BIKE: Shed = Shed(42)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Static(ItemStatic { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub static_token: Token![static], - pub mutability: Option<Token![mut]>, - pub ident: Ident, - pub colon_token: Token![:], - pub ty: Box<Type>, - pub eq_token: Token![=], - pub expr: Box<Expr>, - pub semi_token: Token![;], - }), - - /// A constant item: `const MAX: u16 = 65535`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Const(ItemConst { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub const_token: Token![const], - pub ident: Ident, - pub colon_token: Token![:], - pub ty: Box<Type>, - pub eq_token: Token![=], - pub expr: Box<Expr>, - pub semi_token: Token![;], - }), - - /// A free-standing function: `fn process(n: usize) -> Result<()> { ... - /// }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Fn(ItemFn { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub constness: Option<Token![const]>, - pub asyncness: Option<Token![async]>, - pub unsafety: Option<Token![unsafe]>, - pub abi: Option<Abi>, - pub ident: Ident, - pub decl: Box<FnDecl>, - pub block: Box<Block>, - }), - - /// A module or module declaration: `mod m` or `mod m { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Mod(ItemMod { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub mod_token: Token![mod], - pub ident: Ident, - pub content: Option<(token::Brace, Vec<Item>)>, - pub semi: Option<Token![;]>, - }), - - /// A block of foreign items: `extern "C" { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub ForeignMod(ItemForeignMod { - pub attrs: Vec<Attribute>, - pub abi: Abi, - pub brace_token: token::Brace, - pub items: Vec<ForeignItem>, - }), - - /// A type alias: `type Result<T> = std::result::Result<T, MyError>`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Type(ItemType { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub type_token: Token![type], - pub ident: Ident, - pub generics: Generics, - pub eq_token: Token![=], - pub ty: Box<Type>, - pub semi_token: Token![;], - }), - - /// An existential type: `existential type Iter: Iterator<Item = u8>`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Existential(ItemExistential { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub existential_token: Token![existential], - pub type_token: Token![type], - pub ident: Ident, - pub generics: Generics, - pub colon_token: Option<Token![:]>, - pub bounds: Punctuated<TypeParamBound, Token![+]>, - pub semi_token: Token![;], - }), - - /// A struct definition: `struct Foo<A> { x: A }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Struct(ItemStruct { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub struct_token: Token![struct], - pub ident: Ident, - pub generics: Generics, - pub fields: Fields, - pub semi_token: Option<Token![;]>, - }), - - /// An enum definition: `enum Foo<A, B> { C<A>, D<B> }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Enum(ItemEnum { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub enum_token: Token![enum], - pub ident: Ident, - pub generics: Generics, - pub brace_token: token::Brace, - pub variants: Punctuated<Variant, Token![,]>, - }), - - /// A union definition: `union Foo<A, B> { x: A, y: B }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Union(ItemUnion { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub union_token: Token![union], - pub ident: Ident, - pub generics: Generics, - pub fields: FieldsNamed, - }), - - /// A trait definition: `pub trait Iterator { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Trait(ItemTrait { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub unsafety: Option<Token![unsafe]>, - pub auto_token: Option<Token![auto]>, - pub trait_token: Token![trait], - pub ident: Ident, - pub generics: Generics, - pub colon_token: Option<Token![:]>, - pub supertraits: Punctuated<TypeParamBound, Token![+]>, - pub brace_token: token::Brace, - pub items: Vec<TraitItem>, - }), - - /// A trait alias: `pub trait SharableIterator = Iterator + Sync`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub TraitAlias(ItemTraitAlias { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub trait_token: Token![trait], - pub ident: Ident, - pub generics: Generics, - pub eq_token: Token![=], - pub bounds: Punctuated<TypeParamBound, Token![+]>, - pub semi_token: Token![;], - }), - - /// An impl block providing trait or associated items: `impl<A> Trait - /// for Data<A> { ... }`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Impl(ItemImpl { - pub attrs: Vec<Attribute>, - pub defaultness: Option<Token![default]>, - pub unsafety: Option<Token![unsafe]>, - pub impl_token: Token![impl], - pub generics: Generics, - /// Trait this impl implements. - pub trait_: Option<(Option<Token![!]>, Path, Token![for])>, - /// The Self type of the impl. - pub self_ty: Box<Type>, - pub brace_token: token::Brace, - pub items: Vec<ImplItem>, - }), - - /// A macro invocation, which includes `macro_rules!` definitions. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Macro(ItemMacro { - pub attrs: Vec<Attribute>, - /// The `example` in `macro_rules! example { ... }`. - pub ident: Option<Ident>, - pub mac: Macro, - pub semi_token: Option<Token![;]>, - }), - - /// A 2.0-style declarative macro introduced by the `macro` keyword. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Macro2(ItemMacro2 #manual_extra_traits { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub macro_token: Token![macro], - pub ident: Ident, - pub paren_token: Paren, - pub args: TokenStream, - pub brace_token: Brace, - pub body: TokenStream, - }), - - /// Tokens forming an item not interpreted by Syn. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Verbatim(ItemVerbatim #manual_extra_traits { - pub tts: TokenStream, - }), - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for ItemMacro2 {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for ItemMacro2 { - fn eq(&self, other: &Self) -> bool { - self.attrs == other.attrs - && self.vis == other.vis - && self.macro_token == other.macro_token - && self.ident == other.ident - && self.paren_token == other.paren_token - && TokenStreamHelper(&self.args) == TokenStreamHelper(&other.args) - && self.brace_token == other.brace_token - && TokenStreamHelper(&self.body) == TokenStreamHelper(&other.body) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for ItemMacro2 { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - self.attrs.hash(state); - self.vis.hash(state); - self.macro_token.hash(state); - self.ident.hash(state); - self.paren_token.hash(state); - TokenStreamHelper(&self.args).hash(state); - self.brace_token.hash(state); - TokenStreamHelper(&self.body).hash(state); - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for ItemVerbatim {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for ItemVerbatim { - fn eq(&self, other: &Self) -> bool { - TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for ItemVerbatim { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - TokenStreamHelper(&self.tts).hash(state); - } -} - -impl From<DeriveInput> for Item { - fn from(input: DeriveInput) -> Item { - match input.data { - Data::Struct(data) => Item::Struct(ItemStruct { - attrs: input.attrs, - vis: input.vis, - struct_token: data.struct_token, - ident: input.ident, - generics: input.generics, - fields: data.fields, - semi_token: data.semi_token, - }), - Data::Enum(data) => Item::Enum(ItemEnum { - attrs: input.attrs, - vis: input.vis, - enum_token: data.enum_token, - ident: input.ident, - generics: input.generics, - brace_token: data.brace_token, - variants: data.variants, - }), - Data::Union(data) => Item::Union(ItemUnion { - attrs: input.attrs, - vis: input.vis, - union_token: data.union_token, - ident: input.ident, - generics: input.generics, - fields: data.fields, - }), - } - } -} - -ast_enum_of_structs! { - /// A suffix of an import tree in a `use` item: `Type as Renamed` or `*`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum UseTree { - /// A path prefix of imports in a `use` item: `std::...`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Path(UsePath { - pub ident: Ident, - pub colon2_token: Token![::], - pub tree: Box<UseTree>, - }), - - /// An identifier imported by a `use` item: `HashMap`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Name(UseName { - pub ident: Ident, - }), - - /// An renamed identifier imported by a `use` item: `HashMap as Map`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Rename(UseRename { - pub ident: Ident, - pub as_token: Token![as], - pub rename: Ident, - }), - - /// A glob import in a `use` item: `*`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Glob(UseGlob { - pub star_token: Token![*], - }), - - /// A braced group of imports in a `use` item: `{A, B, C}`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Group(UseGroup { - pub brace_token: token::Brace, - pub items: Punctuated<UseTree, Token![,]>, - }), - } -} - -ast_enum_of_structs! { - /// An item within an `extern` block. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum ForeignItem { - /// A foreign function in an `extern` block. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Fn(ForeignItemFn { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub ident: Ident, - pub decl: Box<FnDecl>, - pub semi_token: Token![;], - }), - - /// A foreign static item in an `extern` block: `static ext: u8`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Static(ForeignItemStatic { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub static_token: Token![static], - pub mutability: Option<Token![mut]>, - pub ident: Ident, - pub colon_token: Token![:], - pub ty: Box<Type>, - pub semi_token: Token![;], - }), - - /// A foreign type in an `extern` block: `type void`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Type(ForeignItemType { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub type_token: Token![type], - pub ident: Ident, - pub semi_token: Token![;], - }), - - /// A macro invocation within an extern block. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Macro(ForeignItemMacro { - pub attrs: Vec<Attribute>, - pub mac: Macro, - pub semi_token: Option<Token![;]>, - }), - - /// Tokens in an `extern` block not interpreted by Syn. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Verbatim(ForeignItemVerbatim #manual_extra_traits { - pub tts: TokenStream, - }), - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for ForeignItemVerbatim {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for ForeignItemVerbatim { - fn eq(&self, other: &Self) -> bool { - TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for ForeignItemVerbatim { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - TokenStreamHelper(&self.tts).hash(state); - } -} - -ast_enum_of_structs! { - /// An item declaration within the definition of a trait. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum TraitItem { - /// An associated constant within the definition of a trait. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Const(TraitItemConst { - pub attrs: Vec<Attribute>, - pub const_token: Token![const], - pub ident: Ident, - pub colon_token: Token![:], - pub ty: Type, - pub default: Option<(Token![=], Expr)>, - pub semi_token: Token![;], - }), - - /// A trait method within the definition of a trait. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Method(TraitItemMethod { - pub attrs: Vec<Attribute>, - pub sig: MethodSig, - pub default: Option<Block>, - pub semi_token: Option<Token![;]>, - }), - - /// An associated type within the definition of a trait. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Type(TraitItemType { - pub attrs: Vec<Attribute>, - pub type_token: Token![type], - pub ident: Ident, - pub generics: Generics, - pub colon_token: Option<Token![:]>, - pub bounds: Punctuated<TypeParamBound, Token![+]>, - pub default: Option<(Token![=], Type)>, - pub semi_token: Token![;], - }), - - /// A macro invocation within the definition of a trait. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Macro(TraitItemMacro { - pub attrs: Vec<Attribute>, - pub mac: Macro, - pub semi_token: Option<Token![;]>, - }), - - /// Tokens within the definition of a trait not interpreted by Syn. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Verbatim(TraitItemVerbatim #manual_extra_traits { - pub tts: TokenStream, - }), - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for TraitItemVerbatim {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for TraitItemVerbatim { - fn eq(&self, other: &Self) -> bool { - TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for TraitItemVerbatim { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - TokenStreamHelper(&self.tts).hash(state); - } -} - -ast_enum_of_structs! { - /// An item within an impl block. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum ImplItem { - /// An associated constant within an impl block. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Const(ImplItemConst { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub defaultness: Option<Token![default]>, - pub const_token: Token![const], - pub ident: Ident, - pub colon_token: Token![:], - pub ty: Type, - pub eq_token: Token![=], - pub expr: Expr, - pub semi_token: Token![;], - }), - - /// A method within an impl block. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Method(ImplItemMethod { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub defaultness: Option<Token![default]>, - pub sig: MethodSig, - pub block: Block, - }), - - /// An associated type within an impl block. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Type(ImplItemType { - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub defaultness: Option<Token![default]>, - pub type_token: Token![type], - pub ident: Ident, - pub generics: Generics, - pub eq_token: Token![=], - pub ty: Type, - pub semi_token: Token![;], - }), - - /// An existential type within an impl block. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Existential(ImplItemExistential { - pub attrs: Vec<Attribute>, - pub existential_token: Token![existential], - pub type_token: Token![type], - pub ident: Ident, - pub generics: Generics, - pub colon_token: Option<Token![:]>, - pub bounds: Punctuated<TypeParamBound, Token![+]>, - pub semi_token: Token![;], - }), - - /// A macro invocation within an impl block. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Macro(ImplItemMacro { - pub attrs: Vec<Attribute>, - pub mac: Macro, - pub semi_token: Option<Token![;]>, - }), - - /// Tokens within an impl block not interpreted by Syn. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Verbatim(ImplItemVerbatim #manual_extra_traits { - pub tts: TokenStream, - }), - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for ImplItemVerbatim {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for ImplItemVerbatim { - fn eq(&self, other: &Self) -> bool { - TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for ImplItemVerbatim { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - TokenStreamHelper(&self.tts).hash(state); - } -} - -ast_struct! { - /// A method's signature in a trait or implementation: `unsafe fn - /// initialize(&self)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct MethodSig { - pub constness: Option<Token![const]>, - pub asyncness: Option<Token![async]>, - pub unsafety: Option<Token![unsafe]>, - pub abi: Option<Abi>, - pub ident: Ident, - pub decl: FnDecl, - } -} - -ast_struct! { - /// Header of a function declaration, without including the body. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct FnDecl { - pub fn_token: Token![fn], - pub generics: Generics, - pub paren_token: token::Paren, - pub inputs: Punctuated<FnArg, Token![,]>, - pub variadic: Option<Token![...]>, - pub output: ReturnType, - } -} - -ast_enum_of_structs! { - /// An argument in a function signature: the `n: usize` in `fn f(n: usize)`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum FnArg { - /// Self captured by reference in a function signature: `&self` or `&mut - /// self`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub SelfRef(ArgSelfRef { - pub and_token: Token![&], - pub lifetime: Option<Lifetime>, - pub mutability: Option<Token![mut]>, - pub self_token: Token![self], - }), - - /// Self captured by value in a function signature: `self` or `mut - /// self`. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub SelfValue(ArgSelf { - pub mutability: Option<Token![mut]>, - pub self_token: Token![self], - }), - - /// An explicitly typed pattern captured by a function signature. - /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub Captured(ArgCaptured { - pub pat: Pat, - pub colon_token: Token![:], - pub ty: Type, - }), - - /// A pattern whose type is inferred captured by a function signature. - pub Inferred(Pat), - /// A type not bound to any pattern in a function signature. - pub Ignored(Type), - } -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use ext::IdentExt; - use parse::{Parse, ParseStream, Result}; - use proc_macro2::{Punct, Spacing, TokenTree}; - use std::iter::FromIterator; - - impl Parse for Item { - fn parse(input: ParseStream) -> Result<Self> { - let mut attrs = input.call(Attribute::parse_outer)?; - let ahead = input.fork(); - let vis: Visibility = ahead.parse()?; - - let lookahead = ahead.lookahead1(); - let mut item = if lookahead.peek(Token![extern]) { - ahead.parse::<Token![extern]>()?; - let lookahead = ahead.lookahead1(); - if lookahead.peek(Token![crate]) { - input.parse().map(Item::ExternCrate) - } else if lookahead.peek(Token![fn]) { - input.parse().map(Item::Fn) - } else if lookahead.peek(token::Brace) { - input.parse().map(Item::ForeignMod) - } else if lookahead.peek(LitStr) { - ahead.parse::<LitStr>()?; - let lookahead = ahead.lookahead1(); - if lookahead.peek(token::Brace) { - input.parse().map(Item::ForeignMod) - } else if lookahead.peek(Token![fn]) { - input.parse().map(Item::Fn) - } else { - Err(lookahead.error()) - } - } else { - Err(lookahead.error()) - } - } else if lookahead.peek(Token![use]) { - input.parse().map(Item::Use) - } else if lookahead.peek(Token![static]) { - input.parse().map(Item::Static) - } else if lookahead.peek(Token![const]) { - ahead.parse::<Token![const]>()?; - let lookahead = ahead.lookahead1(); - if lookahead.peek(Ident) || lookahead.peek(Token![_]) { - input.parse().map(Item::Const) - } else if lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![async]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(Item::Fn) - } else { - Err(lookahead.error()) - } - } else if lookahead.peek(Token![unsafe]) { - ahead.parse::<Token![unsafe]>()?; - let lookahead = ahead.lookahead1(); - if lookahead.peek(Token![trait]) - || lookahead.peek(Token![auto]) && ahead.peek2(Token![trait]) - { - input.parse().map(Item::Trait) - } else if lookahead.peek(Token![impl]) { - input.parse().map(Item::Impl) - } else if lookahead.peek(Token![async]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(Item::Fn) - } else { - Err(lookahead.error()) - } - } else if lookahead.peek(Token![async]) || lookahead.peek(Token![fn]) { - input.parse().map(Item::Fn) - } else if lookahead.peek(Token![mod]) { - input.parse().map(Item::Mod) - } else if lookahead.peek(Token![type]) { - input.parse().map(Item::Type) - } else if lookahead.peek(Token![existential]) { - input.parse().map(Item::Existential) - } else if lookahead.peek(Token![struct]) { - input.parse().map(Item::Struct) - } else if lookahead.peek(Token![enum]) { - input.parse().map(Item::Enum) - } else if lookahead.peek(Token![union]) && ahead.peek2(Ident) { - input.parse().map(Item::Union) - } else if lookahead.peek(Token![trait]) { - input.call(parse_trait_or_trait_alias) - } else if lookahead.peek(Token![auto]) && ahead.peek2(Token![trait]) { - input.parse().map(Item::Trait) - } else if lookahead.peek(Token![impl]) - || lookahead.peek(Token![default]) && !ahead.peek2(Token![!]) - { - input.parse().map(Item::Impl) - } else if lookahead.peek(Token![macro]) { - input.parse().map(Item::Macro2) - } else if vis.is_inherited() - && (lookahead.peek(Ident) - || lookahead.peek(Token![self]) - || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![crate]) - || lookahead.peek(Token![::])) - { - input.parse().map(Item::Macro) - } else { - Err(lookahead.error()) - }?; - - { - let item_attrs = match item { - Item::ExternCrate(ref mut item) => &mut item.attrs, - Item::Use(ref mut item) => &mut item.attrs, - Item::Static(ref mut item) => &mut item.attrs, - Item::Const(ref mut item) => &mut item.attrs, - Item::Fn(ref mut item) => &mut item.attrs, - Item::Mod(ref mut item) => &mut item.attrs, - Item::ForeignMod(ref mut item) => &mut item.attrs, - Item::Type(ref mut item) => &mut item.attrs, - Item::Existential(ref mut item) => &mut item.attrs, - Item::Struct(ref mut item) => &mut item.attrs, - Item::Enum(ref mut item) => &mut item.attrs, - Item::Union(ref mut item) => &mut item.attrs, - Item::Trait(ref mut item) => &mut item.attrs, - Item::TraitAlias(ref mut item) => &mut item.attrs, - Item::Impl(ref mut item) => &mut item.attrs, - Item::Macro(ref mut item) => &mut item.attrs, - Item::Macro2(ref mut item) => &mut item.attrs, - Item::Verbatim(_) => unreachable!(), - }; - attrs.extend(item_attrs.drain(..)); - *item_attrs = attrs; - } - - Ok(item) - } - } - - impl Parse for ItemMacro { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let path = input.call(Path::parse_mod_style)?; - let bang_token: Token![!] = input.parse()?; - let ident: Option<Ident> = input.parse()?; - let (delimiter, tts) = input.call(mac::parse_delimiter)?; - let semi_token: Option<Token![;]> = if !delimiter.is_brace() { - Some(input.parse()?) - } else { - None - }; - Ok(ItemMacro { - attrs: attrs, - ident: ident, - mac: Macro { - path: path, - bang_token: bang_token, - delimiter: delimiter, - tts: tts, - }, - semi_token: semi_token, - }) - } - } - - // TODO: figure out the actual grammar; is body required to be braced? - impl Parse for ItemMacro2 { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let vis: Visibility = input.parse()?; - let macro_token: Token![macro] = input.parse()?; - let ident: Ident = input.parse()?; - - let paren_token; - let args; - let brace_token; - let body; - let lookahead = input.lookahead1(); - if lookahead.peek(token::Paren) { - let paren_content; - paren_token = parenthesized!(paren_content in input); - args = paren_content.parse()?; - - let brace_content; - brace_token = braced!(brace_content in input); - body = brace_content.parse()?; - } else if lookahead.peek(token::Brace) { - // Hack: the ItemMacro2 syntax tree will need to change so that - // we can store None for the args. - // - // https://github.com/dtolnay/syn/issues/548 - // - // For now, store some sentinel tokens that are otherwise - // illegal. - paren_token = token::Paren::default(); - args = TokenStream::from_iter(vec![ - TokenTree::Punct(Punct::new('$', Spacing::Alone)), - TokenTree::Punct(Punct::new('$', Spacing::Alone)), - ]); - - let brace_content; - brace_token = braced!(brace_content in input); - body = brace_content.parse()?; - } else { - return Err(lookahead.error()); - } - - Ok(ItemMacro2 { - attrs: attrs, - vis: vis, - macro_token: macro_token, - ident: ident, - paren_token: paren_token, - args: args, - brace_token: brace_token, - body: body, - }) - } - } - - impl Parse for ItemExternCrate { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ItemExternCrate { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - extern_token: input.parse()?, - crate_token: input.parse()?, - ident: { - if input.peek(Token![self]) { - input.call(Ident::parse_any)? - } else { - input.parse()? - } - }, - rename: { - if input.peek(Token![as]) { - let as_token: Token![as] = input.parse()?; - let rename: Ident = input.parse()?; - Some((as_token, rename)) - } else { - None - } - }, - semi_token: input.parse()?, - }) - } - } - - impl Parse for ItemUse { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ItemUse { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - use_token: input.parse()?, - leading_colon: input.parse()?, - tree: input.parse()?, - semi_token: input.parse()?, - }) - } - } - - impl Parse for UseTree { - fn parse(input: ParseStream) -> Result<UseTree> { - let lookahead = input.lookahead1(); - if lookahead.peek(Ident) - || lookahead.peek(Token![self]) - || lookahead.peek(Token![super]) - || lookahead.peek(Token![crate]) - || lookahead.peek(Token![extern]) - { - let ident = input.call(Ident::parse_any)?; - if input.peek(Token![::]) { - Ok(UseTree::Path(UsePath { - ident: ident, - colon2_token: input.parse()?, - tree: Box::new(input.parse()?), - })) - } else if input.peek(Token![as]) { - Ok(UseTree::Rename(UseRename { - ident: ident, - as_token: input.parse()?, - rename: { - if input.peek(Ident) { - input.parse()? - } else if input.peek(Token![_]) { - Ident::from(input.parse::<Token![_]>()?) - } else { - return Err(input.error("expected identifier or underscore")); - } - }, - })) - } else { - Ok(UseTree::Name(UseName { ident: ident })) - } - } else if lookahead.peek(Token![*]) { - Ok(UseTree::Glob(UseGlob { - star_token: input.parse()?, - })) - } else if lookahead.peek(token::Brace) { - let content; - Ok(UseTree::Group(UseGroup { - brace_token: braced!(content in input), - items: content.parse_terminated(UseTree::parse)?, - })) - } else { - Err(lookahead.error()) - } - } - } - - impl Parse for ItemStatic { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ItemStatic { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - static_token: input.parse()?, - mutability: input.parse()?, - ident: input.parse()?, - colon_token: input.parse()?, - ty: input.parse()?, - eq_token: input.parse()?, - expr: input.parse()?, - semi_token: input.parse()?, - }) - } - } - - impl Parse for ItemConst { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ItemConst { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - const_token: input.parse()?, - ident: { - let lookahead = input.lookahead1(); - if lookahead.peek(Ident) || lookahead.peek(Token![_]) { - input.call(Ident::parse_any)? - } else { - return Err(lookahead.error()); - } - }, - colon_token: input.parse()?, - ty: input.parse()?, - eq_token: input.parse()?, - expr: input.parse()?, - semi_token: input.parse()?, - }) - } - } - - impl Parse for ItemFn { - fn parse(input: ParseStream) -> Result<Self> { - let outer_attrs = input.call(Attribute::parse_outer)?; - let vis: Visibility = input.parse()?; - let constness: Option<Token![const]> = input.parse()?; - let asyncness: Option<Token![async]> = input.parse()?; - let unsafety: Option<Token![unsafe]> = input.parse()?; - let abi: Option<Abi> = input.parse()?; - let fn_token: Token![fn] = input.parse()?; - let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; - - let content; - let paren_token = parenthesized!(content in input); - let inputs = content.parse_terminated(FnArg::parse)?; - let variadic: Option<Token![...]> = match inputs.last() { - Some(punctuated::Pair::End(&FnArg::Captured(ArgCaptured { - ty: Type::Verbatim(TypeVerbatim { ref tts }), - .. - }))) => parse2(tts.clone()).ok(), - _ => None, - }; - - let output: ReturnType = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; - - Ok(ItemFn { - attrs: private::attrs(outer_attrs, inner_attrs), - vis: vis, - constness: constness, - asyncness: asyncness, - unsafety: unsafety, - abi: abi, - ident: ident, - decl: Box::new(FnDecl { - fn_token: fn_token, - paren_token: paren_token, - inputs: inputs, - output: output, - variadic: variadic, - generics: Generics { - where_clause: where_clause, - ..generics - }, - }), - block: Box::new(Block { - brace_token: brace_token, - stmts: stmts, - }), - }) - } - } - - impl Parse for FnArg { - fn parse(input: ParseStream) -> Result<Self> { - // TODO: optimize using advance_to - - if input.peek(Token![&]) { - let ahead = input.fork(); - if ahead.call(arg_self_ref).is_ok() && !ahead.peek(Token![:]) { - return input.call(arg_self_ref).map(FnArg::SelfRef); - } - } - - if input.peek(Token![mut]) || input.peek(Token![self]) { - let ahead = input.fork(); - if ahead.call(arg_self).is_ok() && !ahead.peek(Token![:]) { - return input.call(arg_self).map(FnArg::SelfValue); - } - } - - let ahead = input.fork(); - let err = match ahead.call(arg_captured) { - Ok(_) => return input.call(arg_captured).map(FnArg::Captured), - Err(err) => err, - }; - - let ahead = input.fork(); - if ahead.parse::<Type>().is_ok() { - return input.parse().map(FnArg::Ignored); - } - - Err(err) - } - } - - fn arg_self_ref(input: ParseStream) -> Result<ArgSelfRef> { - Ok(ArgSelfRef { - and_token: input.parse()?, - lifetime: input.parse()?, - mutability: input.parse()?, - self_token: input.parse()?, - }) - } - - fn arg_self(input: ParseStream) -> Result<ArgSelf> { - Ok(ArgSelf { - mutability: input.parse()?, - self_token: input.parse()?, - }) - } - - fn arg_captured(input: ParseStream) -> Result<ArgCaptured> { - Ok(ArgCaptured { - pat: input.parse()?, - colon_token: input.parse()?, - ty: match input.parse::<Token![...]>() { - Ok(dot3) => { - let args = vec![ - TokenTree::Punct(Punct::new('.', Spacing::Joint)), - TokenTree::Punct(Punct::new('.', Spacing::Joint)), - TokenTree::Punct(Punct::new('.', Spacing::Alone)), - ]; - let tokens = TokenStream::from_iter(args.into_iter().zip(&dot3.spans).map( - |(mut arg, span)| { - arg.set_span(*span); - arg - }, - )); - Type::Verbatim(TypeVerbatim { tts: tokens }) - } - Err(_) => input.parse()?, - }, - }) - } - - impl Parse for ItemMod { - fn parse(input: ParseStream) -> Result<Self> { - let outer_attrs = input.call(Attribute::parse_outer)?; - let vis: Visibility = input.parse()?; - let mod_token: Token![mod] = input.parse()?; - let ident: Ident = input.parse()?; - - let lookahead = input.lookahead1(); - if lookahead.peek(Token![;]) { - Ok(ItemMod { - attrs: outer_attrs, - vis: vis, - mod_token: mod_token, - ident: ident, - content: None, - semi: Some(input.parse()?), - }) - } else if lookahead.peek(token::Brace) { - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - - let mut items = Vec::new(); - while !content.is_empty() { - items.push(content.parse()?); - } - - Ok(ItemMod { - attrs: private::attrs(outer_attrs, inner_attrs), - vis: vis, - mod_token: mod_token, - ident: ident, - content: Some((brace_token, items)), - semi: None, - }) - } else { - Err(lookahead.error()) - } - } - } - - impl Parse for ItemForeignMod { - fn parse(input: ParseStream) -> Result<Self> { - let outer_attrs = input.call(Attribute::parse_outer)?; - let abi: Abi = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let mut items = Vec::new(); - while !content.is_empty() { - items.push(content.parse()?); - } - - Ok(ItemForeignMod { - attrs: private::attrs(outer_attrs, inner_attrs), - abi: abi, - brace_token: brace_token, - items: items, - }) - } - } - - impl Parse for ForeignItem { - fn parse(input: ParseStream) -> Result<Self> { - let mut attrs = input.call(Attribute::parse_outer)?; - let ahead = input.fork(); - let vis: Visibility = ahead.parse()?; - - let lookahead = ahead.lookahead1(); - let mut item = if lookahead.peek(Token![fn]) { - input.parse().map(ForeignItem::Fn) - } else if lookahead.peek(Token![static]) { - input.parse().map(ForeignItem::Static) - } else if lookahead.peek(Token![type]) { - input.parse().map(ForeignItem::Type) - } else if vis.is_inherited() - && (lookahead.peek(Ident) - || lookahead.peek(Token![self]) - || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![crate]) - || lookahead.peek(Token![::])) - { - input.parse().map(ForeignItem::Macro) - } else { - Err(lookahead.error()) - }?; - - { - let item_attrs = match item { - ForeignItem::Fn(ref mut item) => &mut item.attrs, - ForeignItem::Static(ref mut item) => &mut item.attrs, - ForeignItem::Type(ref mut item) => &mut item.attrs, - ForeignItem::Macro(ref mut item) => &mut item.attrs, - ForeignItem::Verbatim(_) => unreachable!(), - }; - attrs.extend(item_attrs.drain(..)); - *item_attrs = attrs; - } - - Ok(item) - } - } - - impl Parse for ForeignItemFn { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let vis: Visibility = input.parse()?; - let fn_token: Token![fn] = input.parse()?; - let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; - - let content; - let paren_token = parenthesized!(content in input); - let mut inputs = Punctuated::new(); - while !content.is_empty() && !content.peek(Token![...]) { - inputs.push_value(content.parse()?); - if content.is_empty() { - break; - } - inputs.push_punct(content.parse()?); - } - let variadic: Option<Token![...]> = if inputs.empty_or_trailing() { - content.parse()? - } else { - None - }; - - let output: ReturnType = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; - let semi_token: Token![;] = input.parse()?; - - Ok(ForeignItemFn { - attrs: attrs, - vis: vis, - ident: ident, - decl: Box::new(FnDecl { - fn_token: fn_token, - paren_token: paren_token, - inputs: inputs, - output: output, - variadic: variadic, - generics: Generics { - where_clause: where_clause, - ..generics - }, - }), - semi_token: semi_token, - }) - } - } - - impl Parse for ForeignItemStatic { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ForeignItemStatic { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - static_token: input.parse()?, - mutability: input.parse()?, - ident: input.parse()?, - colon_token: input.parse()?, - ty: input.parse()?, - semi_token: input.parse()?, - }) - } - } - - impl Parse for ForeignItemType { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ForeignItemType { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - type_token: input.parse()?, - ident: input.parse()?, - semi_token: input.parse()?, - }) - } - } - - impl Parse for ForeignItemMacro { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let mac: Macro = input.parse()?; - let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() { - None - } else { - Some(input.parse()?) - }; - Ok(ForeignItemMacro { - attrs: attrs, - mac: mac, - semi_token: semi_token, - }) - } - } - - impl Parse for ItemType { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ItemType { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - type_token: input.parse()?, - ident: input.parse()?, - generics: { - let mut generics: Generics = input.parse()?; - generics.where_clause = input.parse()?; - generics - }, - eq_token: input.parse()?, - ty: input.parse()?, - semi_token: input.parse()?, - }) - } - } - - impl Parse for ItemExistential { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ItemExistential { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - existential_token: input.parse()?, - type_token: input.parse()?, - ident: input.parse()?, - generics: { - let mut generics: Generics = input.parse()?; - generics.where_clause = input.parse()?; - generics - }, - colon_token: Some(input.parse()?), - bounds: { - let mut bounds = Punctuated::new(); - while !input.peek(Token![;]) { - if !bounds.is_empty() { - bounds.push_punct(input.parse()?); - } - bounds.push_value(input.parse()?); - } - bounds - }, - semi_token: input.parse()?, - }) - } - } - - impl Parse for ItemStruct { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let vis = input.parse::<Visibility>()?; - let struct_token = input.parse::<Token![struct]>()?; - let ident = input.parse::<Ident>()?; - let generics = input.parse::<Generics>()?; - let (where_clause, fields, semi_token) = derive::parsing::data_struct(input)?; - Ok(ItemStruct { - attrs: attrs, - vis: vis, - struct_token: struct_token, - ident: ident, - generics: Generics { - where_clause: where_clause, - ..generics - }, - fields: fields, - semi_token: semi_token, - }) - } - } - - impl Parse for ItemEnum { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let vis = input.parse::<Visibility>()?; - let enum_token = input.parse::<Token![enum]>()?; - let ident = input.parse::<Ident>()?; - let generics = input.parse::<Generics>()?; - let (where_clause, brace_token, variants) = derive::parsing::data_enum(input)?; - Ok(ItemEnum { - attrs: attrs, - vis: vis, - enum_token: enum_token, - ident: ident, - generics: Generics { - where_clause: where_clause, - ..generics - }, - brace_token: brace_token, - variants: variants, - }) - } - } - - impl Parse for ItemUnion { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let vis = input.parse::<Visibility>()?; - let union_token = input.parse::<Token![union]>()?; - let ident = input.parse::<Ident>()?; - let generics = input.parse::<Generics>()?; - let (where_clause, fields) = derive::parsing::data_union(input)?; - Ok(ItemUnion { - attrs: attrs, - vis: vis, - union_token: union_token, - ident: ident, - generics: Generics { - where_clause: where_clause, - ..generics - }, - fields: fields, - }) - } - } - - fn parse_trait_or_trait_alias(input: ParseStream) -> Result<Item> { - let (attrs, vis, trait_token, ident, generics) = parse_start_of_trait_alias(input)?; - let lookahead = input.lookahead1(); - if lookahead.peek(token::Brace) - || lookahead.peek(Token![:]) - || lookahead.peek(Token![where]) - { - let unsafety = None; - let auto_token = None; - parse_rest_of_trait( - input, - attrs, - vis, - unsafety, - auto_token, - trait_token, - ident, - generics, - ) - .map(Item::Trait) - } else if lookahead.peek(Token![=]) { - parse_rest_of_trait_alias(input, attrs, vis, trait_token, ident, generics) - .map(Item::TraitAlias) - } else { - Err(lookahead.error()) - } - } - - impl Parse for ItemTrait { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let vis: Visibility = input.parse()?; - let unsafety: Option<Token![unsafe]> = input.parse()?; - let auto_token: Option<Token![auto]> = input.parse()?; - let trait_token: Token![trait] = input.parse()?; - let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; - parse_rest_of_trait( - input, - attrs, - vis, - unsafety, - auto_token, - trait_token, - ident, - generics, - ) - } - } - - fn parse_rest_of_trait( - input: ParseStream, - attrs: Vec<Attribute>, - vis: Visibility, - unsafety: Option<Token![unsafe]>, - auto_token: Option<Token![auto]>, - trait_token: Token![trait], - ident: Ident, - mut generics: Generics, - ) -> Result<ItemTrait> { - let colon_token: Option<Token![:]> = input.parse()?; - - let mut supertraits = Punctuated::new(); - if colon_token.is_some() { - loop { - supertraits.push_value(input.parse()?); - if input.peek(Token![where]) || input.peek(token::Brace) { - break; - } - supertraits.push_punct(input.parse()?); - if input.peek(Token![where]) || input.peek(token::Brace) { - break; - } - } - } - - generics.where_clause = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let mut items = Vec::new(); - while !content.is_empty() { - items.push(content.parse()?); - } - - Ok(ItemTrait { - attrs: attrs, - vis: vis, - unsafety: unsafety, - auto_token: auto_token, - trait_token: trait_token, - ident: ident, - generics: generics, - colon_token: colon_token, - supertraits: supertraits, - brace_token: brace_token, - items: items, - }) - } - - impl Parse for ItemTraitAlias { - fn parse(input: ParseStream) -> Result<Self> { - let (attrs, vis, trait_token, ident, generics) = parse_start_of_trait_alias(input)?; - parse_rest_of_trait_alias(input, attrs, vis, trait_token, ident, generics) - } - } - - fn parse_start_of_trait_alias( - input: ParseStream, - ) -> Result<(Vec<Attribute>, Visibility, Token![trait], Ident, Generics)> { - let attrs = input.call(Attribute::parse_outer)?; - let vis: Visibility = input.parse()?; - let trait_token: Token![trait] = input.parse()?; - let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; - Ok((attrs, vis, trait_token, ident, generics)) - } - - fn parse_rest_of_trait_alias( - input: ParseStream, - attrs: Vec<Attribute>, - vis: Visibility, - trait_token: Token![trait], - ident: Ident, - mut generics: Generics, - ) -> Result<ItemTraitAlias> { - let eq_token: Token![=] = input.parse()?; - - let mut bounds = Punctuated::new(); - loop { - if input.peek(Token![where]) || input.peek(Token![;]) { - break; - } - bounds.push_value(input.parse()?); - if input.peek(Token![where]) || input.peek(Token![;]) { - break; - } - bounds.push_punct(input.parse()?); - } - - generics.where_clause = input.parse()?; - let semi_token: Token![;] = input.parse()?; - - Ok(ItemTraitAlias { - attrs: attrs, - vis: vis, - trait_token: trait_token, - ident: ident, - generics: generics, - eq_token: eq_token, - bounds: bounds, - semi_token: semi_token, - }) - } - - impl Parse for TraitItem { - fn parse(input: ParseStream) -> Result<Self> { - let mut attrs = input.call(Attribute::parse_outer)?; - let ahead = input.fork(); - - let lookahead = ahead.lookahead1(); - let mut item = if lookahead.peek(Token![const]) { - ahead.parse::<Token![const]>()?; - let lookahead = ahead.lookahead1(); - if lookahead.peek(Ident) { - input.parse().map(TraitItem::Const) - } else if lookahead.peek(Token![async]) - || lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(TraitItem::Method) - } else { - Err(lookahead.error()) - } - } else if lookahead.peek(Token![async]) - || lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(TraitItem::Method) - } else if lookahead.peek(Token![type]) { - input.parse().map(TraitItem::Type) - } else if lookahead.peek(Ident) - || lookahead.peek(Token![self]) - || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![crate]) - || lookahead.peek(Token![::]) - { - input.parse().map(TraitItem::Macro) - } else { - Err(lookahead.error()) - }?; - - { - let item_attrs = match item { - TraitItem::Const(ref mut item) => &mut item.attrs, - TraitItem::Method(ref mut item) => &mut item.attrs, - TraitItem::Type(ref mut item) => &mut item.attrs, - TraitItem::Macro(ref mut item) => &mut item.attrs, - TraitItem::Verbatim(_) => unreachable!(), - }; - attrs.extend(item_attrs.drain(..)); - *item_attrs = attrs; - } - - Ok(item) - } - } - - impl Parse for TraitItemConst { - fn parse(input: ParseStream) -> Result<Self> { - Ok(TraitItemConst { - attrs: input.call(Attribute::parse_outer)?, - const_token: input.parse()?, - ident: input.parse()?, - colon_token: input.parse()?, - ty: input.parse()?, - default: { - if input.peek(Token![=]) { - let eq_token: Token![=] = input.parse()?; - let default: Expr = input.parse()?; - Some((eq_token, default)) - } else { - None - } - }, - semi_token: input.parse()?, - }) - } - } - - impl Parse for TraitItemMethod { - fn parse(input: ParseStream) -> Result<Self> { - let outer_attrs = input.call(Attribute::parse_outer)?; - let constness: Option<Token![const]> = input.parse()?; - let asyncness: Option<Token![async]> = input.parse()?; - let unsafety: Option<Token![unsafe]> = input.parse()?; - let abi: Option<Abi> = input.parse()?; - let fn_token: Token![fn] = input.parse()?; - let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; - - let content; - let paren_token = parenthesized!(content in input); - let inputs = content.parse_terminated(FnArg::parse)?; - - let output: ReturnType = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; - - let lookahead = input.lookahead1(); - let (brace_token, inner_attrs, stmts, semi_token) = if lookahead.peek(token::Brace) { - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; - (Some(brace_token), inner_attrs, stmts, None) - } else if lookahead.peek(Token![;]) { - let semi_token: Token![;] = input.parse()?; - (None, Vec::new(), Vec::new(), Some(semi_token)) - } else { - return Err(lookahead.error()); - }; - - Ok(TraitItemMethod { - attrs: private::attrs(outer_attrs, inner_attrs), - sig: MethodSig { - constness: constness, - asyncness: asyncness, - unsafety: unsafety, - abi: abi, - ident: ident, - decl: FnDecl { - fn_token: fn_token, - paren_token: paren_token, - inputs: inputs, - output: output, - variadic: None, - generics: Generics { - where_clause: where_clause, - ..generics - }, - }, - }, - default: brace_token.map(|brace_token| Block { - brace_token: brace_token, - stmts: stmts, - }), - semi_token: semi_token, - }) - } - } - - impl Parse for TraitItemType { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let type_token: Token![type] = input.parse()?; - let ident: Ident = input.parse()?; - let mut generics: Generics = input.parse()?; - let colon_token: Option<Token![:]> = input.parse()?; - - let mut bounds = Punctuated::new(); - if colon_token.is_some() { - while !input.peek(Token![where]) && !input.peek(Token![=]) && !input.peek(Token![;]) - { - if !bounds.is_empty() { - bounds.push_punct(input.parse()?); - } - bounds.push_value(input.parse()?); - } - } - - generics.where_clause = input.parse()?; - let default = if input.peek(Token![=]) { - let eq_token: Token![=] = input.parse()?; - let default: Type = input.parse()?; - Some((eq_token, default)) - } else { - None - }; - let semi_token: Token![;] = input.parse()?; - - Ok(TraitItemType { - attrs: attrs, - type_token: type_token, - ident: ident, - generics: generics, - colon_token: colon_token, - bounds: bounds, - default: default, - semi_token: semi_token, - }) - } - } - - impl Parse for TraitItemMacro { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let mac: Macro = input.parse()?; - let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() { - None - } else { - Some(input.parse()?) - }; - Ok(TraitItemMacro { - attrs: attrs, - mac: mac, - semi_token: semi_token, - }) - } - } - - impl Parse for ItemImpl { - fn parse(input: ParseStream) -> Result<Self> { - let outer_attrs = input.call(Attribute::parse_outer)?; - let defaultness: Option<Token![default]> = input.parse()?; - let unsafety: Option<Token![unsafe]> = input.parse()?; - let impl_token: Token![impl] = input.parse()?; - - let has_generics = input.peek(Token![<]) - && (input.peek2(Token![>]) - || input.peek2(Token![#]) - || (input.peek2(Ident) || input.peek2(Lifetime)) - && (input.peek3(Token![:]) - || input.peek3(Token![,]) - || input.peek3(Token![>]))); - let generics: Generics = if has_generics { - input.parse()? - } else { - Generics::default() - }; - - let trait_ = { - // TODO: optimize using advance_to - let ahead = input.fork(); - if ahead.parse::<Option<Token![!]>>().is_ok() - && ahead.parse::<Path>().is_ok() - && ahead.parse::<Token![for]>().is_ok() - { - let polarity: Option<Token![!]> = input.parse()?; - let path: Path = input.parse()?; - let for_token: Token![for] = input.parse()?; - Some((polarity, path, for_token)) - } else { - None - } - }; - let self_ty: Type = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - - let mut items = Vec::new(); - while !content.is_empty() { - items.push(content.parse()?); - } - - Ok(ItemImpl { - attrs: private::attrs(outer_attrs, inner_attrs), - defaultness: defaultness, - unsafety: unsafety, - impl_token: impl_token, - generics: Generics { - where_clause: where_clause, - ..generics - }, - trait_: trait_, - self_ty: Box::new(self_ty), - brace_token: brace_token, - items: items, - }) - } - } - - impl Parse for ImplItem { - fn parse(input: ParseStream) -> Result<Self> { - let mut attrs = input.call(Attribute::parse_outer)?; - let ahead = input.fork(); - let vis: Visibility = ahead.parse()?; - - let mut lookahead = ahead.lookahead1(); - let defaultness = if lookahead.peek(Token![default]) && !ahead.peek2(Token![!]) { - let defaultness: Token![default] = ahead.parse()?; - lookahead = ahead.lookahead1(); - Some(defaultness) - } else { - None - }; - - let mut item = if lookahead.peek(Token![const]) { - ahead.parse::<Token![const]>()?; - let lookahead = ahead.lookahead1(); - if lookahead.peek(Ident) { - input.parse().map(ImplItem::Const) - } else if lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![async]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(ImplItem::Method) - } else { - Err(lookahead.error()) - } - } else if lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![async]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(ImplItem::Method) - } else if lookahead.peek(Token![type]) { - input.parse().map(ImplItem::Type) - } else if vis.is_inherited() - && defaultness.is_none() - && lookahead.peek(Token![existential]) - { - input.parse().map(ImplItem::Existential) - } else if vis.is_inherited() - && defaultness.is_none() - && (lookahead.peek(Ident) - || lookahead.peek(Token![self]) - || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![crate]) - || lookahead.peek(Token![::])) - { - input.parse().map(ImplItem::Macro) - } else { - Err(lookahead.error()) - }?; - - { - let item_attrs = match item { - ImplItem::Const(ref mut item) => &mut item.attrs, - ImplItem::Method(ref mut item) => &mut item.attrs, - ImplItem::Type(ref mut item) => &mut item.attrs, - ImplItem::Existential(ref mut item) => &mut item.attrs, - ImplItem::Macro(ref mut item) => &mut item.attrs, - ImplItem::Verbatim(_) => unreachable!(), - }; - attrs.extend(item_attrs.drain(..)); - *item_attrs = attrs; - } - - Ok(item) - } - } - - impl Parse for ImplItemConst { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ImplItemConst { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - defaultness: input.parse()?, - const_token: input.parse()?, - ident: input.parse()?, - colon_token: input.parse()?, - ty: input.parse()?, - eq_token: input.parse()?, - expr: input.parse()?, - semi_token: input.parse()?, - }) - } - } - - impl Parse for ImplItemMethod { - fn parse(input: ParseStream) -> Result<Self> { - let outer_attrs = input.call(Attribute::parse_outer)?; - let vis: Visibility = input.parse()?; - let defaultness: Option<Token![default]> = input.parse()?; - let constness: Option<Token![const]> = input.parse()?; - let asyncness: Option<Token![async]> = input.parse()?; - let unsafety: Option<Token![unsafe]> = input.parse()?; - let abi: Option<Abi> = input.parse()?; - let fn_token: Token![fn] = input.parse()?; - let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; - - let content; - let paren_token = parenthesized!(content in input); - let inputs = content.parse_terminated(FnArg::parse)?; - - let output: ReturnType = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; - - Ok(ImplItemMethod { - attrs: private::attrs(outer_attrs, inner_attrs), - vis: vis, - defaultness: defaultness, - sig: MethodSig { - constness: constness, - asyncness: asyncness, - unsafety: unsafety, - abi: abi, - ident: ident, - decl: FnDecl { - fn_token: fn_token, - paren_token: paren_token, - inputs: inputs, - output: output, - variadic: None, - generics: Generics { - where_clause: where_clause, - ..generics - }, - }, - }, - block: Block { - brace_token: brace_token, - stmts: stmts, - }, - }) - } - } - - impl Parse for ImplItemType { - fn parse(input: ParseStream) -> Result<Self> { - Ok(ImplItemType { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - defaultness: input.parse()?, - type_token: input.parse()?, - ident: input.parse()?, - generics: { - let mut generics: Generics = input.parse()?; - generics.where_clause = input.parse()?; - generics - }, - eq_token: input.parse()?, - ty: input.parse()?, - semi_token: input.parse()?, - }) - } - } - - impl Parse for ImplItemExistential { - fn parse(input: ParseStream) -> Result<Self> { - let ety: ItemExistential = input.parse()?; - Ok(ImplItemExistential { - attrs: ety.attrs, - existential_token: ety.existential_token, - type_token: ety.type_token, - ident: ety.ident, - generics: ety.generics, - colon_token: ety.colon_token, - bounds: ety.bounds, - semi_token: ety.semi_token, - }) - } - } - - impl Parse for ImplItemMacro { - fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; - let mac: Macro = input.parse()?; - let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() { - None - } else { - Some(input.parse()?) - }; - Ok(ImplItemMacro { - attrs: attrs, - mac: mac, - semi_token: semi_token, - }) - } - } - - impl Visibility { - fn is_inherited(&self) -> bool { - match *self { - Visibility::Inherited => true, - _ => false, - } - } - } - - impl MacroDelimiter { - fn is_brace(&self) -> bool { - match *self { - MacroDelimiter::Brace(_) => true, - MacroDelimiter::Paren(_) | MacroDelimiter::Bracket(_) => false, - } - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - - use proc_macro2::TokenStream; - use quote::{ToTokens, TokenStreamExt}; - - use attr::FilterAttrs; - use print::TokensOrDefault; - - impl ToTokens for ItemExternCrate { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.extern_token.to_tokens(tokens); - self.crate_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - if let Some((ref as_token, ref rename)) = self.rename { - as_token.to_tokens(tokens); - rename.to_tokens(tokens); - } - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ItemUse { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.use_token.to_tokens(tokens); - self.leading_colon.to_tokens(tokens); - self.tree.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ItemStatic { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.static_token.to_tokens(tokens); - self.mutability.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.expr.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ItemConst { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.const_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.expr.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ItemFn { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.constness.to_tokens(tokens); - self.asyncness.to_tokens(tokens); - self.unsafety.to_tokens(tokens); - self.abi.to_tokens(tokens); - NamedDecl(&self.decl, &self.ident).to_tokens(tokens); - self.block.brace_token.surround(tokens, |tokens| { - tokens.append_all(self.attrs.inner()); - tokens.append_all(&self.block.stmts); - }); - } - } - - impl ToTokens for ItemMod { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.mod_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - if let Some((ref brace, ref items)) = self.content { - brace.surround(tokens, |tokens| { - tokens.append_all(self.attrs.inner()); - tokens.append_all(items); - }); - } else { - TokensOrDefault(&self.semi).to_tokens(tokens); - } - } - } - - impl ToTokens for ItemForeignMod { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.abi.to_tokens(tokens); - self.brace_token.surround(tokens, |tokens| { - tokens.append_all(self.attrs.inner()); - tokens.append_all(&self.items); - }); - } - } - - impl ToTokens for ItemType { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.type_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ItemExistential { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.existential_token.to_tokens(tokens); - self.type_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - if !self.bounds.is_empty() { - TokensOrDefault(&self.colon_token).to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ItemEnum { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.enum_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - self.brace_token.surround(tokens, |tokens| { - self.variants.to_tokens(tokens); - }); - } - } - - impl ToTokens for ItemStruct { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.struct_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - match self.fields { - Fields::Named(ref fields) => { - self.generics.where_clause.to_tokens(tokens); - fields.to_tokens(tokens); - } - Fields::Unnamed(ref fields) => { - fields.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - TokensOrDefault(&self.semi_token).to_tokens(tokens); - } - Fields::Unit => { - self.generics.where_clause.to_tokens(tokens); - TokensOrDefault(&self.semi_token).to_tokens(tokens); - } - } - } - } - - impl ToTokens for ItemUnion { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.union_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - self.fields.to_tokens(tokens); - } - } - - impl ToTokens for ItemTrait { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.unsafety.to_tokens(tokens); - self.auto_token.to_tokens(tokens); - self.trait_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - if !self.supertraits.is_empty() { - TokensOrDefault(&self.colon_token).to_tokens(tokens); - self.supertraits.to_tokens(tokens); - } - self.generics.where_clause.to_tokens(tokens); - self.brace_token.surround(tokens, |tokens| { - tokens.append_all(&self.items); - }); - } - } - - impl ToTokens for ItemTraitAlias { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.trait_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.bounds.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ItemImpl { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.defaultness.to_tokens(tokens); - self.unsafety.to_tokens(tokens); - self.impl_token.to_tokens(tokens); - self.generics.to_tokens(tokens); - if let Some((ref polarity, ref path, ref for_token)) = self.trait_ { - polarity.to_tokens(tokens); - path.to_tokens(tokens); - for_token.to_tokens(tokens); - } - self.self_ty.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - self.brace_token.surround(tokens, |tokens| { - tokens.append_all(self.attrs.inner()); - tokens.append_all(&self.items); - }); - } - } - - impl ToTokens for ItemMacro { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.mac.path.to_tokens(tokens); - self.mac.bang_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - match self.mac.delimiter { - MacroDelimiter::Paren(ref paren) => { - paren.surround(tokens, |tokens| self.mac.tts.to_tokens(tokens)); - } - MacroDelimiter::Brace(ref brace) => { - brace.surround(tokens, |tokens| self.mac.tts.to_tokens(tokens)); - } - MacroDelimiter::Bracket(ref bracket) => { - bracket.surround(tokens, |tokens| self.mac.tts.to_tokens(tokens)); - } - } - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ItemMacro2 { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.macro_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - - // Hack: see comment in impl Parse for ItemMacro2. - if self.args.to_string() != "$ $" { - self.paren_token.surround(tokens, |tokens| { - self.args.to_tokens(tokens); - }); - } - - self.brace_token.surround(tokens, |tokens| { - self.body.to_tokens(tokens); - }); - } - } - - impl ToTokens for ItemVerbatim { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.tts.to_tokens(tokens); - } - } - - impl ToTokens for UsePath { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.ident.to_tokens(tokens); - self.colon2_token.to_tokens(tokens); - self.tree.to_tokens(tokens); - } - } - - impl ToTokens for UseName { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.ident.to_tokens(tokens); - } - } - - impl ToTokens for UseRename { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.ident.to_tokens(tokens); - self.as_token.to_tokens(tokens); - self.rename.to_tokens(tokens); - } - } - - impl ToTokens for UseGlob { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.star_token.to_tokens(tokens); - } - } - - impl ToTokens for UseGroup { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.brace_token.surround(tokens, |tokens| { - self.items.to_tokens(tokens); - }); - } - } - - impl ToTokens for TraitItemConst { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.const_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - if let Some((ref eq_token, ref default)) = self.default { - eq_token.to_tokens(tokens); - default.to_tokens(tokens); - } - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for TraitItemMethod { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.sig.to_tokens(tokens); - match self.default { - Some(ref block) => { - block.brace_token.surround(tokens, |tokens| { - tokens.append_all(self.attrs.inner()); - tokens.append_all(&block.stmts); - }); - } - None => { - TokensOrDefault(&self.semi_token).to_tokens(tokens); - } - } - } - } - - impl ToTokens for TraitItemType { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.type_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - if !self.bounds.is_empty() { - TokensOrDefault(&self.colon_token).to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - self.generics.where_clause.to_tokens(tokens); - if let Some((ref eq_token, ref default)) = self.default { - eq_token.to_tokens(tokens); - default.to_tokens(tokens); - } - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for TraitItemMacro { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.mac.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for TraitItemVerbatim { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.tts.to_tokens(tokens); - } - } - - impl ToTokens for ImplItemConst { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.defaultness.to_tokens(tokens); - self.const_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.expr.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ImplItemMethod { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.defaultness.to_tokens(tokens); - self.sig.to_tokens(tokens); - self.block.brace_token.surround(tokens, |tokens| { - tokens.append_all(self.attrs.inner()); - tokens.append_all(&self.block.stmts); - }); - } - } - - impl ToTokens for ImplItemType { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.defaultness.to_tokens(tokens); - self.type_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ImplItemExistential { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.existential_token.to_tokens(tokens); - self.type_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.generics.to_tokens(tokens); - self.generics.where_clause.to_tokens(tokens); - if !self.bounds.is_empty() { - TokensOrDefault(&self.colon_token).to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ImplItemMacro { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.mac.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ImplItemVerbatim { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.tts.to_tokens(tokens); - } - } - - impl ToTokens for ForeignItemFn { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - NamedDecl(&self.decl, &self.ident).to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ForeignItemStatic { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.static_token.to_tokens(tokens); - self.mutability.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ForeignItemType { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.vis.to_tokens(tokens); - self.type_token.to_tokens(tokens); - self.ident.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ForeignItemMacro { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.attrs.outer()); - self.mac.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - } - } - - impl ToTokens for ForeignItemVerbatim { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.tts.to_tokens(tokens); - } - } - - impl ToTokens for MethodSig { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.constness.to_tokens(tokens); - self.asyncness.to_tokens(tokens); - self.unsafety.to_tokens(tokens); - self.abi.to_tokens(tokens); - NamedDecl(&self.decl, &self.ident).to_tokens(tokens); - } - } - - struct NamedDecl<'a>(&'a FnDecl, &'a Ident); - - impl<'a> ToTokens for NamedDecl<'a> { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.0.fn_token.to_tokens(tokens); - self.1.to_tokens(tokens); - self.0.generics.to_tokens(tokens); - self.0.paren_token.surround(tokens, |tokens| { - self.0.inputs.to_tokens(tokens); - if self.0.variadic.is_some() && !self.0.inputs.empty_or_trailing() { - <Token![,]>::default().to_tokens(tokens); - } - self.0.variadic.to_tokens(tokens); - }); - self.0.output.to_tokens(tokens); - self.0.generics.where_clause.to_tokens(tokens); - } - } - - impl ToTokens for ArgSelfRef { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.and_token.to_tokens(tokens); - self.lifetime.to_tokens(tokens); - self.mutability.to_tokens(tokens); - self.self_token.to_tokens(tokens); - } - } - - impl ToTokens for ArgSelf { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.mutability.to_tokens(tokens); - self.self_token.to_tokens(tokens); - } - } - - impl ToTokens for ArgCaptured { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.pat.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - } - } -} diff --git a/0.15.42/src/lib.rs b/0.15.42/src/lib.rs deleted file mode 100644 index 35d07677..00000000 --- a/0.15.42/src/lib.rs +++ /dev/null @@ -1,740 +0,0 @@ -//! Syn is a parsing library for parsing a stream of Rust tokens into a syntax -//! tree of Rust source code. -//! -//! Currently this library is geared toward use in Rust procedural macros, but -//! contains some APIs that may be useful more generally. -//! -//! - **Data structures** — Syn provides a complete syntax tree that can -//! represent any valid Rust source code. The syntax tree is rooted at -//! [`syn::File`] which represents a full source file, but there are other -//! entry points that may be useful to procedural macros including -//! [`syn::Item`], [`syn::Expr`] and [`syn::Type`]. -//! -//! - **Custom derives** — Of particular interest to custom derives is -//! [`syn::DeriveInput`] which is any of the three legal input items to a -//! derive macro. An example below shows using this type in a library that can -//! derive implementations of a trait of your own. -//! -//! - **Parsing** — Parsing in Syn is built around [parser functions] with the -//! signature `fn(ParseStream) -> Result<T>`. Every syntax tree node defined -//! by Syn is individually parsable and may be used as a building block for -//! custom syntaxes, or you may dream up your own brand new syntax without -//! involving any of our syntax tree types. -//! -//! - **Location information** — Every token parsed by Syn is associated with a -//! `Span` that tracks line and column information back to the source of that -//! token. These spans allow a procedural macro to display detailed error -//! messages pointing to all the right places in the user's code. There is an -//! example of this below. -//! -//! - **Feature flags** — Functionality is aggressively feature gated so your -//! procedural macros enable only what they need, and do not pay in compile -//! time for all the rest. -//! -//! [`syn::File`]: struct.File.html -//! [`syn::Item`]: enum.Item.html -//! [`syn::Expr`]: enum.Expr.html -//! [`syn::Type`]: enum.Type.html -//! [`syn::DeriveInput`]: struct.DeriveInput.html -//! [parser functions]: parse/index.html -//! -//! *Version requirement: Syn supports any compiler version back to Rust's very -//! first support for procedural macros in Rust 1.15.0. Some features especially -//! around error reporting are only available in newer compilers or on the -//! nightly channel.* -//! -//! ## Example of a custom derive -//! -//! The canonical custom derive using Syn looks like this. We write an ordinary -//! Rust function tagged with a `proc_macro_derive` attribute and the name of -//! the trait we are deriving. Any time that derive appears in the user's code, -//! the Rust compiler passes their data structure as tokens into our macro. We -//! get to execute arbitrary Rust code to figure out what to do with those -//! tokens, then hand some tokens back to the compiler to compile into the -//! user's crate. -//! -//! [`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html -//! -//! ```toml -//! [dependencies] -//! syn = "0.15" -//! quote = "0.6" -//! -//! [lib] -//! proc-macro = true -//! ``` -//! -//! ```edition2018 -//! extern crate proc_macro; -//! -//! use proc_macro::TokenStream; -//! use quote::quote; -//! use syn::{parse_macro_input, DeriveInput}; -//! -//! # const IGNORE_TOKENS: &str = stringify! { -//! #[proc_macro_derive(MyMacro)] -//! # }; -//! pub fn my_macro(input: TokenStream) -> TokenStream { -//! // Parse the input tokens into a syntax tree -//! let input = parse_macro_input!(input as DeriveInput); -//! -//! // Build the output, possibly using quasi-quotation -//! let expanded = quote! { -//! // ... -//! }; -//! -//! // Hand the output tokens back to the compiler -//! TokenStream::from(expanded) -//! } -//! ``` -//! -//! The [`heapsize`] example directory shows a complete working Macros 1.1 -//! implementation of a custom derive. It works on any Rust compiler 1.15+. -//! The example derives a `HeapSize` trait which computes an estimate of the -//! amount of heap memory owned by a value. -//! -//! [`heapsize`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize -//! -//! ```edition2018 -//! pub trait HeapSize { -//! /// Total number of bytes of heap memory owned by `self`. -//! fn heap_size_of_children(&self) -> usize; -//! } -//! ``` -//! -//! The custom derive allows users to write `#[derive(HeapSize)]` on data -//! structures in their program. -//! -//! ```edition2018 -//! # const IGNORE_TOKENS: &str = stringify! { -//! #[derive(HeapSize)] -//! # }; -//! struct Demo<'a, T: ?Sized> { -//! a: Box<T>, -//! b: u8, -//! c: &'a str, -//! d: String, -//! } -//! ``` -//! -//! ## Spans and error reporting -//! -//! The token-based procedural macro API provides great control over where the -//! compiler's error messages are displayed in user code. Consider the error the -//! user sees if one of their field types does not implement `HeapSize`. -//! -//! ```edition2018 -//! # const IGNORE_TOKENS: &str = stringify! { -//! #[derive(HeapSize)] -//! # }; -//! struct Broken { -//! ok: String, -//! bad: std::thread::Thread, -//! } -//! ``` -//! -//! By tracking span information all the way through the expansion of a -//! procedural macro as shown in the `heapsize` example, token-based macros in -//! Syn are able to trigger errors that directly pinpoint the source of the -//! problem. -//! -//! ```text -//! error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied -//! --> src/main.rs:7:5 -//! | -//! 7 | bad: std::thread::Thread, -//! | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread` -//! ``` -//! -//! ## Parsing a custom syntax -//! -//! The [`lazy-static`] example directory shows the implementation of a -//! `functionlike!(...)` procedural macro in which the input tokens are parsed -//! using Syn's parsing API. -//! -//! [`lazy-static`]: https://github.com/dtolnay/syn/tree/master/examples/lazy-static -//! -//! The example reimplements the popular `lazy_static` crate from crates.io as a -//! procedural macro. -//! -//! ```edition2018 -//! # macro_rules! lazy_static { -//! # ($($tt:tt)*) => {} -//! # } -//! # -//! lazy_static! { -//! static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap(); -//! } -//! ``` -//! -//! The implementation shows how to trigger custom warnings and error messages -//! on the macro input. -//! -//! ```text -//! warning: come on, pick a more creative name -//! --> src/main.rs:10:16 -//! | -//! 10 | static ref FOO: String = "lazy_static".to_owned(); -//! | ^^^ -//! ``` -//! -//! ## Testing -//! -//! When testing macros, we often care not just that the macro can be used -//! successfully but also that when the macro is provided with invalid input it -//! produces maximally helpful error messages. Consider using the [`trybuild`] -//! crate to write tests for errors that are emitted by your macro or errors -//! detected by the Rust compiler in the expanded code following misuse of the -//! macro. Such tests help avoid regressions from later refactors that -//! mistakenly make an error no longer trigger or be less helpful than it used -//! to be. -//! -//! [`trybuild`]: https://github.com/dtolnay/trybuild -//! -//! ## Debugging -//! -//! When developing a procedural macro it can be helpful to look at what the -//! generated code looks like. Use `cargo rustc -- -Zunstable-options -//! --pretty=expanded` or the [`cargo expand`] subcommand. -//! -//! [`cargo expand`]: https://github.com/dtolnay/cargo-expand -//! -//! To show the expanded code for some crate that uses your procedural macro, -//! run `cargo expand` from that crate. To show the expanded code for one of -//! your own test cases, run `cargo expand --test the_test_case` where the last -//! argument is the name of the test file without the `.rs` extension. -//! -//! This write-up by Brandon W Maister discusses debugging in more detail: -//! [Debugging Rust's new Custom Derive system][debugging]. -//! -//! [debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/ -//! -//! ## Optional features -//! -//! Syn puts a lot of functionality behind optional features in order to -//! optimize compile time for the most common use cases. The following features -//! are available. -//! -//! - **`derive`** *(enabled by default)* — Data structures for representing the -//! possible input to a custom derive, including structs and enums and types. -//! - **`full`** — Data structures for representing the syntax tree of all valid -//! Rust source code, including items and expressions. -//! - **`parsing`** *(enabled by default)* — Ability to parse input tokens into -//! a syntax tree node of a chosen type. -//! - **`printing`** *(enabled by default)* — Ability to print a syntax tree -//! node as tokens of Rust source code. -//! - **`visit`** — Trait for traversing a syntax tree. -//! - **`visit-mut`** — Trait for traversing and mutating in place a syntax -//! tree. -//! - **`fold`** — Trait for transforming an owned syntax tree. -//! - **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree -//! types. -//! - **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree -//! types. -//! - **`proc-macro`** *(enabled by default)* — Runtime dependency on the -//! 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/0.15.42")] -#![allow(unknown_lints, bare_trait_objects, ellipsis_inclusive_range_patterns)] -#![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))] -#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))] -// Ignored clippy lints. -#![cfg_attr( - feature = "cargo-clippy", - allow( - block_in_if_condition_stmt, - cognitive_complexity, - deprecated_cfg_attr, - doc_markdown, - eval_order_dependence, - large_enum_variant, - needless_pass_by_value, - never_loop, - redundant_field_names, - redundant_static_lifetimes, - too_many_arguments, - ) -)] -// Ignored clippy_pedantic lints. -#![cfg_attr( - feature = "cargo-clippy", - allow( - cast_possible_truncation, - cast_possible_wrap, - empty_enum, - if_not_else, - items_after_statements, - module_name_repetitions, - shadow_unrelated, - similar_names, - single_match_else, - unseparated_literal_suffix, - use_self, - used_underscore_binding, - ) -)] - -#[cfg(all( - not(all(target_arch = "wasm32", target_os = "unknown")), - feature = "proc-macro" -))] -extern crate proc_macro; -extern crate proc_macro2; -extern crate unicode_xid; - -#[cfg(feature = "printing")] -extern crate quote; - -#[macro_use] -mod macros; - -// Not public API. -#[cfg(feature = "parsing")] -#[doc(hidden)] -#[macro_use] -pub mod group; - -#[macro_use] -pub mod token; - -mod ident; -pub use ident::Ident; - -#[cfg(any(feature = "full", feature = "derive"))] -mod attr; -#[cfg(any(feature = "full", feature = "derive"))] -pub use attr::{AttrStyle, Attribute, AttributeArgs, Meta, MetaList, MetaNameValue, NestedMeta}; - -#[cfg(any(feature = "full", feature = "derive"))] -mod data; -#[cfg(any(feature = "full", feature = "derive"))] -pub use data::{ - Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, VisRestricted, - Visibility, -}; - -#[cfg(any(feature = "full", feature = "derive"))] -mod expr; -#[cfg(any(feature = "full", feature = "derive"))] -pub use expr::{ - Expr, ExprArray, ExprAssign, ExprAssignOp, ExprAsync, ExprBinary, ExprBlock, ExprBox, - ExprBreak, ExprCall, ExprCast, ExprClosure, ExprContinue, ExprField, ExprForLoop, ExprGroup, - ExprIf, ExprInPlace, ExprIndex, ExprLet, ExprLit, ExprLoop, ExprMacro, ExprMatch, - ExprMethodCall, ExprParen, ExprPath, ExprRange, ExprReference, ExprRepeat, ExprReturn, - ExprStruct, ExprTry, ExprTryBlock, ExprTuple, ExprType, ExprUnary, ExprUnsafe, ExprVerbatim, - ExprWhile, ExprYield, Index, Member, -}; - -#[cfg(feature = "full")] -pub use expr::{ - Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local, MethodTurbofish, Pat, - PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange, PatRef, PatSlice, PatStruct, PatTuple, - PatTupleStruct, PatVerbatim, PatWild, RangeLimits, Stmt, -}; - -#[cfg(any(feature = "full", feature = "derive"))] -mod generics; -#[cfg(any(feature = "full", feature = "derive"))] -pub use generics::{ - BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq, - PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound, - WhereClause, WherePredicate, -}; -#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] -pub use generics::{ImplGenerics, Turbofish, TypeGenerics}; - -#[cfg(feature = "full")] -mod item; -#[cfg(feature = "full")] -pub use item::{ - ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl, ForeignItem, ForeignItemFn, ForeignItemMacro, - ForeignItemStatic, ForeignItemType, ForeignItemVerbatim, ImplItem, ImplItemConst, - ImplItemExistential, ImplItemMacro, ImplItemMethod, ImplItemType, ImplItemVerbatim, Item, - ItemConst, ItemEnum, ItemExistential, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, - ItemMacro, ItemMacro2, ItemMod, ItemStatic, ItemStruct, ItemTrait, ItemTraitAlias, ItemType, - ItemUnion, ItemUse, ItemVerbatim, MethodSig, TraitItem, TraitItemConst, TraitItemMacro, - TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseGroup, UseName, UsePath, - UseRename, UseTree, -}; - -#[cfg(feature = "full")] -mod file; -#[cfg(feature = "full")] -pub use file::File; - -mod lifetime; -pub use lifetime::Lifetime; - -#[cfg(any(feature = "full", feature = "derive"))] -mod lit; -#[cfg(any(feature = "full", feature = "derive"))] -pub use lit::{ - FloatSuffix, IntSuffix, Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr, - LitVerbatim, StrStyle, -}; - -#[cfg(any(feature = "full", feature = "derive"))] -mod mac; -#[cfg(any(feature = "full", feature = "derive"))] -pub use mac::{Macro, MacroDelimiter}; - -#[cfg(any(feature = "full", feature = "derive"))] -mod derive; -#[cfg(feature = "derive")] -pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput}; - -#[cfg(any(feature = "full", feature = "derive"))] -mod op; -#[cfg(any(feature = "full", feature = "derive"))] -pub use op::{BinOp, UnOp}; - -#[cfg(any(feature = "full", feature = "derive"))] -mod ty; -#[cfg(any(feature = "full", feature = "derive"))] -pub use ty::{ - Abi, BareFnArg, BareFnArgName, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup, - TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, TypeReference, - TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim, -}; - -#[cfg(any(feature = "full", feature = "derive"))] -mod path; -#[cfg(any(feature = "full", feature = "derive"))] -pub use path::{ - AngleBracketedGenericArguments, Binding, Constraint, GenericArgument, - ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf, -}; - -#[cfg(feature = "parsing")] -pub mod buffer; -#[cfg(feature = "parsing")] -pub mod ext; -pub mod punctuated; -#[cfg(all(any(feature = "full", feature = "derive"), feature = "extra-traits"))] -mod tt; - -// Not public API except the `parse_quote!` macro. -#[cfg(feature = "parsing")] -#[doc(hidden)] -pub mod parse_quote; - -// Not public API except the `parse_macro_input!` macro. -#[cfg(all( - not(all(target_arch = "wasm32", target_os = "unknown")), - feature = "parsing", - feature = "proc-macro" -))] -#[doc(hidden)] -pub mod parse_macro_input; - -#[cfg(all(feature = "parsing", feature = "printing"))] -pub mod spanned; - -mod gen { - /// Syntax tree traversal to walk a shared borrow of a syntax tree. - /// - /// Each method of the [`Visit`] trait is a hook that can be overridden to - /// customize the behavior when visiting the corresponding type of node. By - /// default, every method recursively visits the substructure of the input - /// by invoking the right visitor method of each of its fields. - /// - /// [`Visit`]: visit::Visit - /// - /// ```edition2018 - /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; - /// # - /// pub trait Visit<'ast> { - /// /* ... */ - /// - /// fn visit_expr_binary(&mut self, node: &'ast ExprBinary) { - /// for attr in &node.attrs { - /// self.visit_attribute(attr); - /// } - /// self.visit_expr(&*node.left); - /// self.visit_bin_op(&node.op); - /// self.visit_expr(&*node.right); - /// } - /// - /// /* ... */ - /// # fn visit_attribute(&mut self, node: &'ast Attribute); - /// # fn visit_expr(&mut self, node: &'ast Expr); - /// # fn visit_bin_op(&mut self, node: &'ast BinOp); - /// } - /// ``` - /// - /// *This module is available if Syn is built with the `"visit"` feature.* - #[cfg(feature = "visit")] - pub mod visit; - - /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in - /// place. - /// - /// Each method of the [`VisitMut`] trait is a hook that can be overridden - /// to customize the behavior when mutating the corresponding type of node. - /// By default, every method recursively visits the substructure of the - /// input by invoking the right visitor method of each of its fields. - /// - /// [`VisitMut`]: visit_mut::VisitMut - /// - /// ```edition2018 - /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; - /// # - /// pub trait VisitMut { - /// /* ... */ - /// - /// fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) { - /// for attr in &mut node.attrs { - /// self.visit_attribute_mut(attr); - /// } - /// self.visit_expr_mut(&mut *node.left); - /// self.visit_bin_op_mut(&mut node.op); - /// self.visit_expr_mut(&mut *node.right); - /// } - /// - /// /* ... */ - /// # fn visit_attribute_mut(&mut self, node: &mut Attribute); - /// # fn visit_expr_mut(&mut self, node: &mut Expr); - /// # fn visit_bin_op_mut(&mut self, node: &mut BinOp); - /// } - /// ``` - /// - /// *This module is available if Syn is built with the `"visit-mut"` - /// feature.* - #[cfg(feature = "visit-mut")] - pub mod visit_mut; - - /// Syntax tree traversal to transform the nodes of an owned syntax tree. - /// - /// Each method of the [`Fold`] trait is a hook that can be overridden to - /// customize the behavior when transforming the corresponding type of node. - /// By default, every method recursively visits the substructure of the - /// input by invoking the right visitor method of each of its fields. - /// - /// [`Fold`]: fold::Fold - /// - /// ```edition2018 - /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; - /// # - /// pub trait Fold { - /// /* ... */ - /// - /// fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary { - /// ExprBinary { - /// attrs: node.attrs - /// .into_iter() - /// .map(|attr| self.fold_attribute(attr)) - /// .collect(), - /// left: Box::new(self.fold_expr(*node.left)), - /// op: self.fold_bin_op(node.op), - /// right: Box::new(self.fold_expr(*node.right)), - /// } - /// } - /// - /// /* ... */ - /// # fn fold_attribute(&mut self, node: Attribute) -> Attribute; - /// # fn fold_expr(&mut self, node: Expr) -> Expr; - /// # fn fold_bin_op(&mut self, node: BinOp) -> BinOp; - /// } - /// ``` - /// - /// *This module is available if Syn is built with the `"fold"` feature.* - #[cfg(feature = "fold")] - pub mod fold; - - #[cfg(any(feature = "full", feature = "derive"))] - #[path = "../gen_helper.rs"] - mod helper; -} -pub use gen::*; - -// Not public API. -#[doc(hidden)] -pub mod export; - -mod custom_keyword; -mod custom_punctuation; -mod sealed; - -#[cfg(feature = "parsing")] -mod lookahead; - -#[cfg(feature = "parsing")] -pub mod parse; - -mod span; - -#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] -mod print; - -mod thread; - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(any(feature = "parsing", feature = "full", feature = "derive"))] -#[allow(non_camel_case_types)] -struct private; - -//////////////////////////////////////////////////////////////////////////////// - -mod error; -pub use error::{Error, Result}; - -/// Parse tokens of source code into the chosen syntax tree node. -/// -/// This is preferred over parsing a string because tokens are able to preserve -/// information about where in the user's code they were originally written (the -/// "span" of the token), possibly allowing the compiler to produce better error -/// messages. -/// -/// This function parses a `proc_macro::TokenStream` which is the type used for -/// interop with the compiler in a procedural macro. To parse a -/// `proc_macro2::TokenStream`, use [`syn::parse2`] instead. -/// -/// [`syn::parse2`]: parse2 -/// -/// *This function is available if Syn is built with both the `"parsing"` and -/// `"proc-macro"` features.* -/// -/// # Examples -/// -/// ```edition2018 -/// 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() -/// } -/// ``` -#[cfg(all( - not(all(target_arch = "wasm32", target_os = "unknown")), - feature = "parsing", - feature = "proc-macro" -))] -pub fn parse<T: parse::Parse>(tokens: proc_macro::TokenStream) -> Result<T> { - parse::Parser::parse(T::parse, tokens) -} - -/// Parse a proc-macro2 token stream into the chosen syntax tree node. -/// -/// 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 tts -/// of a [`Macro`] node. When in a procedural macro parsing the -/// `proc_macro::TokenStream` provided by the compiler, use [`syn::parse`] -/// instead. -/// -/// [`syn::parse`]: parse() -/// -/// *This function is available if Syn is built with the `"parsing"` feature.* -#[cfg(feature = "parsing")] -pub fn parse2<T: parse::Parse>(tokens: proc_macro2::TokenStream) -> Result<T> { - parse::Parser::parse2(T::parse, tokens) -} - -/// Parse a string of Rust code into the chosen syntax tree node. -/// -/// *This function is available if Syn is built with the `"parsing"` feature.* -/// -/// # Hygiene -/// -/// Every span in the resulting syntax tree will be set to resolve at the macro -/// call site. -/// -/// # Examples -/// -/// ```edition2018 -/// use syn::{Expr, Result}; -/// -/// fn run() -> Result<()> { -/// let code = "assert_eq!(u8::max_value(), 255)"; -/// let expr = syn::parse_str::<Expr>(code)?; -/// println!("{:#?}", expr); -/// Ok(()) -/// } -/// # -/// # fn main() { -/// # run().unwrap(); -/// # } -/// ``` -#[cfg(feature = "parsing")] -pub fn parse_str<T: parse::Parse>(s: &str) -> Result<T> { - parse::Parser::parse_str(T::parse, s) -} - -// FIXME the name parse_file makes it sound like you might pass in a path to a -// file, rather than the content. -/// Parse the content of a file of Rust code. -/// -/// This is different from `syn::parse_str::<File>(content)` in two ways: -/// -/// - It discards a leading byte order mark `\u{FEFF}` if the file has one. -/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`. -/// -/// If present, either of these would be an error using `from_str`. -/// -/// *This function is available if Syn is built with the `"parsing"` and -/// `"full"` features.* -/// -/// # Examples -/// -/// ```edition2018,no_run -/// use std::error::Error; -/// use std::fs::File; -/// use std::io::Read; -/// -/// fn run() -> Result<(), Box<Error>> { -/// let mut file = File::open("path/to/code.rs")?; -/// let mut content = String::new(); -/// file.read_to_string(&mut content)?; -/// -/// let ast = syn::parse_file(&content)?; -/// if let Some(shebang) = ast.shebang { -/// println!("{}", shebang); -/// } -/// println!("{} items", ast.items.len()); -/// -/// Ok(()) -/// } -/// # -/// # fn main() { -/// # run().unwrap(); -/// # } -/// ``` -#[cfg(all(feature = "parsing", feature = "full"))] -pub fn parse_file(mut content: &str) -> Result<File> { - // Strip the BOM if it is present - const BOM: &'static str = "\u{feff}"; - if content.starts_with(BOM) { - content = &content[BOM.len()..]; - } - - let mut shebang = None; - if content.starts_with("#!") && !content.starts_with("#![") { - if let Some(idx) = content.find('\n') { - shebang = Some(content[..idx].to_string()); - content = &content[idx..]; - } else { - shebang = Some(content.to_string()); - content = ""; - } - } - - let mut file: File = parse_str(content)?; - file.shebang = shebang; - Ok(file) -} diff --git a/0.15.42/src/lifetime.rs b/0.15.42/src/lifetime.rs deleted file mode 100644 index 461560c9..00000000 --- a/0.15.42/src/lifetime.rs +++ /dev/null @@ -1,155 +0,0 @@ -use std::cmp::Ordering; -use std::fmt::{self, Display}; -use std::hash::{Hash, Hasher}; - -use proc_macro2::{Ident, Span}; -use unicode_xid::UnicodeXID; - -#[cfg(feature = "parsing")] -use lookahead; - -/// A Rust lifetime: `'a`. -/// -/// Lifetime names must conform to the following rules: -/// -/// - Must start with an apostrophe. -/// - Must not consist of just an apostrophe: `'`. -/// - Character after the apostrophe must be `_` or a Unicode code point with -/// the XID_Start property. -/// - All following characters must be Unicode code points with the XID_Continue -/// property. -/// -/// *This type is available if Syn is built with the `"derive"` or `"full"` -/// feature.* -#[cfg_attr(feature = "extra-traits", derive(Debug))] -#[derive(Clone)] -pub struct Lifetime { - pub apostrophe: Span, - pub ident: Ident, -} - -impl Lifetime { - /// # Panics - /// - /// Panics if the lifetime does not conform to the bulleted rules above. - /// - /// # Invocation - /// - /// ```edition2018 - /// # use proc_macro2::Span; - /// # use syn::Lifetime; - /// # - /// # fn f() -> Lifetime { - /// Lifetime::new("'a", Span::call_site()) - /// # } - /// ``` - pub fn new(symbol: &str, span: Span) -> Self { - if !symbol.starts_with('\'') { - panic!( - "lifetime name must start with apostrophe as in \"'a\", got {:?}", - symbol - ); - } - - if symbol == "'" { - panic!("lifetime name must not be empty"); - } - - fn xid_ok(symbol: &str) -> bool { - let mut chars = symbol.chars(); - let first = chars.next().unwrap(); - if !(UnicodeXID::is_xid_start(first) || first == '_') { - return false; - } - for ch in chars { - if !UnicodeXID::is_xid_continue(ch) { - return false; - } - } - true - } - - if !xid_ok(&symbol[1..]) { - panic!("{:?} is not a valid lifetime name", symbol); - } - - Lifetime { - apostrophe: span, - ident: Ident::new(&symbol[1..], span), - } - } -} - -impl Display for Lifetime { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - "'".fmt(formatter)?; - self.ident.fmt(formatter) - } -} - -impl PartialEq for Lifetime { - fn eq(&self, other: &Lifetime) -> bool { - self.ident.eq(&other.ident) - } -} - -impl Eq for Lifetime {} - -impl PartialOrd for Lifetime { - fn partial_cmp(&self, other: &Lifetime) -> Option<Ordering> { - Some(self.cmp(other)) - } -} - -impl Ord for Lifetime { - fn cmp(&self, other: &Lifetime) -> Ordering { - self.ident.cmp(&other.ident) - } -} - -impl Hash for Lifetime { - fn hash<H: Hasher>(&self, h: &mut H) { - self.ident.hash(h) - } -} - -#[cfg(feature = "parsing")] -#[doc(hidden)] -#[allow(non_snake_case)] -pub fn Lifetime(marker: lookahead::TokenMarker) -> Lifetime { - match marker {} -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use parse::{Parse, ParseStream, Result}; - - impl Parse for Lifetime { - fn parse(input: ParseStream) -> Result<Self> { - input.step(|cursor| { - cursor - .lifetime() - .ok_or_else(|| cursor.error("expected lifetime")) - }) - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - - use proc_macro2::{Punct, Spacing, TokenStream}; - use quote::{ToTokens, TokenStreamExt}; - - impl ToTokens for Lifetime { - fn to_tokens(&self, tokens: &mut TokenStream) { - let mut apostrophe = Punct::new('\'', Spacing::Joint); - apostrophe.set_span(self.apostrophe); - tokens.append(apostrophe); - self.ident.to_tokens(tokens); - } - } -} diff --git a/0.15.42/src/lit.rs b/0.15.42/src/lit.rs deleted file mode 100644 index aa6a6548..00000000 --- a/0.15.42/src/lit.rs +++ /dev/null @@ -1,1106 +0,0 @@ -use proc_macro2::{Literal, Span}; -use std::str; - -#[cfg(feature = "printing")] -use proc_macro2::Ident; - -#[cfg(feature = "parsing")] -use proc_macro2::TokenStream; - -use proc_macro2::TokenTree; - -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; - -#[cfg(feature = "parsing")] -use lookahead; -#[cfg(feature = "parsing")] -use parse::{Parse, Parser, Result}; - -ast_enum_of_structs! { - /// A Rust literal such as a string or integer or boolean. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Lit { - /// A UTF-8 string literal: `"foo"`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Str(LitStr #manual_extra_traits { - token: Literal, - }), - - /// A byte string literal: `b"foo"`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub ByteStr(LitByteStr #manual_extra_traits { - token: Literal, - }), - - /// A byte literal: `b'f'`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Byte(LitByte #manual_extra_traits { - token: Literal, - }), - - /// A character literal: `'a'`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Char(LitChar #manual_extra_traits { - token: Literal, - }), - - /// An integer literal: `1` or `1u16`. - /// - /// Holds up to 64 bits of data. Use `LitVerbatim` for any larger - /// integer literal. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Int(LitInt #manual_extra_traits { - token: Literal, - }), - - /// A floating point literal: `1f64` or `1.0e10f64`. - /// - /// Must be finite. May not be infinte or NaN. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Float(LitFloat #manual_extra_traits { - token: Literal, - }), - - /// A boolean literal: `true` or `false`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Bool(LitBool #manual_extra_traits { - pub value: bool, - pub span: Span, - }), - - /// A raw token literal not interpreted by Syn, possibly because it - /// represents an integer larger than 64 bits. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Verbatim(LitVerbatim #manual_extra_traits { - pub token: Literal, - }), - } -} - -impl LitStr { - pub fn new(value: &str, span: Span) -> Self { - let mut lit = Literal::string(value); - lit.set_span(span); - LitStr { token: lit } - } - - pub fn value(&self) -> String { - value::parse_lit_str(&self.token.to_string()) - } - - /// Parse a syntax tree node from the content of this string literal. - /// - /// All spans in the syntax tree will point to the span of this `LitStr`. - /// - /// # Example - /// - /// ```edition2018 - /// use proc_macro2::Span; - /// use syn::{Attribute, Error, Ident, Lit, Meta, MetaNameValue, Path, Result}; - /// - /// // Parses the path from an attribute that looks like: - /// // - /// // #[path = "a::b::c"] - /// // - /// // or returns `None` if the input is some other attribute. - /// fn get_path(attr: &Attribute) -> Result<Option<Path>> { - /// if !attr.path.is_ident("path") { - /// return Ok(None); - /// } - /// - /// match attr.parse_meta()? { - /// Meta::NameValue(MetaNameValue { lit: Lit::Str(lit_str), .. }) => { - /// lit_str.parse().map(Some) - /// } - /// _ => { - /// let message = "expected #[path = \"...\"]"; - /// Err(Error::new_spanned(attr, message)) - /// } - /// } - /// } - /// ``` - #[cfg(feature = "parsing")] - pub fn parse<T: Parse>(&self) -> Result<T> { - self.parse_with(T::parse) - } - - /// Invoke parser on the content of this string literal. - /// - /// All spans in the syntax tree will point to the span of this `LitStr`. - /// - /// # Example - /// - /// ```edition2018 - /// # use proc_macro2::Span; - /// # use syn::{LitStr, Result}; - /// # - /// # fn main() -> Result<()> { - /// # let lit_str = LitStr::new("a::b::c", Span::call_site()); - /// # - /// # const IGNORE: &str = stringify! { - /// let lit_str: LitStr = /* ... */; - /// # }; - /// - /// // Parse a string literal like "a::b::c" into a Path, not allowing - /// // generic arguments on any of the path segments. - /// let basic_path = lit_str.parse_with(syn::Path::parse_mod_style)?; - /// # - /// # Ok(()) - /// # } - /// ``` - #[cfg(feature = "parsing")] - pub fn parse_with<F: Parser>(&self, parser: F) -> Result<F::Output> { - use proc_macro2::Group; - - // Token stream with every span replaced by the given one. - fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream { - stream - .into_iter() - .map(|token| respan_token_tree(token, span)) - .collect() - } - - // Token tree with every span replaced by the given one. - fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree { - match token { - TokenTree::Group(ref mut g) => { - let stream = respan_token_stream(g.stream().clone(), span); - *g = Group::new(g.delimiter(), stream); - g.set_span(span); - } - ref mut other => other.set_span(span), - } - token - } - - // Parse string literal into a token stream with every span equal to the - // original literal's span. - let mut tokens = ::parse_str(&self.value())?; - tokens = respan_token_stream(tokens, self.span()); - - parser.parse2(tokens) - } - - pub fn span(&self) -> Span { - self.token.span() - } - - pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) - } -} - -impl LitByteStr { - pub fn new(value: &[u8], span: Span) -> Self { - let mut token = Literal::byte_string(value); - token.set_span(span); - LitByteStr { token: token } - } - - pub fn value(&self) -> Vec<u8> { - value::parse_lit_byte_str(&self.token.to_string()) - } - - pub fn span(&self) -> Span { - self.token.span() - } - - pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) - } -} - -impl LitByte { - pub fn new(value: u8, span: Span) -> Self { - let mut token = Literal::u8_suffixed(value); - token.set_span(span); - LitByte { token: token } - } - - pub fn value(&self) -> u8 { - value::parse_lit_byte(&self.token.to_string()) - } - - pub fn span(&self) -> Span { - self.token.span() - } - - pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) - } -} - -impl LitChar { - pub fn new(value: char, span: Span) -> Self { - let mut token = Literal::character(value); - token.set_span(span); - LitChar { token: token } - } - - pub fn value(&self) -> char { - value::parse_lit_char(&self.token.to_string()) - } - - pub fn span(&self) -> Span { - self.token.span() - } - - pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) - } -} - -impl LitInt { - pub fn new(value: u64, suffix: IntSuffix, span: Span) -> Self { - let mut token = match suffix { - IntSuffix::Isize => Literal::isize_suffixed(value as isize), - IntSuffix::I8 => Literal::i8_suffixed(value as i8), - IntSuffix::I16 => Literal::i16_suffixed(value as i16), - IntSuffix::I32 => Literal::i32_suffixed(value as i32), - IntSuffix::I64 => Literal::i64_suffixed(value as i64), - IntSuffix::I128 => value::to_literal(&format!("{}i128", value)), - IntSuffix::Usize => Literal::usize_suffixed(value as usize), - IntSuffix::U8 => Literal::u8_suffixed(value as u8), - IntSuffix::U16 => Literal::u16_suffixed(value as u16), - IntSuffix::U32 => Literal::u32_suffixed(value as u32), - IntSuffix::U64 => Literal::u64_suffixed(value), - IntSuffix::U128 => value::to_literal(&format!("{}u128", value)), - IntSuffix::None => Literal::u64_unsuffixed(value), - }; - token.set_span(span); - LitInt { token: token } - } - - pub fn value(&self) -> u64 { - value::parse_lit_int(&self.token.to_string()).unwrap() - } - - pub fn suffix(&self) -> IntSuffix { - let value = self.token.to_string(); - for (s, suffix) in vec![ - ("i8", IntSuffix::I8), - ("i16", IntSuffix::I16), - ("i32", IntSuffix::I32), - ("i64", IntSuffix::I64), - ("i128", IntSuffix::I128), - ("isize", IntSuffix::Isize), - ("u8", IntSuffix::U8), - ("u16", IntSuffix::U16), - ("u32", IntSuffix::U32), - ("u64", IntSuffix::U64), - ("u128", IntSuffix::U128), - ("usize", IntSuffix::Usize), - ] { - if value.ends_with(s) { - return suffix; - } - } - IntSuffix::None - } - - pub fn span(&self) -> Span { - self.token.span() - } - - pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) - } -} - -impl LitFloat { - pub fn new(value: f64, suffix: FloatSuffix, span: Span) -> Self { - let mut token = match suffix { - FloatSuffix::F32 => Literal::f32_suffixed(value as f32), - FloatSuffix::F64 => Literal::f64_suffixed(value), - FloatSuffix::None => Literal::f64_unsuffixed(value), - }; - token.set_span(span); - LitFloat { token: token } - } - - pub fn value(&self) -> f64 { - value::parse_lit_float(&self.token.to_string()) - } - - pub fn suffix(&self) -> FloatSuffix { - let value = self.token.to_string(); - for (s, suffix) in vec![("f32", FloatSuffix::F32), ("f64", FloatSuffix::F64)] { - if value.ends_with(s) { - return suffix; - } - } - FloatSuffix::None - } - - pub fn span(&self) -> Span { - self.token.span() - } - - pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) - } -} - -macro_rules! lit_extra_traits { - ($ty:ident, $field:ident) => { - #[cfg(feature = "extra-traits")] - impl Eq for $ty {} - - #[cfg(feature = "extra-traits")] - impl PartialEq for $ty { - fn eq(&self, other: &Self) -> bool { - self.$field.to_string() == other.$field.to_string() - } - } - - #[cfg(feature = "extra-traits")] - impl Hash for $ty { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - self.$field.to_string().hash(state); - } - } - - #[cfg(feature = "parsing")] - #[doc(hidden)] - #[allow(non_snake_case)] - pub fn $ty(marker: lookahead::TokenMarker) -> $ty { - match marker {} - } - }; -} - -impl LitVerbatim { - pub fn span(&self) -> Span { - self.token.span() - } - - pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) - } -} - -lit_extra_traits!(LitStr, token); -lit_extra_traits!(LitByteStr, token); -lit_extra_traits!(LitByte, token); -lit_extra_traits!(LitChar, token); -lit_extra_traits!(LitInt, token); -lit_extra_traits!(LitFloat, token); -lit_extra_traits!(LitBool, value); -lit_extra_traits!(LitVerbatim, token); - -ast_enum! { - /// The style of a string literal, either plain quoted or a raw string like - /// `r##"data"##`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum StrStyle #no_visit { - /// An ordinary string like `"data"`. - Cooked, - /// A raw string like `r##"data"##`. - /// - /// The unsigned integer is the number of `#` symbols used. - Raw(usize), - } -} - -ast_enum! { - /// The suffix on an integer literal if any, like the `u8` in `127u8`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum IntSuffix #no_visit { - I8, - I16, - I32, - I64, - I128, - Isize, - U8, - U16, - U32, - U64, - U128, - Usize, - None, - } -} - -ast_enum! { - /// The suffix on a floating point literal if any, like the `f32` in - /// `1.0f32`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum FloatSuffix #no_visit { - F32, - F64, - None, - } -} - -#[cfg(feature = "parsing")] -#[doc(hidden)] -#[allow(non_snake_case)] -pub fn Lit(marker: lookahead::TokenMarker) -> Lit { - match marker {} -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - use parse::{Parse, ParseStream, Result}; - - impl Parse for Lit { - fn parse(input: ParseStream) -> Result<Self> { - input.step(|cursor| { - if let Some((lit, rest)) = cursor.literal() { - return Ok((Lit::new(lit), rest)); - } - while let Some((ident, rest)) = cursor.ident() { - let value = if ident == "true" { - true - } else if ident == "false" { - false - } else { - break; - }; - let lit_bool = LitBool { - value: value, - span: ident.span(), - }; - return Ok((Lit::Bool(lit_bool), rest)); - } - Err(cursor.error("expected literal")) - }) - } - } - - impl Parse for LitStr { - fn parse(input: ParseStream) -> Result<Self> { - let head = input.fork(); - match input.parse()? { - Lit::Str(lit) => Ok(lit), - _ => Err(head.error("expected string literal")), - } - } - } - - impl Parse for LitByteStr { - fn parse(input: ParseStream) -> Result<Self> { - let head = input.fork(); - match input.parse()? { - Lit::ByteStr(lit) => Ok(lit), - _ => Err(head.error("expected byte string literal")), - } - } - } - - impl Parse for LitByte { - fn parse(input: ParseStream) -> Result<Self> { - let head = input.fork(); - match input.parse()? { - Lit::Byte(lit) => Ok(lit), - _ => Err(head.error("expected byte literal")), - } - } - } - - impl Parse for LitChar { - fn parse(input: ParseStream) -> Result<Self> { - let head = input.fork(); - match input.parse()? { - Lit::Char(lit) => Ok(lit), - _ => Err(head.error("expected character literal")), - } - } - } - - impl Parse for LitInt { - fn parse(input: ParseStream) -> Result<Self> { - let head = input.fork(); - match input.parse()? { - Lit::Int(lit) => Ok(lit), - _ => Err(head.error("expected integer literal")), - } - } - } - - impl Parse for LitFloat { - fn parse(input: ParseStream) -> Result<Self> { - let head = input.fork(); - match input.parse()? { - Lit::Float(lit) => Ok(lit), - _ => Err(head.error("expected floating point literal")), - } - } - } - - impl Parse for LitBool { - fn parse(input: ParseStream) -> Result<Self> { - let head = input.fork(); - match input.parse()? { - Lit::Bool(lit) => Ok(lit), - _ => Err(head.error("expected boolean literal")), - } - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - use proc_macro2::TokenStream; - use quote::{ToTokens, TokenStreamExt}; - - impl ToTokens for LitStr { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); - } - } - - impl ToTokens for LitByteStr { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); - } - } - - impl ToTokens for LitByte { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); - } - } - - impl ToTokens for LitChar { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); - } - } - - impl ToTokens for LitInt { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); - } - } - - impl ToTokens for LitFloat { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); - } - } - - impl ToTokens for LitBool { - fn to_tokens(&self, tokens: &mut TokenStream) { - let s = if self.value { "true" } else { "false" }; - tokens.append(Ident::new(s, self.span)); - } - } - - impl ToTokens for LitVerbatim { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); - } - } -} - -mod value { - use super::*; - use proc_macro2::TokenStream; - use std::char; - use std::ops::{Index, RangeFrom}; - - impl Lit { - /// Interpret a Syn literal from a proc-macro2 literal. - /// - /// Not all proc-macro2 literals are valid Syn literals. In particular, - /// doc comments are considered by proc-macro2 to be literals but in Syn - /// they are [`Attribute`]. - /// - /// [`Attribute`]: crate::Attribute - /// - /// # Panics - /// - /// Panics if the input is a doc comment literal. - pub fn new(token: Literal) -> Self { - let value = token.to_string(); - - match value::byte(&value, 0) { - b'"' | b'r' => return Lit::Str(LitStr { token: token }), - b'b' => match value::byte(&value, 1) { - b'"' | b'r' => return Lit::ByteStr(LitByteStr { token: token }), - b'\'' => return Lit::Byte(LitByte { token: token }), - _ => {} - }, - b'\'' => return Lit::Char(LitChar { token: token }), - b'0'...b'9' => { - if number_is_int(&value) { - return Lit::Int(LitInt { token: token }); - } else if number_is_float(&value) { - return Lit::Float(LitFloat { token: token }); - } else { - // number overflow - return Lit::Verbatim(LitVerbatim { token: token }); - } - } - _ => { - if value == "true" || value == "false" { - return Lit::Bool(LitBool { - value: value == "true", - span: token.span(), - }); - } - } - } - - panic!("Unrecognized literal: {}", value); - } - } - - fn number_is_int(value: &str) -> bool { - if number_is_float(value) { - false - } else { - value::parse_lit_int(value).is_some() - } - } - - fn number_is_float(value: &str) -> bool { - if value.contains('.') { - true - } else if value.starts_with("0x") || value.ends_with("size") { - false - } else { - value.contains('e') || value.contains('E') - } - } - - /// Get the byte at offset idx, or a default of `b'\0'` if we're looking - /// past the end of the input buffer. - pub fn byte<S: AsRef<[u8]> + ?Sized>(s: &S, idx: usize) -> u8 { - let s = s.as_ref(); - if idx < s.len() { - s[idx] - } else { - 0 - } - } - - fn next_chr(s: &str) -> char { - s.chars().next().unwrap_or('\0') - } - - pub fn parse_lit_str(s: &str) -> String { - match byte(s, 0) { - b'"' => parse_lit_str_cooked(s), - b'r' => parse_lit_str_raw(s), - _ => unreachable!(), - } - } - - // Clippy false positive - // https://github.com/rust-lang-nursery/rust-clippy/issues/2329 - #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))] - fn parse_lit_str_cooked(mut s: &str) -> String { - assert_eq!(byte(s, 0), b'"'); - s = &s[1..]; - - let mut out = String::new(); - 'outer: loop { - let ch = match byte(s, 0) { - b'"' => break, - b'\\' => { - let b = byte(s, 1); - s = &s[2..]; - match b { - b'x' => { - let (byte, rest) = backslash_x(s); - s = rest; - assert!(byte <= 0x80, "Invalid \\x byte in string literal"); - char::from_u32(u32::from(byte)).unwrap() - } - b'u' => { - let (chr, rest) = backslash_u(s); - s = rest; - chr - } - b'n' => '\n', - b'r' => '\r', - b't' => '\t', - b'\\' => '\\', - b'0' => '\0', - b'\'' => '\'', - b'"' => '"', - b'\r' | b'\n' => loop { - let ch = next_chr(s); - if ch.is_whitespace() { - s = &s[ch.len_utf8()..]; - } else { - continue 'outer; - } - }, - b => panic!("unexpected byte {:?} after \\ character in byte literal", b), - } - } - b'\r' => { - assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string"); - s = &s[2..]; - '\n' - } - _ => { - let ch = next_chr(s); - s = &s[ch.len_utf8()..]; - ch - } - }; - out.push(ch); - } - - assert_eq!(s, "\""); - out - } - - fn parse_lit_str_raw(mut s: &str) -> String { - assert_eq!(byte(s, 0), b'r'); - s = &s[1..]; - - let mut pounds = 0; - while byte(s, pounds) == b'#' { - pounds += 1; - } - assert_eq!(byte(s, pounds), b'"'); - assert_eq!(byte(s, s.len() - pounds - 1), b'"'); - for end in s[s.len() - pounds..].bytes() { - assert_eq!(end, b'#'); - } - - s[pounds + 1..s.len() - pounds - 1].to_owned() - } - - pub fn parse_lit_byte_str(s: &str) -> Vec<u8> { - assert_eq!(byte(s, 0), b'b'); - match byte(s, 1) { - b'"' => parse_lit_byte_str_cooked(s), - b'r' => parse_lit_byte_str_raw(s), - _ => unreachable!(), - } - } - - // Clippy false positive - // https://github.com/rust-lang-nursery/rust-clippy/issues/2329 - #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))] - fn parse_lit_byte_str_cooked(mut s: &str) -> Vec<u8> { - assert_eq!(byte(s, 0), b'b'); - assert_eq!(byte(s, 1), b'"'); - s = &s[2..]; - - // We're going to want to have slices which don't respect codepoint boundaries. - let mut s = s.as_bytes(); - - let mut out = Vec::new(); - 'outer: loop { - let byte = match byte(s, 0) { - b'"' => break, - b'\\' => { - let b = byte(s, 1); - s = &s[2..]; - match b { - b'x' => { - let (b, rest) = backslash_x(s); - s = rest; - b - } - b'n' => b'\n', - b'r' => b'\r', - b't' => b'\t', - b'\\' => b'\\', - b'0' => b'\0', - b'\'' => b'\'', - b'"' => b'"', - b'\r' | b'\n' => loop { - let byte = byte(s, 0); - let ch = char::from_u32(u32::from(byte)).unwrap(); - if ch.is_whitespace() { - s = &s[1..]; - } else { - continue 'outer; - } - }, - b => panic!("unexpected byte {:?} after \\ character in byte literal", b), - } - } - b'\r' => { - assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string"); - s = &s[2..]; - b'\n' - } - b => { - s = &s[1..]; - b - } - }; - out.push(byte); - } - - assert_eq!(s, b"\""); - out - } - - fn parse_lit_byte_str_raw(s: &str) -> Vec<u8> { - assert_eq!(byte(s, 0), b'b'); - parse_lit_str_raw(&s[1..]).into_bytes() - } - - pub fn parse_lit_byte(s: &str) -> u8 { - assert_eq!(byte(s, 0), b'b'); - assert_eq!(byte(s, 1), b'\''); - - // We're going to want to have slices which don't respect codepoint boundaries. - let mut s = s[2..].as_bytes(); - - let b = match byte(s, 0) { - b'\\' => { - let b = byte(s, 1); - s = &s[2..]; - match b { - b'x' => { - let (b, rest) = backslash_x(s); - s = rest; - b - } - b'n' => b'\n', - b'r' => b'\r', - b't' => b'\t', - b'\\' => b'\\', - b'0' => b'\0', - b'\'' => b'\'', - b'"' => b'"', - b => panic!("unexpected byte {:?} after \\ character in byte literal", b), - } - } - b => { - s = &s[1..]; - b - } - }; - - assert_eq!(byte(s, 0), b'\''); - b - } - - pub fn parse_lit_char(mut s: &str) -> char { - assert_eq!(byte(s, 0), b'\''); - s = &s[1..]; - - let ch = match byte(s, 0) { - b'\\' => { - let b = byte(s, 1); - s = &s[2..]; - match b { - b'x' => { - let (byte, rest) = backslash_x(s); - s = rest; - assert!(byte <= 0x80, "Invalid \\x byte in string literal"); - char::from_u32(u32::from(byte)).unwrap() - } - b'u' => { - let (chr, rest) = backslash_u(s); - s = rest; - chr - } - b'n' => '\n', - b'r' => '\r', - b't' => '\t', - b'\\' => '\\', - b'0' => '\0', - b'\'' => '\'', - b'"' => '"', - b => panic!("unexpected byte {:?} after \\ character in byte literal", b), - } - } - _ => { - let ch = next_chr(s); - s = &s[ch.len_utf8()..]; - ch - } - }; - assert_eq!(s, "\'", "Expected end of char literal"); - ch - } - - fn backslash_x<S>(s: &S) -> (u8, &S) - where - S: Index<RangeFrom<usize>, Output = S> + AsRef<[u8]> + ?Sized, - { - let mut ch = 0; - let b0 = byte(s, 0); - let b1 = byte(s, 1); - ch += 0x10 - * match b0 { - b'0'...b'9' => b0 - b'0', - b'a'...b'f' => 10 + (b0 - b'a'), - b'A'...b'F' => 10 + (b0 - b'A'), - _ => panic!("unexpected non-hex character after \\x"), - }; - ch += match b1 { - b'0'...b'9' => b1 - b'0', - b'a'...b'f' => 10 + (b1 - b'a'), - b'A'...b'F' => 10 + (b1 - b'A'), - _ => panic!("unexpected non-hex character after \\x"), - }; - (ch, &s[2..]) - } - - fn backslash_u(mut s: &str) -> (char, &str) { - if byte(s, 0) != b'{' { - panic!("expected {{ after \\u"); - } - s = &s[1..]; - - let mut ch = 0; - for _ in 0..6 { - let b = byte(s, 0); - match b { - b'0'...b'9' => { - ch *= 0x10; - ch += u32::from(b - b'0'); - s = &s[1..]; - } - b'a'...b'f' => { - ch *= 0x10; - ch += u32::from(10 + b - b'a'); - s = &s[1..]; - } - b'A'...b'F' => { - ch *= 0x10; - ch += u32::from(10 + b - b'A'); - s = &s[1..]; - } - b'}' => break, - _ => panic!("unexpected non-hex character after \\u"), - } - } - assert!(byte(s, 0) == b'}'); - s = &s[1..]; - - if let Some(ch) = char::from_u32(ch) { - (ch, s) - } else { - panic!("character code {:x} is not a valid unicode character", ch); - } - } - - pub fn parse_lit_int(mut s: &str) -> Option<u64> { - let base = match (byte(s, 0), byte(s, 1)) { - (b'0', b'x') => { - s = &s[2..]; - 16 - } - (b'0', b'o') => { - s = &s[2..]; - 8 - } - (b'0', b'b') => { - s = &s[2..]; - 2 - } - (b'0'...b'9', _) => 10, - _ => unreachable!(), - }; - - let mut value = 0u64; - loop { - let b = byte(s, 0); - let digit = match b { - b'0'...b'9' => u64::from(b - b'0'), - b'a'...b'f' if base > 10 => 10 + u64::from(b - b'a'), - b'A'...b'F' if base > 10 => 10 + u64::from(b - b'A'), - b'_' => { - s = &s[1..]; - continue; - } - // NOTE: Looking at a floating point literal, we don't want to - // consider these integers. - b'.' if base == 10 => return None, - b'e' | b'E' if base == 10 => return None, - _ => break, - }; - - if digit >= base { - panic!("Unexpected digit {:x} out of base range", digit); - } - - value = match value.checked_mul(base) { - Some(value) => value, - None => return None, - }; - value = match value.checked_add(digit) { - Some(value) => value, - None => return None, - }; - s = &s[1..]; - } - - Some(value) - } - - pub fn parse_lit_float(input: &str) -> f64 { - // Rust's floating point literals are very similar to the ones parsed by - // the standard library, except that rust's literals can contain - // ignorable underscores. Let's remove those underscores. - let mut bytes = input.to_owned().into_bytes(); - let mut write = 0; - for read in 0..bytes.len() { - if bytes[read] == b'_' { - continue; // Don't increase write - } - if write != read { - let x = bytes[read]; - bytes[write] = x; - } - write += 1; - } - bytes.truncate(write); - let input = String::from_utf8(bytes).unwrap(); - let end = input.find('f').unwrap_or_else(|| input.len()); - input[..end].parse().unwrap() - } - - pub fn to_literal(s: &str) -> Literal { - let stream = s.parse::<TokenStream>().unwrap(); - match stream.into_iter().next().unwrap() { - TokenTree::Literal(l) => l, - _ => unreachable!(), - } - } -} diff --git a/0.15.42/src/lookahead.rs b/0.15.42/src/lookahead.rs deleted file mode 100644 index d1b0cff3..00000000 --- a/0.15.42/src/lookahead.rs +++ /dev/null @@ -1,168 +0,0 @@ -use std::cell::RefCell; - -use proc_macro2::{Delimiter, Span}; - -use buffer::Cursor; -use error::{self, Error}; -use sealed::lookahead::Sealed; -use span::IntoSpans; -use token::Token; - -/// Support for checking the next token in a stream to decide how to parse. -/// -/// An important advantage over [`ParseStream::peek`] is that here we -/// automatically construct an appropriate error message based on the token -/// alternatives that get peeked. If you are producing your own error message, -/// go ahead and use `ParseStream::peek` instead. -/// -/// Use [`ParseStream::lookahead1`] to construct this object. -/// -/// [`ParseStream::peek`]: crate::parse::ParseBuffer::peek -/// [`ParseStream::lookahead1`]: crate::parse::ParseBuffer::lookahead1 -/// -/// # Example -/// -/// ```edition2018 -/// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam}; -/// use syn::parse::{Parse, ParseStream}; -/// -/// // A generic parameter, a single one of the comma-separated elements inside -/// // angle brackets in: -/// // -/// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... } -/// // -/// // On invalid input, lookahead gives us a reasonable error message. -/// // -/// // error: expected one of: identifier, lifetime, `const` -/// // | -/// // 5 | fn f<!Sized>() {} -/// // | ^ -/// enum GenericParam { -/// Type(TypeParam), -/// Lifetime(LifetimeDef), -/// Const(ConstParam), -/// } -/// -/// impl Parse for GenericParam { -/// fn parse(input: ParseStream) -> Result<Self> { -/// let lookahead = input.lookahead1(); -/// if lookahead.peek(Ident) { -/// input.parse().map(GenericParam::Type) -/// } else if lookahead.peek(Lifetime) { -/// input.parse().map(GenericParam::Lifetime) -/// } else if lookahead.peek(Token![const]) { -/// input.parse().map(GenericParam::Const) -/// } else { -/// Err(lookahead.error()) -/// } -/// } -/// } -/// ``` -pub struct Lookahead1<'a> { - scope: Span, - cursor: Cursor<'a>, - comparisons: RefCell<Vec<&'static str>>, -} - -pub fn new(scope: Span, cursor: Cursor) -> Lookahead1 { - Lookahead1 { - scope: scope, - cursor: cursor, - comparisons: RefCell::new(Vec::new()), - } -} - -fn peek_impl( - lookahead: &Lookahead1, - peek: fn(Cursor) -> bool, - display: fn() -> &'static str, -) -> bool { - if peek(lookahead.cursor) { - return true; - } - lookahead.comparisons.borrow_mut().push(display()); - false -} - -impl<'a> Lookahead1<'a> { - /// Looks at the next token in the parse stream to determine whether it - /// matches the requested type of token. - /// - /// # Syntax - /// - /// Note that this method does not use turbofish syntax. Pass the peek type - /// inside of parentheses. - /// - /// - `input.peek(Token![struct])` - /// - `input.peek(Token![==])` - /// - `input.peek(Ident)` *(does not accept keywords)* - /// - `input.peek(Ident::peek_any)` - /// - `input.peek(Lifetime)` - /// - `input.peek(token::Brace)` - pub fn peek<T: Peek>(&self, token: T) -> bool { - let _ = token; - peek_impl(self, T::Token::peek, T::Token::display) - } - - /// Triggers an error at the current position of the parse stream. - /// - /// 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.borrow(); - match comparisons.len() { - 0 => { - if self.cursor.eof() { - Error::new(self.scope, "unexpected end of input") - } else { - Error::new(self.cursor.span(), "unexpected token") - } - } - 1 => { - let message = format!("expected {}", comparisons[0]); - error::new_at(self.scope, self.cursor, message) - } - 2 => { - let message = format!("expected {} or {}", comparisons[0], comparisons[1]); - error::new_at(self.scope, self.cursor, message) - } - _ => { - let join = comparisons.join(", "); - let message = format!("expected one of: {}", join); - error::new_at(self.scope, self.cursor, message) - } - } - } -} - -/// Types that can be parsed by looking at just one token. -/// -/// Use [`ParseStream::peek`] to peek one of these types in a parse stream -/// without consuming it from the stream. -/// -/// This trait is sealed and cannot be implemented for types outside of Syn. -/// -/// [`ParseStream::peek`]: crate::parse::ParseBuffer::peek -pub trait Peek: Sealed { - // Not public API. - #[doc(hidden)] - type Token: Token; -} - -impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Peek for F { - type Token = T; -} - -pub enum TokenMarker {} - -impl<S> IntoSpans<S> for TokenMarker { - fn into_spans(self) -> S { - match self {} - } -} - -pub fn is_delimiter(cursor: Cursor, delimiter: Delimiter) -> bool { - cursor.group(delimiter).is_some() -} - -impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Sealed for F {} diff --git a/0.15.42/src/mac.rs b/0.15.42/src/mac.rs deleted file mode 100644 index c4b16ba8..00000000 --- a/0.15.42/src/mac.rs +++ /dev/null @@ -1,239 +0,0 @@ -use super::*; -use proc_macro2::TokenStream; -#[cfg(feature = "parsing")] -use proc_macro2::{Delimiter, Span, TokenTree}; -use token::{Brace, Bracket, Paren}; - -#[cfg(feature = "parsing")] -use parse::{Parse, ParseStream, Parser, Result}; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; -#[cfg(feature = "extra-traits")] -use tt::TokenStreamHelper; - -ast_struct! { - /// A macro invocation: `println!("{}", mac)`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct Macro #manual_extra_traits { - pub path: Path, - pub bang_token: Token![!], - pub delimiter: MacroDelimiter, - pub tts: TokenStream, - } -} - -ast_enum! { - /// A grouping token that surrounds a macro body: `m!(...)` or `m!{...}` or `m![...]`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum MacroDelimiter { - Paren(Paren), - Brace(Brace), - Bracket(Bracket), - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for Macro {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Macro { - fn eq(&self, other: &Self) -> bool { - self.path == other.path - && self.bang_token == other.bang_token - && self.delimiter == other.delimiter - && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Macro { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - self.path.hash(state); - self.bang_token.hash(state); - self.delimiter.hash(state); - TokenStreamHelper(&self.tts).hash(state); - } -} - -#[cfg(feature = "parsing")] -fn delimiter_span(delimiter: &MacroDelimiter) -> Span { - match *delimiter { - MacroDelimiter::Paren(ref token) => token.span, - MacroDelimiter::Brace(ref token) => token.span, - MacroDelimiter::Bracket(ref token) => token.span, - } -} - -impl Macro { - /// Parse the tokens within the macro invocation's delimiters into a syntax - /// tree. - /// - /// This is equivalent to `syn::parse2::<T>(mac.tts)` except that it - /// produces a more useful span when `tts` is empty. - /// - /// # Example - /// - /// ```edition2018 - /// use syn::{parse_quote, Expr, ExprLit, Ident, Lit, LitStr, Macro, Token}; - /// use syn::ext::IdentExt; - /// use syn::parse::{Error, Parse, ParseStream, Result}; - /// use syn::punctuated::Punctuated; - /// - /// // The arguments expected by libcore's format_args macro, and as a - /// // result most other formatting and printing macros like println. - /// // - /// // println!("{} is {number:.prec$}", "x", prec=5, number=0.01) - /// struct FormatArgs { - /// format_string: Expr, - /// positional_args: Vec<Expr>, - /// named_args: Vec<(Ident, Expr)>, - /// } - /// - /// impl Parse for FormatArgs { - /// fn parse(input: ParseStream) -> Result<Self> { - /// let format_string: Expr; - /// let mut positional_args = Vec::new(); - /// let mut named_args = Vec::new(); - /// - /// format_string = input.parse()?; - /// while !input.is_empty() { - /// input.parse::<Token![,]>()?; - /// if input.is_empty() { - /// break; - /// } - /// if input.peek(Ident::peek_any) && input.peek2(Token![=]) { - /// while !input.is_empty() { - /// let name: Ident = input.call(Ident::parse_any)?; - /// input.parse::<Token![=]>()?; - /// let value: Expr = input.parse()?; - /// named_args.push((name, value)); - /// if input.is_empty() { - /// break; - /// } - /// input.parse::<Token![,]>()?; - /// } - /// break; - /// } - /// positional_args.push(input.parse()?); - /// } - /// - /// Ok(FormatArgs { - /// format_string, - /// positional_args, - /// named_args, - /// }) - /// } - /// } - /// - /// // Extract the first argument, the format string literal, from an - /// // invocation of a formatting or printing macro. - /// fn get_format_string(m: &Macro) -> Result<LitStr> { - /// let args: FormatArgs = m.parse_body()?; - /// match args.format_string { - /// Expr::Lit(ExprLit { lit: Lit::Str(lit), .. }) => Ok(lit), - /// other => { - /// // First argument was not a string literal expression. - /// // Maybe something like: println!(concat!(...), ...) - /// Err(Error::new_spanned(other, "format string must be a string literal")) - /// } - /// } - /// } - /// - /// fn main() { - /// let invocation = parse_quote! { - /// println!("{:?}", Instant::now()) - /// }; - /// let lit = get_format_string(&invocation).unwrap(); - /// assert_eq!(lit.value(), "{:?}"); - /// } - /// ``` - #[cfg(feature = "parsing")] - pub fn parse_body<T: Parse>(&self) -> Result<T> { - self.parse_body_with(T::parse) - } - - /// Parse the tokens within the macro invocation's delimiters using the - /// given parser. - #[cfg(feature = "parsing")] - pub fn parse_body_with<F: Parser>(&self, parser: F) -> Result<F::Output> { - // TODO: see if we can get a group.span_close() span in here as the - // scope, rather than the span of the whole group. - let scope = delimiter_span(&self.delimiter); - private::parse_scoped(parser, scope, self.tts.clone()) - } -} - -#[cfg(feature = "parsing")] -pub fn parse_delimiter(input: ParseStream) -> Result<(MacroDelimiter, TokenStream)> { - input.step(|cursor| { - if let Some((TokenTree::Group(g), rest)) = cursor.token_tree() { - let span = g.span(); - let delimiter = match g.delimiter() { - Delimiter::Parenthesis => MacroDelimiter::Paren(Paren(span)), - Delimiter::Brace => MacroDelimiter::Brace(Brace(span)), - Delimiter::Bracket => MacroDelimiter::Bracket(Bracket(span)), - Delimiter::None => { - return Err(cursor.error("expected delimiter")); - } - }; - Ok(((delimiter, g.stream().clone()), rest)) - } else { - Err(cursor.error("expected delimiter")) - } - }) -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use parse::{Parse, ParseStream, Result}; - - impl Parse for Macro { - fn parse(input: ParseStream) -> Result<Self> { - let tts; - Ok(Macro { - path: input.call(Path::parse_mod_style)?, - bang_token: input.parse()?, - delimiter: { - let (delimiter, content) = parse_delimiter(input)?; - tts = content; - delimiter - }, - tts: tts, - }) - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - use proc_macro2::TokenStream; - use quote::ToTokens; - - impl ToTokens for Macro { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.path.to_tokens(tokens); - self.bang_token.to_tokens(tokens); - match self.delimiter { - MacroDelimiter::Paren(ref paren) => { - paren.surround(tokens, |tokens| self.tts.to_tokens(tokens)); - } - MacroDelimiter::Brace(ref brace) => { - brace.surround(tokens, |tokens| self.tts.to_tokens(tokens)); - } - MacroDelimiter::Bracket(ref bracket) => { - bracket.surround(tokens, |tokens| self.tts.to_tokens(tokens)); - } - } - } - } -} diff --git a/0.15.42/src/macros.rs b/0.15.42/src/macros.rs deleted file mode 100644 index bb59063a..00000000 --- a/0.15.42/src/macros.rs +++ /dev/null @@ -1,165 +0,0 @@ -#[cfg(any(feature = "full", feature = "derive"))] -macro_rules! ast_struct { - ( - $(#[$attr:meta])* - pub struct $name:ident #full $($rest:tt)* - ) => { - #[cfg(feature = "full")] - $(#[$attr])* - #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] - pub struct $name $($rest)* - - #[cfg(not(feature = "full"))] - $(#[$attr])* - #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] - pub struct $name { - _noconstruct: (), - } - }; - - ( - $(#[$attr:meta])* - pub struct $name:ident #manual_extra_traits $($rest:tt)* - ) => { - $(#[$attr])* - #[cfg_attr(feature = "extra-traits", derive(Debug))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] - pub struct $name $($rest)* - }; - - ( - $(#[$attr:meta])* - pub struct $name:ident $($rest:tt)* - ) => { - $(#[$attr])* - #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] - pub struct $name $($rest)* - }; -} - -#[cfg(any(feature = "full", feature = "derive"))] -macro_rules! ast_enum { - ( - $(#[$enum_attr:meta])* - pub enum $name:ident $(# $tags:ident)* { $($variants:tt)* } - ) => ( - $(#[$enum_attr])* - #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] - pub enum $name { - $($variants)* - } - ) -} - -#[cfg(any(feature = "full", feature = "derive"))] -macro_rules! ast_enum_of_structs { - ( - $(#[$enum_attr:meta])* - pub enum $name:ident { - $( - $(#[$variant_attr:meta])* - pub $variant:ident $( ($member:ident $($rest:tt)*) )*, - )* - } - - $($remaining:tt)* - ) => ( - ast_enum! { - $(#[$enum_attr])* - pub enum $name { - $( - $(#[$variant_attr])* - $variant $( ($member) )*, - )* - } - } - - $( - maybe_ast_struct! { - $(#[$variant_attr])* - $( - pub struct $member $($rest)* - )* - } - - $( - impl From<$member> for $name { - fn from(e: $member) -> $name { - $name::$variant(e) - } - } - )* - )* - - #[cfg(feature = "printing")] - generate_to_tokens! { - $($remaining)* - () - tokens - $name { $($variant $( [$($rest)*] )*,)* } - } - ) -} - -#[cfg(all(feature = "printing", any(feature = "full", feature = "derive")))] -macro_rules! generate_to_tokens { - (do_not_generate_to_tokens $($foo:tt)*) => (); - - (($($arms:tt)*) $tokens:ident $name:ident { $variant:ident, $($next:tt)*}) => { - generate_to_tokens!( - ($($arms)* $name::$variant => {}) - $tokens $name { $($next)* } - ); - }; - - (($($arms:tt)*) $tokens:ident $name:ident { $variant:ident [$($rest:tt)*], $($next:tt)*}) => { - generate_to_tokens!( - ($($arms)* $name::$variant(ref _e) => to_tokens_call!(_e, $tokens, $($rest)*),) - $tokens $name { $($next)* } - ); - }; - - (($($arms:tt)*) $tokens:ident $name:ident {}) => { - impl ::quote::ToTokens for $name { - fn to_tokens(&self, $tokens: &mut ::proc_macro2::TokenStream) { - match *self { - $($arms)* - } - } - } - }; -} - -#[cfg(all(feature = "printing", feature = "full"))] -macro_rules! to_tokens_call { - ($e:ident, $tokens:ident, $($rest:tt)*) => { - $e.to_tokens($tokens) - }; -} - -#[cfg(all(feature = "printing", feature = "derive", not(feature = "full")))] -macro_rules! to_tokens_call { - // If the variant is marked as #full, don't auto-generate to-tokens for it. - ($e:ident, $tokens:ident, #full $($rest:tt)*) => { - unreachable!() - }; - ($e:ident, $tokens:ident, $($rest:tt)*) => { - $e.to_tokens($tokens) - }; -} - -#[cfg(any(feature = "full", feature = "derive"))] -macro_rules! maybe_ast_struct { - ( - $(#[$attr:meta])* - $( - pub struct $name:ident - )* - ) => (); - - ($($rest:tt)*) => (ast_struct! { $($rest)* }); -} diff --git a/0.15.42/src/op.rs b/0.15.42/src/op.rs deleted file mode 100644 index 96d8c995..00000000 --- a/0.15.42/src/op.rs +++ /dev/null @@ -1,231 +0,0 @@ -ast_enum! { - /// A binary operator: `+`, `+=`, `&`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - #[cfg_attr(feature = "clone-impls", derive(Copy))] - pub enum BinOp { - /// The `+` operator (addition) - Add(Token![+]), - /// The `-` operator (subtraction) - Sub(Token![-]), - /// The `*` operator (multiplication) - Mul(Token![*]), - /// The `/` operator (division) - Div(Token![/]), - /// The `%` operator (modulus) - Rem(Token![%]), - /// The `&&` operator (logical and) - And(Token![&&]), - /// The `||` operator (logical or) - Or(Token![||]), - /// The `^` operator (bitwise xor) - BitXor(Token![^]), - /// The `&` operator (bitwise and) - BitAnd(Token![&]), - /// The `|` operator (bitwise or) - BitOr(Token![|]), - /// The `<<` operator (shift left) - Shl(Token![<<]), - /// The `>>` operator (shift right) - Shr(Token![>>]), - /// The `==` operator (equality) - Eq(Token![==]), - /// The `<` operator (less than) - Lt(Token![<]), - /// The `<=` operator (less than or equal to) - Le(Token![<=]), - /// The `!=` operator (not equal to) - Ne(Token![!=]), - /// The `>=` operator (greater than or equal to) - Ge(Token![>=]), - /// The `>` operator (greater than) - Gt(Token![>]), - /// The `+=` operator - AddEq(Token![+=]), - /// The `-=` operator - SubEq(Token![-=]), - /// The `*=` operator - MulEq(Token![*=]), - /// The `/=` operator - DivEq(Token![/=]), - /// The `%=` operator - RemEq(Token![%=]), - /// The `^=` operator - BitXorEq(Token![^=]), - /// The `&=` operator - BitAndEq(Token![&=]), - /// The `|=` operator - BitOrEq(Token![|=]), - /// The `<<=` operator - ShlEq(Token![<<=]), - /// The `>>=` operator - ShrEq(Token![>>=]), - } -} - -ast_enum! { - /// A unary operator: `*`, `!`, `-`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - #[cfg_attr(feature = "clone-impls", derive(Copy))] - pub enum UnOp { - /// The `*` operator for dereferencing - Deref(Token![*]), - /// The `!` operator for logical inversion - Not(Token![!]), - /// The `-` operator for negation - Neg(Token![-]), - } -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use parse::{Parse, ParseStream, Result}; - - fn parse_binop(input: ParseStream) -> Result<BinOp> { - if input.peek(Token![&&]) { - input.parse().map(BinOp::And) - } else if input.peek(Token![||]) { - input.parse().map(BinOp::Or) - } else if input.peek(Token![<<]) { - input.parse().map(BinOp::Shl) - } else if input.peek(Token![>>]) { - input.parse().map(BinOp::Shr) - } else if input.peek(Token![==]) { - input.parse().map(BinOp::Eq) - } else if input.peek(Token![<=]) { - input.parse().map(BinOp::Le) - } else if input.peek(Token![!=]) { - input.parse().map(BinOp::Ne) - } else if input.peek(Token![>=]) { - input.parse().map(BinOp::Ge) - } else if input.peek(Token![+]) { - input.parse().map(BinOp::Add) - } else if input.peek(Token![-]) { - input.parse().map(BinOp::Sub) - } else if input.peek(Token![*]) { - input.parse().map(BinOp::Mul) - } else if input.peek(Token![/]) { - input.parse().map(BinOp::Div) - } else if input.peek(Token![%]) { - input.parse().map(BinOp::Rem) - } else if input.peek(Token![^]) { - input.parse().map(BinOp::BitXor) - } else if input.peek(Token![&]) { - input.parse().map(BinOp::BitAnd) - } else if input.peek(Token![|]) { - input.parse().map(BinOp::BitOr) - } else if input.peek(Token![<]) { - input.parse().map(BinOp::Lt) - } else if input.peek(Token![>]) { - input.parse().map(BinOp::Gt) - } else { - Err(input.error("expected binary operator")) - } - } - - impl Parse for BinOp { - #[cfg(not(feature = "full"))] - fn parse(input: ParseStream) -> Result<Self> { - parse_binop(input) - } - - #[cfg(feature = "full")] - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Token![+=]) { - input.parse().map(BinOp::AddEq) - } else if input.peek(Token![-=]) { - input.parse().map(BinOp::SubEq) - } else if input.peek(Token![*=]) { - input.parse().map(BinOp::MulEq) - } else if input.peek(Token![/=]) { - input.parse().map(BinOp::DivEq) - } else if input.peek(Token![%=]) { - input.parse().map(BinOp::RemEq) - } else if input.peek(Token![^=]) { - input.parse().map(BinOp::BitXorEq) - } else if input.peek(Token![&=]) { - input.parse().map(BinOp::BitAndEq) - } else if input.peek(Token![|=]) { - input.parse().map(BinOp::BitOrEq) - } else if input.peek(Token![<<=]) { - input.parse().map(BinOp::ShlEq) - } else if input.peek(Token![>>=]) { - input.parse().map(BinOp::ShrEq) - } else { - parse_binop(input) - } - } - } - - impl Parse for UnOp { - fn parse(input: ParseStream) -> Result<Self> { - let lookahead = input.lookahead1(); - if lookahead.peek(Token![*]) { - input.parse().map(UnOp::Deref) - } else if lookahead.peek(Token![!]) { - input.parse().map(UnOp::Not) - } else if lookahead.peek(Token![-]) { - input.parse().map(UnOp::Neg) - } else { - Err(lookahead.error()) - } - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - use proc_macro2::TokenStream; - use quote::ToTokens; - - impl ToTokens for BinOp { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - BinOp::Add(ref t) => t.to_tokens(tokens), - BinOp::Sub(ref t) => t.to_tokens(tokens), - BinOp::Mul(ref t) => t.to_tokens(tokens), - BinOp::Div(ref t) => t.to_tokens(tokens), - BinOp::Rem(ref t) => t.to_tokens(tokens), - BinOp::And(ref t) => t.to_tokens(tokens), - BinOp::Or(ref t) => t.to_tokens(tokens), - BinOp::BitXor(ref t) => t.to_tokens(tokens), - BinOp::BitAnd(ref t) => t.to_tokens(tokens), - BinOp::BitOr(ref t) => t.to_tokens(tokens), - BinOp::Shl(ref t) => t.to_tokens(tokens), - BinOp::Shr(ref t) => t.to_tokens(tokens), - BinOp::Eq(ref t) => t.to_tokens(tokens), - BinOp::Lt(ref t) => t.to_tokens(tokens), - BinOp::Le(ref t) => t.to_tokens(tokens), - BinOp::Ne(ref t) => t.to_tokens(tokens), - BinOp::Ge(ref t) => t.to_tokens(tokens), - BinOp::Gt(ref t) => t.to_tokens(tokens), - BinOp::AddEq(ref t) => t.to_tokens(tokens), - BinOp::SubEq(ref t) => t.to_tokens(tokens), - BinOp::MulEq(ref t) => t.to_tokens(tokens), - BinOp::DivEq(ref t) => t.to_tokens(tokens), - BinOp::RemEq(ref t) => t.to_tokens(tokens), - BinOp::BitXorEq(ref t) => t.to_tokens(tokens), - BinOp::BitAndEq(ref t) => t.to_tokens(tokens), - BinOp::BitOrEq(ref t) => t.to_tokens(tokens), - BinOp::ShlEq(ref t) => t.to_tokens(tokens), - BinOp::ShrEq(ref t) => t.to_tokens(tokens), - } - } - } - - impl ToTokens for UnOp { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - UnOp::Deref(ref t) => t.to_tokens(tokens), - UnOp::Not(ref t) => t.to_tokens(tokens), - UnOp::Neg(ref t) => t.to_tokens(tokens), - } - } - } -} diff --git a/0.15.42/src/parse.rs b/0.15.42/src/parse.rs deleted file mode 100644 index 4ecbaf24..00000000 --- a/0.15.42/src/parse.rs +++ /dev/null @@ -1,1147 +0,0 @@ -//! Parsing interface for parsing a token stream into a syntax tree node. -//! -//! Parsing in Syn is built on parser functions that take in a [`ParseStream`] -//! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying -//! these parser functions is a lower level mechanism built around the -//! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of -//! tokens in a token stream. -//! -//! [`ParseStream`]: type.ParseStream.html -//! [`Result<T>`]: type.Result.html -//! [`Cursor`]: ../buffer/index.html -//! -//! # Example -//! -//! Here is a snippet of parsing code to get a feel for the style of the -//! library. We define data structures for a subset of Rust syntax including -//! enums (not shown) and structs, then provide implementations of the [`Parse`] -//! trait to parse these syntax tree data structures from a token stream. -//! -//! Once `Parse` impls have been defined, they can be called conveniently from a -//! procedural macro through [`parse_macro_input!`] as shown at the bottom of -//! the snippet. If the caller provides syntactically invalid input to the -//! procedural macro, they will receive a helpful compiler error message -//! pointing out the exact token that triggered the failure to parse. -//! -//! [`parse_macro_input!`]: ../macro.parse_macro_input.html -//! -//! ```edition2018 -//! extern crate proc_macro; -//! -//! use proc_macro::TokenStream; -//! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token}; -//! use syn::parse::{Parse, ParseStream}; -//! use syn::punctuated::Punctuated; -//! -//! enum Item { -//! Struct(ItemStruct), -//! Enum(ItemEnum), -//! } -//! -//! struct ItemStruct { -//! struct_token: Token![struct], -//! ident: Ident, -//! brace_token: token::Brace, -//! fields: Punctuated<Field, Token![,]>, -//! } -//! # -//! # enum ItemEnum {} -//! -//! impl Parse for Item { -//! fn parse(input: ParseStream) -> Result<Self> { -//! let lookahead = input.lookahead1(); -//! if lookahead.peek(Token![struct]) { -//! input.parse().map(Item::Struct) -//! } else if lookahead.peek(Token![enum]) { -//! input.parse().map(Item::Enum) -//! } else { -//! Err(lookahead.error()) -//! } -//! } -//! } -//! -//! impl Parse for ItemStruct { -//! fn parse(input: ParseStream) -> Result<Self> { -//! let content; -//! Ok(ItemStruct { -//! struct_token: input.parse()?, -//! ident: input.parse()?, -//! brace_token: braced!(content in input), -//! fields: content.parse_terminated(Field::parse_named)?, -//! }) -//! } -//! } -//! # -//! # impl Parse for ItemEnum { -//! # fn parse(input: ParseStream) -> Result<Self> { -//! # unimplemented!() -//! # } -//! # } -//! -//! # const IGNORE: &str = stringify! { -//! #[proc_macro] -//! # }; -//! pub fn my_macro(tokens: TokenStream) -> TokenStream { -//! let input = parse_macro_input!(tokens as Item); -//! -//! /* ... */ -//! # "".parse().unwrap() -//! } -//! ``` -//! -//! # The `syn::parse*` functions -//! -//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve -//! as an entry point for parsing syntax tree nodes that can be parsed in an -//! obvious default way. These functions can return any syntax tree node that -//! implements the [`Parse`] trait, which includes most types in Syn. -//! -//! [`syn::parse`]: ../fn.parse.html -//! [`syn::parse2`]: ../fn.parse2.html -//! [`syn::parse_str`]: ../fn.parse_str.html -//! [`Parse`]: trait.Parse.html -//! -//! ```edition2018 -//! use syn::Type; -//! -//! # fn run_parser() -> syn::Result<()> { -//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?; -//! # Ok(()) -//! # } -//! # -//! # fn main() { -//! # run_parser().unwrap(); -//! # } -//! ``` -//! -//! The [`parse_quote!`] macro also uses this approach. -//! -//! [`parse_quote!`]: ../macro.parse_quote.html -//! -//! # The `Parser` trait -//! -//! Some types can be parsed in several ways depending on context. For example -//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like -//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`] -//! may or may not allow trailing punctuation, and parsing it the wrong way -//! would either reject valid input or accept invalid input. -//! -//! [`Attribute`]: ../struct.Attribute.html -//! [`Punctuated`]: ../punctuated/index.html -//! -//! The `Parse` trait is not implemented in these cases because there is no good -//! behavior to consider the default. -//! -//! ```edition2018,compile_fail -//! # extern crate proc_macro; -//! # -//! # use syn::punctuated::Punctuated; -//! # use syn::{PathSegment, Result, Token}; -//! # -//! # fn f(tokens: proc_macro::TokenStream) -> Result<()> { -//! # -//! // Can't parse `Punctuated` without knowing whether trailing punctuation -//! // should be allowed in this context. -//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?; -//! # -//! # Ok(()) -//! # } -//! ``` -//! -//! In these cases the types provide a choice of parser functions rather than a -//! single `Parse` implementation, and those parser functions can be invoked -//! through the [`Parser`] trait. -//! -//! [`Parser`]: trait.Parser.html -//! -//! ```edition2018 -//! extern crate proc_macro; -//! -//! use proc_macro::TokenStream; -//! use syn::parse::Parser; -//! use syn::punctuated::Punctuated; -//! use syn::{Attribute, Expr, PathSegment, Result, Token}; -//! -//! fn call_some_parser_methods(input: TokenStream) -> Result<()> { -//! // Parse a nonempty sequence of path segments separated by `::` punctuation -//! // with no trailing punctuation. -//! let tokens = input.clone(); -//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty; -//! let _path = parser.parse(tokens)?; -//! -//! // Parse a possibly empty sequence of expressions terminated by commas with -//! // an optional trailing punctuation. -//! let tokens = input.clone(); -//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated; -//! let _args = parser.parse(tokens)?; -//! -//! // Parse zero or more outer attributes but not inner attributes. -//! let tokens = input.clone(); -//! let parser = Attribute::parse_outer; -//! let _attrs = parser.parse(tokens)?; -//! -//! Ok(()) -//! } -//! ``` -//! -//! --- -//! -//! *This module is available if Syn is built with the `"parsing"` feature.* - -#[path = "discouraged.rs"] -pub mod discouraged; - -use std::cell::Cell; -use std::fmt::{self, Debug, Display}; -use std::marker::PhantomData; -use std::mem; -use std::ops::Deref; -use std::rc::Rc; -use std::str::FromStr; - -#[cfg(all( - not(all(target_arch = "wasm32", target_os = "unknown")), - feature = "proc-macro" -))] -use proc_macro; -use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree}; - -use buffer::{Cursor, TokenBuffer}; -use error; -use lookahead; -use private; -use punctuated::Punctuated; -use token::Token; - -pub use error::{Error, Result}; -pub use lookahead::{Lookahead1, Peek}; - -/// Parsing interface implemented by all types that can be parsed in a default -/// way from a token stream. -pub trait Parse: Sized { - fn parse(input: ParseStream) -> Result<Self>; -} - -/// Input to a Syn parser function. -/// -/// See the methods of this type under the documentation of [`ParseBuffer`]. For -/// an overview of parsing in Syn, refer to the [module documentation]. -/// -/// [module documentation]: self -pub type ParseStream<'a> = &'a ParseBuffer<'a>; - -/// Cursor position within a buffered token stream. -/// -/// This type is more commonly used through the type alias [`ParseStream`] which -/// is an alias for `&ParseBuffer`. -/// -/// `ParseStream` is the input type for all parser functions in Syn. They have -/// the signature `fn(ParseStream) -> Result<T>`. -/// -/// ## Calling a parser function -/// -/// There is no public way to construct a `ParseBuffer`. Instead, if you are -/// looking to invoke a parser function that requires `ParseStream` as input, -/// you will need to go through one of the public parsing entry points. -/// -/// - The [`parse_macro_input!`] macro if parsing input of a procedural macro; -/// - One of [the `syn::parse*` functions][syn-parse]; or -/// - A method of the [`Parser`] trait. -/// -/// [syn-parse]: index.html#the-synparse-functions -pub struct ParseBuffer<'a> { - scope: Span, - // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a. - // The rest of the code in this module needs to be careful that only a - // cursor derived from this `cell` is ever assigned to this `cell`. - // - // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a - // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter - // than 'a, and then assign a Cursor<'short> into the Cell. - // - // By extension, it would not be safe to expose an API that accepts a - // Cursor<'a> and trusts that it lives as long as the cursor currently in - // the cell. - cell: Cell<Cursor<'static>>, - marker: PhantomData<Cursor<'a>>, - unexpected: Rc<Cell<Option<Span>>>, -} - -impl<'a> Drop for ParseBuffer<'a> { - fn drop(&mut self) { - if !self.is_empty() && self.unexpected.get().is_none() { - self.unexpected.set(Some(self.cursor().span())); - } - } -} - -impl<'a> Display for ParseBuffer<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - Display::fmt(&self.cursor().token_stream(), f) - } -} - -impl<'a> Debug for ParseBuffer<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - Debug::fmt(&self.cursor().token_stream(), f) - } -} - -/// Cursor state associated with speculative parsing. -/// -/// This type is the input of the closure provided to [`ParseStream::step`]. -/// -/// [`ParseStream::step`]: ParseBuffer::step -/// -/// # Example -/// -/// ```edition2018 -/// use proc_macro2::TokenTree; -/// use syn::Result; -/// use syn::parse::ParseStream; -/// -/// // This function advances the stream past the next occurrence of `@`. If -/// // no `@` is present in the stream, the stream position is unchanged and -/// // an error is returned. -/// fn skip_past_next_at(input: ParseStream) -> Result<()> { -/// input.step(|cursor| { -/// let mut rest = *cursor; -/// while let Some((tt, next)) = rest.token_tree() { -/// match &tt { -/// TokenTree::Punct(punct) if punct.as_char() == '@' => { -/// return Ok(((), next)); -/// } -/// _ => rest = next, -/// } -/// } -/// Err(cursor.error("no `@` was found after this point")) -/// }) -/// } -/// # -/// # fn remainder_after_skipping_past_next_at( -/// # input: ParseStream, -/// # ) -> Result<proc_macro2::TokenStream> { -/// # skip_past_next_at(input)?; -/// # input.parse() -/// # } -/// # -/// # fn main() { -/// # use syn::parse::Parser; -/// # let remainder = remainder_after_skipping_past_next_at -/// # .parse_str("a @ b c") -/// # .unwrap(); -/// # assert_eq!(remainder.to_string(), "b c"); -/// # } -/// ``` -#[derive(Copy, Clone)] -pub struct StepCursor<'c, 'a> { - scope: Span, - // This field is covariant in 'c. - cursor: Cursor<'c>, - // This field is contravariant in 'c. Together these make StepCursor - // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a - // different lifetime but can upcast into a StepCursor with a shorter - // lifetime 'a. - // - // As long as we only ever construct a StepCursor for which 'c outlives 'a, - // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c - // outlives 'a. - marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>, -} - -impl<'c, 'a> Deref for StepCursor<'c, 'a> { - type Target = Cursor<'c>; - - fn deref(&self) -> &Self::Target { - &self.cursor - } -} - -impl<'c, 'a> StepCursor<'c, 'a> { - /// Triggers an error at the current position of the parse stream. - /// - /// The `ParseStream::step` invocation will return this same error without - /// advancing the stream state. - pub fn error<T: Display>(self, message: T) -> Error { - error::new_at(self.scope, self.cursor, message) - } -} - -impl private { - pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> { - // Refer to the comments within the StepCursor definition. We use the - // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a. - // Cursor is covariant in its lifetime parameter so we can cast a - // Cursor<'c> to one with the shorter lifetime Cursor<'a>. - let _ = proof; - unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) } - } -} - -fn skip(input: ParseStream) -> bool { - input - .step(|cursor| { - if let Some((_lifetime, rest)) = cursor.lifetime() { - Ok((true, rest)) - } else if let Some((_token, rest)) = cursor.token_tree() { - Ok((true, rest)) - } else { - Ok((false, *cursor)) - } - }) - .unwrap() -} - -impl private { - pub fn new_parse_buffer( - scope: Span, - cursor: Cursor, - unexpected: Rc<Cell<Option<Span>>>, - ) -> ParseBuffer { - ParseBuffer { - scope: scope, - // See comment on `cell` in the struct definition. - cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }), - marker: PhantomData, - unexpected: unexpected, - } - } - - pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> { - buffer.unexpected.clone() - } -} - -impl<'a> ParseBuffer<'a> { - /// Parses a syntax tree node of type `T`, advancing the position of our - /// parse stream past it. - pub fn parse<T: Parse>(&self) -> Result<T> { - T::parse(self) - } - - /// Calls the given parser function to parse a syntax tree node of type `T` - /// from this stream. - /// - /// # Example - /// - /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of - /// zero or more outer attributes. - /// - /// [`Attribute::parse_outer`]: crate::Attribute::parse_outer - /// - /// ```edition2018 - /// use syn::{Attribute, Ident, Result, Token}; - /// use syn::parse::{Parse, ParseStream}; - /// - /// // Parses a unit struct with attributes. - /// // - /// // #[path = "s.tmpl"] - /// // struct S; - /// struct UnitStruct { - /// attrs: Vec<Attribute>, - /// struct_token: Token![struct], - /// name: Ident, - /// semi_token: Token![;], - /// } - /// - /// impl Parse for UnitStruct { - /// fn parse(input: ParseStream) -> Result<Self> { - /// Ok(UnitStruct { - /// attrs: input.call(Attribute::parse_outer)?, - /// struct_token: input.parse()?, - /// name: input.parse()?, - /// semi_token: input.parse()?, - /// }) - /// } - /// } - /// ``` - pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> { - function(self) - } - - /// Looks at the next token in the parse stream to determine whether it - /// matches the requested type of token. - /// - /// Does not advance the position of the parse stream. - /// - /// # Syntax - /// - /// Note that this method does not use turbofish syntax. Pass the peek type - /// inside of parentheses. - /// - /// - `input.peek(Token![struct])` - /// - `input.peek(Token![==])` - /// - `input.peek(Ident)` *(does not accept keywords)* - /// - `input.peek(Ident::peek_any)` - /// - `input.peek(Lifetime)` - /// - `input.peek(token::Brace)` - /// - /// # Example - /// - /// In this example we finish parsing the list of supertraits when the next - /// token in the input is either `where` or an opening curly brace. - /// - /// ```edition2018 - /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound}; - /// use syn::parse::{Parse, ParseStream}; - /// use syn::punctuated::Punctuated; - /// - /// // Parses a trait definition containing no associated items. - /// // - /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {} - /// struct MarkerTrait { - /// trait_token: Token![trait], - /// ident: Ident, - /// generics: Generics, - /// colon_token: Option<Token![:]>, - /// supertraits: Punctuated<TypeParamBound, Token![+]>, - /// brace_token: token::Brace, - /// } - /// - /// impl Parse for MarkerTrait { - /// fn parse(input: ParseStream) -> Result<Self> { - /// let trait_token: Token![trait] = input.parse()?; - /// let ident: Ident = input.parse()?; - /// let mut generics: Generics = input.parse()?; - /// let colon_token: Option<Token![:]> = input.parse()?; - /// - /// let mut supertraits = Punctuated::new(); - /// if colon_token.is_some() { - /// loop { - /// supertraits.push_value(input.parse()?); - /// if input.peek(Token![where]) || input.peek(token::Brace) { - /// break; - /// } - /// supertraits.push_punct(input.parse()?); - /// } - /// } - /// - /// generics.where_clause = input.parse()?; - /// let content; - /// let empty_brace_token = braced!(content in input); - /// - /// Ok(MarkerTrait { - /// trait_token: trait_token, - /// ident: ident, - /// generics: generics, - /// colon_token: colon_token, - /// supertraits: supertraits, - /// brace_token: empty_brace_token, - /// }) - /// } - /// } - /// ``` - pub fn peek<T: Peek>(&self, token: T) -> bool { - let _ = token; - T::Token::peek(self.cursor()) - } - - /// Looks at the second-next token in the parse stream. - /// - /// This is commonly useful as a way to implement contextual keywords. - /// - /// # Example - /// - /// This example needs to use `peek2` because the symbol `union` is not a - /// keyword in Rust. We can't use just `peek` and decide to parse a union if - /// the very next token is `union`, because someone is free to write a `mod - /// union` and a macro invocation that looks like `union::some_macro! { ... - /// }`. In other words `union` is a contextual keyword. - /// - /// ```edition2018 - /// use syn::{Ident, ItemUnion, Macro, Result, Token}; - /// use syn::parse::{Parse, ParseStream}; - /// - /// // Parses either a union or a macro invocation. - /// enum UnionOrMacro { - /// // union MaybeUninit<T> { uninit: (), value: T } - /// Union(ItemUnion), - /// // lazy_static! { ... } - /// Macro(Macro), - /// } - /// - /// impl Parse for UnionOrMacro { - /// fn parse(input: ParseStream) -> Result<Self> { - /// if input.peek(Token![union]) && input.peek2(Ident) { - /// input.parse().map(UnionOrMacro::Union) - /// } else { - /// input.parse().map(UnionOrMacro::Macro) - /// } - /// } - /// } - /// ``` - pub fn peek2<T: Peek>(&self, token: T) -> bool { - let ahead = self.fork(); - skip(&ahead) && ahead.peek(token) - } - - /// Looks at the third-next token in the parse stream. - pub fn peek3<T: Peek>(&self, token: T) -> bool { - let ahead = self.fork(); - skip(&ahead) && skip(&ahead) && ahead.peek(token) - } - - /// Parses zero or more occurrences of `T` separated by punctuation of type - /// `P`, with optional trailing punctuation. - /// - /// Parsing continues until the end of this parse stream. The entire content - /// of this parse stream must consist of `T` and `P`. - /// - /// # Example - /// - /// ```edition2018 - /// # use quote::quote; - /// # - /// use syn::{parenthesized, token, Ident, Result, Token, Type}; - /// use syn::parse::{Parse, ParseStream}; - /// use syn::punctuated::Punctuated; - /// - /// // Parse a simplified tuple struct syntax like: - /// // - /// // struct S(A, B); - /// struct TupleStruct { - /// struct_token: Token![struct], - /// ident: Ident, - /// paren_token: token::Paren, - /// fields: Punctuated<Type, Token![,]>, - /// semi_token: Token![;], - /// } - /// - /// impl Parse for TupleStruct { - /// fn parse(input: ParseStream) -> Result<Self> { - /// let content; - /// Ok(TupleStruct { - /// struct_token: input.parse()?, - /// ident: input.parse()?, - /// paren_token: parenthesized!(content in input), - /// fields: content.parse_terminated(Type::parse)?, - /// semi_token: input.parse()?, - /// }) - /// } - /// } - /// # - /// # fn main() { - /// # let input = quote! { - /// # struct S(A, B); - /// # }; - /// # syn::parse2::<TupleStruct>(input).unwrap(); - /// # } - /// ``` - pub fn parse_terminated<T, P: Parse>( - &self, - parser: fn(ParseStream) -> Result<T>, - ) -> Result<Punctuated<T, P>> { - Punctuated::parse_terminated_with(self, parser) - } - - /// Returns whether there are tokens remaining in this stream. - /// - /// This method returns true at the end of the content of a set of - /// delimiters, as well as at the very end of the complete macro input. - /// - /// # Example - /// - /// ```edition2018 - /// use syn::{braced, token, Ident, Item, Result, Token}; - /// use syn::parse::{Parse, ParseStream}; - /// - /// // Parses a Rust `mod m { ... }` containing zero or more items. - /// struct Mod { - /// mod_token: Token![mod], - /// name: Ident, - /// brace_token: token::Brace, - /// items: Vec<Item>, - /// } - /// - /// impl Parse for Mod { - /// fn parse(input: ParseStream) -> Result<Self> { - /// let content; - /// Ok(Mod { - /// mod_token: input.parse()?, - /// name: input.parse()?, - /// brace_token: braced!(content in input), - /// items: { - /// let mut items = Vec::new(); - /// while !content.is_empty() { - /// items.push(content.parse()?); - /// } - /// items - /// }, - /// }) - /// } - /// } - /// ``` - pub fn is_empty(&self) -> bool { - self.cursor().eof() - } - - /// Constructs a helper for peeking at the next token in this stream and - /// building an error message if it is not one of a set of expected tokens. - /// - /// # Example - /// - /// ```edition2018 - /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam}; - /// use syn::parse::{Parse, ParseStream}; - /// - /// // A generic parameter, a single one of the comma-separated elements inside - /// // angle brackets in: - /// // - /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... } - /// // - /// // On invalid input, lookahead gives us a reasonable error message. - /// // - /// // error: expected one of: identifier, lifetime, `const` - /// // | - /// // 5 | fn f<!Sized>() {} - /// // | ^ - /// enum GenericParam { - /// Type(TypeParam), - /// Lifetime(LifetimeDef), - /// Const(ConstParam), - /// } - /// - /// impl Parse for GenericParam { - /// fn parse(input: ParseStream) -> Result<Self> { - /// let lookahead = input.lookahead1(); - /// if lookahead.peek(Ident) { - /// input.parse().map(GenericParam::Type) - /// } else if lookahead.peek(Lifetime) { - /// input.parse().map(GenericParam::Lifetime) - /// } else if lookahead.peek(Token![const]) { - /// input.parse().map(GenericParam::Const) - /// } else { - /// Err(lookahead.error()) - /// } - /// } - /// } - /// ``` - pub fn lookahead1(&self) -> Lookahead1<'a> { - lookahead::new(self.scope, self.cursor()) - } - - /// Forks a parse stream so that parsing tokens out of either the original - /// or the fork does not advance the position of the other. - /// - /// # Performance - /// - /// Forking a parse stream is a cheap fixed amount of work and does not - /// involve copying token buffers. Where you might hit performance problems - /// is if your macro ends up parsing a large amount of content more than - /// once. - /// - /// ```edition2018 - /// # use syn::{Expr, Result}; - /// # use syn::parse::ParseStream; - /// # - /// # fn bad(input: ParseStream) -> Result<Expr> { - /// // Do not do this. - /// if input.fork().parse::<Expr>().is_ok() { - /// return input.parse::<Expr>(); - /// } - /// # unimplemented!() - /// # } - /// ``` - /// - /// As a rule, avoid parsing an unbounded amount of tokens out of a forked - /// parse stream. Only use a fork when the amount of work performed against - /// the fork is small and bounded. - /// - /// When complex speculative parsing against the forked stream is - /// unavoidable, use [`parse::discouraged::Speculative`] to advance the - /// original stream once the fork's parse is determined to have been - /// successful. - /// - /// For a lower level way to perform speculative parsing at the token level, - /// consider using [`ParseStream::step`] instead. - /// - /// [`parse::discouraged::Speculative`]: discouraged::Speculative - /// [`ParseStream::step`]: ParseBuffer::step - /// - /// # Example - /// - /// The parse implementation shown here parses possibly restricted `pub` - /// visibilities. - /// - /// - `pub` - /// - `pub(crate)` - /// - `pub(self)` - /// - `pub(super)` - /// - `pub(in some::path)` - /// - /// To handle the case of visibilities inside of tuple structs, the parser - /// needs to distinguish parentheses that specify visibility restrictions - /// from parentheses that form part of a tuple type. - /// - /// ```edition2018 - /// # struct A; - /// # struct B; - /// # struct C; - /// # - /// struct S(pub(crate) A, pub (B, C)); - /// ``` - /// - /// In this example input the first tuple struct element of `S` has - /// `pub(crate)` visibility while the second tuple struct element has `pub` - /// visibility; the parentheses around `(B, C)` are part of the type rather - /// than part of a visibility restriction. - /// - /// The parser uses a forked parse stream to check the first token inside of - /// parentheses after the `pub` keyword. This is a small bounded amount of - /// work performed against the forked parse stream. - /// - /// ```edition2018 - /// use syn::{parenthesized, token, Ident, Path, Result, Token}; - /// use syn::ext::IdentExt; - /// use syn::parse::{Parse, ParseStream}; - /// - /// struct PubVisibility { - /// pub_token: Token![pub], - /// restricted: Option<Restricted>, - /// } - /// - /// struct Restricted { - /// paren_token: token::Paren, - /// in_token: Option<Token![in]>, - /// path: Path, - /// } - /// - /// impl Parse for PubVisibility { - /// fn parse(input: ParseStream) -> Result<Self> { - /// let pub_token: Token![pub] = input.parse()?; - /// - /// if input.peek(token::Paren) { - /// let ahead = input.fork(); - /// let mut content; - /// parenthesized!(content in ahead); - /// - /// if content.peek(Token![crate]) - /// || content.peek(Token![self]) - /// || content.peek(Token![super]) - /// { - /// return Ok(PubVisibility { - /// pub_token: pub_token, - /// restricted: Some(Restricted { - /// paren_token: parenthesized!(content in input), - /// in_token: None, - /// path: Path::from(content.call(Ident::parse_any)?), - /// }), - /// }); - /// } else if content.peek(Token![in]) { - /// return Ok(PubVisibility { - /// pub_token: pub_token, - /// restricted: Some(Restricted { - /// paren_token: parenthesized!(content in input), - /// in_token: Some(content.parse()?), - /// path: content.call(Path::parse_mod_style)?, - /// }), - /// }); - /// } - /// } - /// - /// Ok(PubVisibility { - /// pub_token: pub_token, - /// restricted: None, - /// }) - /// } - /// } - /// ``` - pub fn fork(&self) -> Self { - ParseBuffer { - scope: self.scope, - cell: self.cell.clone(), - marker: PhantomData, - // Not the parent's unexpected. Nothing cares whether the clone - // parses all the way. - unexpected: Rc::new(Cell::new(None)), - } - } - - /// Triggers an error at the current position of the parse stream. - /// - /// # Example - /// - /// ```edition2018 - /// use syn::{Expr, Result, Token}; - /// use syn::parse::{Parse, ParseStream}; - /// - /// // Some kind of loop: `while` or `for` or `loop`. - /// struct Loop { - /// expr: Expr, - /// } - /// - /// impl Parse for Loop { - /// fn parse(input: ParseStream) -> Result<Self> { - /// if input.peek(Token![while]) - /// || input.peek(Token![for]) - /// || input.peek(Token![loop]) - /// { - /// Ok(Loop { - /// expr: input.parse()?, - /// }) - /// } else { - /// Err(input.error("expected some kind of loop")) - /// } - /// } - /// } - /// ``` - pub fn error<T: Display>(&self, message: T) -> Error { - error::new_at(self.scope, self.cursor(), message) - } - - /// Speculatively parses tokens from this parse stream, advancing the - /// position of this stream only if parsing succeeds. - /// - /// This is a powerful low-level API used for defining the `Parse` impls of - /// the basic built-in token types. It is not something that will be used - /// widely outside of the Syn codebase. - /// - /// # Example - /// - /// ```edition2018 - /// use proc_macro2::TokenTree; - /// use syn::Result; - /// use syn::parse::ParseStream; - /// - /// // This function advances the stream past the next occurrence of `@`. If - /// // no `@` is present in the stream, the stream position is unchanged and - /// // an error is returned. - /// fn skip_past_next_at(input: ParseStream) -> Result<()> { - /// input.step(|cursor| { - /// let mut rest = *cursor; - /// while let Some((tt, next)) = rest.token_tree() { - /// match &tt { - /// TokenTree::Punct(punct) if punct.as_char() == '@' => { - /// return Ok(((), next)); - /// } - /// _ => rest = next, - /// } - /// } - /// Err(cursor.error("no `@` was found after this point")) - /// }) - /// } - /// # - /// # fn remainder_after_skipping_past_next_at( - /// # input: ParseStream, - /// # ) -> Result<proc_macro2::TokenStream> { - /// # skip_past_next_at(input)?; - /// # input.parse() - /// # } - /// # - /// # fn main() { - /// # use syn::parse::Parser; - /// # let remainder = remainder_after_skipping_past_next_at - /// # .parse_str("a @ b c") - /// # .unwrap(); - /// # assert_eq!(remainder.to_string(), "b c"); - /// # } - /// ``` - pub fn step<F, R>(&self, function: F) -> Result<R> - where - F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>, - { - // Since the user's function is required to work for any 'c, we know - // that the Cursor<'c> they return is either derived from the input - // StepCursor<'c, 'a> or from a Cursor<'static>. - // - // It would not be legal to write this function without the invariant - // lifetime 'c in StepCursor<'c, 'a>. If this function were written only - // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to - // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke - // `step` on their ParseBuffer<'short> with a closure that returns - // Cursor<'short>, and we would wrongly write that Cursor<'short> into - // the Cell intended to hold Cursor<'a>. - // - // In some cases it may be necessary for R to contain a Cursor<'a>. - // Within Syn we solve this using `private::advance_step_cursor` which - // uses the existence of a StepCursor<'c, 'a> as proof that it is safe - // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it - // would be safe to expose that API as a method on StepCursor. - let (node, rest) = function(StepCursor { - scope: self.scope, - cursor: self.cell.get(), - marker: PhantomData, - })?; - self.cell.set(rest); - Ok(node) - } - - /// Provides low-level access to the token representation underlying this - /// parse stream. - /// - /// Cursors are immutable so no operations you perform against the cursor - /// will affect the state of this parse stream. - pub fn cursor(&self) -> Cursor<'a> { - self.cell.get() - } - - fn check_unexpected(&self) -> Result<()> { - match self.unexpected.get() { - Some(span) => Err(Error::new(span, "unexpected token")), - None => Ok(()), - } - } -} - -impl<T: Parse> Parse for Box<T> { - fn parse(input: ParseStream) -> Result<Self> { - input.parse().map(Box::new) - } -} - -impl<T: Parse + Token> Parse for Option<T> { - fn parse(input: ParseStream) -> Result<Self> { - if T::peek(input.cursor()) { - Ok(Some(input.parse()?)) - } else { - Ok(None) - } - } -} - -impl Parse for TokenStream { - fn parse(input: ParseStream) -> Result<Self> { - input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty()))) - } -} - -impl Parse for TokenTree { - fn parse(input: ParseStream) -> Result<Self> { - input.step(|cursor| match cursor.token_tree() { - Some((tt, rest)) => Ok((tt, rest)), - None => Err(cursor.error("expected token tree")), - }) - } -} - -impl Parse for Group { - fn parse(input: ParseStream) -> Result<Self> { - input.step(|cursor| { - for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] { - if let Some((inside, span, rest)) = cursor.group(*delim) { - let mut group = Group::new(*delim, inside.token_stream()); - group.set_span(span); - return Ok((group, rest)); - } - } - Err(cursor.error("expected group token")) - }) - } -} - -impl Parse for Punct { - fn parse(input: ParseStream) -> Result<Self> { - input.step(|cursor| match cursor.punct() { - Some((punct, rest)) => Ok((punct, rest)), - None => Err(cursor.error("expected punctuation token")), - }) - } -} - -impl Parse for Literal { - fn parse(input: ParseStream) -> Result<Self> { - input.step(|cursor| match cursor.literal() { - Some((literal, rest)) => Ok((literal, rest)), - None => Err(cursor.error("expected literal token")), - }) - } -} - -/// Parser that can parse Rust tokens into a particular syntax tree node. -/// -/// Refer to the [module documentation] for details about parsing in Syn. -/// -/// [module documentation]: self -/// -/// *This trait is available if Syn is built with the `"parsing"` feature.* -pub trait Parser: Sized { - type Output; - - /// 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. - fn parse2(self, tokens: TokenStream) -> Result<Self::Output>; - - /// 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 method is available if Syn is built with both the `"parsing"` and - /// `"proc-macro"` features.* - #[cfg(all( - not(all(target_arch = "wasm32", target_os = "unknown")), - feature = "proc-macro" - ))] - fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> { - self.parse2(proc_macro2::TokenStream::from(tokens)) - } - - /// 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. - /// - /// # Hygiene - /// - /// Every span in the resulting syntax tree will be set to resolve at the - /// macro call site. - fn parse_str(self, s: &str) -> Result<Self::Output> { - self.parse2(proc_macro2::TokenStream::from_str(s)?) - } - - // Not public API. - #[doc(hidden)] - fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> { - let _ = scope; - self.parse2(tokens) - } -} - -fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer { - let scope = Span::call_site(); - let cursor = tokens.begin(); - let unexpected = Rc::new(Cell::new(None)); - private::new_parse_buffer(scope, cursor, unexpected) -} - -impl<F, T> Parser for F -where - F: FnOnce(ParseStream) -> Result<T>, -{ - type Output = T; - - fn parse2(self, tokens: TokenStream) -> Result<T> { - let buf = TokenBuffer::new2(tokens); - let state = tokens_to_parse_buffer(&buf); - let node = self(&state)?; - state.check_unexpected()?; - if state.is_empty() { - Ok(node) - } else { - Err(state.error("unexpected token")) - } - } - - #[doc(hidden)] - fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> { - let buf = TokenBuffer::new2(tokens); - let cursor = buf.begin(); - let unexpected = Rc::new(Cell::new(None)); - let state = private::new_parse_buffer(scope, cursor, unexpected); - let node = self(&state)?; - state.check_unexpected()?; - if state.is_empty() { - Ok(node) - } else { - Err(state.error("unexpected token")) - } - } -} - -impl private { - pub fn parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output> { - f.__parse_scoped(scope, tokens) - } -} diff --git a/0.15.42/src/parse_macro_input.rs b/0.15.42/src/parse_macro_input.rs deleted file mode 100644 index c70cb00f..00000000 --- a/0.15.42/src/parse_macro_input.rs +++ /dev/null @@ -1,106 +0,0 @@ -/// Parse the input TokenStream of a macro, triggering a compile error if the -/// tokens fail to parse. -/// -/// Refer to the [`parse` module] documentation for more details about parsing -/// in Syn. -/// -/// [`parse` module]: parse/index.html -/// -/// # Intended usage -/// -/// ```edition2018 -/// extern crate proc_macro; -/// -/// use proc_macro::TokenStream; -/// use syn::{parse_macro_input, Result}; -/// use syn::parse::{Parse, ParseStream}; -/// -/// struct MyMacroInput { -/// /* ... */ -/// } -/// -/// impl Parse for MyMacroInput { -/// fn parse(input: ParseStream) -> Result<Self> { -/// /* ... */ -/// # Ok(MyMacroInput {}) -/// } -/// } -/// -/// # const IGNORE: &str = stringify! { -/// #[proc_macro] -/// # }; -/// pub fn my_macro(tokens: TokenStream) -> TokenStream { -/// let input = parse_macro_input!(tokens as MyMacroInput); -/// -/// /* ... */ -/// # "".parse().unwrap() -/// } -/// ``` -// -// TODO: change the parse module link to an intra rustdoc link, currently -// blocked on https://github.com/rust-lang/rust/issues/62830 -#[macro_export(local_inner_macros)] -macro_rules! parse_macro_input { - ($tokenstream:ident as $ty:ty) => { - match $crate::parse_macro_input::parse::<$ty>($tokenstream) { - $crate::export::Ok(data) => data, - $crate::export::Err(err) => { - return $crate::export::TokenStream::from(err.to_compile_error()); - } - } - }; - ($tokenstream:ident) => { - parse_macro_input!($tokenstream as _) - }; -} - -//////////////////////////////////////////////////////////////////////////////// -// Can parse any type that implements Parse. - -use parse::{Parse, ParseStream, Parser, Result}; -use proc_macro::TokenStream; - -// Not public API. -#[doc(hidden)] -pub fn parse<T: ParseMacroInput>(token_stream: TokenStream) -> Result<T> { - T::parse.parse(token_stream) -} - -// Not public API. -#[doc(hidden)] -pub trait ParseMacroInput: Sized { - fn parse(input: ParseStream) -> Result<Self>; -} - -impl<T: Parse> ParseMacroInput for T { - fn parse(input: ParseStream) -> Result<Self> { - <T as Parse>::parse(input) - } -} - -//////////////////////////////////////////////////////////////////////////////// -// Any other types that we want `parse_macro_input!` to be able to parse. - -#[cfg(any(feature = "full", feature = "derive"))] -use AttributeArgs; - -#[cfg(any(feature = "full", feature = "derive"))] -impl ParseMacroInput for AttributeArgs { - fn parse(input: ParseStream) -> Result<Self> { - let mut metas = Vec::new(); - - loop { - if input.is_empty() { - break; - } - let value = input.parse()?; - metas.push(value); - if input.is_empty() { - break; - } - input.parse::<Token![,]>()?; - } - - Ok(metas) - } -} diff --git a/0.15.42/src/parse_quote.rs b/0.15.42/src/parse_quote.rs deleted file mode 100644 index ed5cf7d8..00000000 --- a/0.15.42/src/parse_quote.rs +++ /dev/null @@ -1,146 +0,0 @@ -/// Quasi-quotation macro that accepts input like the [`quote!`] macro but uses -/// type inference to figure out a return type for those tokens. -/// -/// [`quote!`]: https://docs.rs/quote/0.6/quote/index.html -/// -/// The return type can be any syntax tree node that implements the [`Parse`] -/// trait. -/// -/// [`Parse`]: parse::Parse -/// -/// ```edition2018 -/// use quote::quote; -/// use syn::{parse_quote, Stmt}; -/// -/// fn main() { -/// let name = quote!(v); -/// let ty = quote!(u8); -/// -/// let stmt: Stmt = parse_quote! { -/// let #name: #ty = Default::default(); -/// }; -/// -/// println!("{:#?}", stmt); -/// } -/// ``` -/// -/// *This macro is available if Syn is built with the `"parsing"` feature, -/// although interpolation of syntax tree nodes into the quoted tokens is only -/// supported if Syn is built with the `"printing"` feature as well.* -/// -/// # Example -/// -/// The following helper function adds a bound `T: HeapSize` to every type -/// parameter `T` in the input generics. -/// -/// ```edition2018 -/// use syn::{parse_quote, Generics, GenericParam}; -/// -/// // Add a bound `T: HeapSize` to every type parameter T. -/// fn add_trait_bounds(mut generics: Generics) -> Generics { -/// for param in &mut generics.params { -/// if let GenericParam::Type(type_param) = param { -/// type_param.bounds.push(parse_quote!(HeapSize)); -/// } -/// } -/// generics -/// } -/// ``` -/// -/// # Special cases -/// -/// This macro can parse the following additional types as a special case even -/// though they do not implement the `Parse` trait. -/// -/// - [`Attribute`] — parses one attribute, allowing either outer like `#[...]` -/// or inner like `#![...]` -/// - [`Punctuated<T, P>`] — parses zero or more `T` separated by punctuation -/// `P` with optional trailing punctuation -/// -/// [`Punctuated<T, P>`]: punctuated::Punctuated -/// -/// # Panics -/// -/// Panics if the tokens fail to parse as the expected syntax tree type. The -/// caller is responsible for ensuring that the input tokens are syntactically -/// valid. -// -// TODO: allow Punctuated to be inferred as intra doc link, currently blocked on -// https://github.com/rust-lang/rust/issues/62834 -#[macro_export(local_inner_macros)] -macro_rules! parse_quote { - ($($tt:tt)*) => { - $crate::parse_quote::parse($crate::export::From::from(quote_impl!($($tt)*))) - }; -} - -#[cfg(not(syn_can_call_macro_by_path))] -#[doc(hidden)] -#[macro_export] -macro_rules! quote_impl { - ($($tt:tt)*) => { - // Require caller to have their own `#[macro_use] extern crate quote`. - quote!($($tt)*) - }; -} - -#[cfg(syn_can_call_macro_by_path)] -#[doc(hidden)] -#[macro_export] -macro_rules! quote_impl { - ($($tt:tt)*) => { - $crate::export::quote::quote!($($tt)*) - }; -} - -//////////////////////////////////////////////////////////////////////////////// -// Can parse any type that implements Parse. - -use parse::{Parse, ParseStream, Parser, Result}; -use proc_macro2::TokenStream; - -// Not public API. -#[doc(hidden)] -pub fn parse<T: ParseQuote>(token_stream: TokenStream) -> T { - let parser = T::parse; - match parser.parse2(token_stream) { - Ok(t) => t, - Err(err) => panic!("{}", err), - } -} - -// Not public API. -#[doc(hidden)] -pub trait ParseQuote: Sized { - fn parse(input: ParseStream) -> Result<Self>; -} - -impl<T: Parse> ParseQuote for T { - fn parse(input: ParseStream) -> Result<Self> { - <T as Parse>::parse(input) - } -} - -//////////////////////////////////////////////////////////////////////////////// -// Any other types that we want `parse_quote!` to be able to parse. - -use punctuated::Punctuated; -#[cfg(any(feature = "full", feature = "derive"))] -use {attr, Attribute}; - -#[cfg(any(feature = "full", feature = "derive"))] -impl ParseQuote for Attribute { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Token![#]) && input.peek2(Token![!]) { - attr::parsing::single_parse_inner(input) - } else { - attr::parsing::single_parse_outer(input) - } - } -} - -impl<T: Parse, P: Parse> ParseQuote for Punctuated<T, P> { - fn parse(input: ParseStream) -> Result<Self> { - Self::parse_terminated(input) - } -} diff --git a/0.15.42/src/path.rs b/0.15.42/src/path.rs deleted file mode 100644 index 6e891b94..00000000 --- a/0.15.42/src/path.rs +++ /dev/null @@ -1,704 +0,0 @@ -use super::*; -use punctuated::Punctuated; - -ast_struct! { - /// A path at which a named item is exported: `std::collections::HashMap`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct Path { - pub leading_colon: Option<Token![::]>, - pub segments: Punctuated<PathSegment, Token![::]>, - } -} - -impl<T> From<T> for Path -where - T: Into<PathSegment>, -{ - fn from(segment: T) -> Self { - let mut path = Path { - leading_colon: None, - segments: Punctuated::new(), - }; - path.segments.push_value(segment.into()); - path - } -} - -ast_struct! { - /// A segment of a path together with any path arguments on that segment. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct PathSegment { - pub ident: Ident, - pub arguments: PathArguments, - } -} - -impl<T> From<T> for PathSegment -where - T: Into<Ident>, -{ - fn from(ident: T) -> Self { - PathSegment { - ident: ident.into(), - arguments: PathArguments::None, - } - } -} - -ast_enum! { - /// Angle bracketed or parenthesized arguments of a path segment. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// ## Angle bracketed - /// - /// The `<'a, T>` in `std::slice::iter<'a, T>`. - /// - /// ## Parenthesized - /// - /// The `(A, B) -> C` in `Fn(A, B) -> C`. - pub enum PathArguments { - None, - /// The `<'a, T>` in `std::slice::iter<'a, T>`. - AngleBracketed(AngleBracketedGenericArguments), - /// The `(A, B) -> C` in `Fn(A, B) -> C`. - Parenthesized(ParenthesizedGenericArguments), - } -} - -impl Default for PathArguments { - fn default() -> Self { - PathArguments::None - } -} - -impl PathArguments { - pub fn is_empty(&self) -> bool { - match *self { - PathArguments::None => true, - PathArguments::AngleBracketed(ref bracketed) => bracketed.args.is_empty(), - PathArguments::Parenthesized(_) => false, - } - } - - #[cfg(feature = "parsing")] - fn is_none(&self) -> bool { - match *self { - PathArguments::None => true, - PathArguments::AngleBracketed(_) | PathArguments::Parenthesized(_) => false, - } - } -} - -ast_enum! { - /// An individual generic argument, like `'a`, `T`, or `Item = T`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum GenericArgument { - /// A lifetime argument. - Lifetime(Lifetime), - /// A type argument. - Type(Type), - /// A binding (equality constraint) on an associated type: the `Item = - /// u8` in `Iterator<Item = u8>`. - Binding(Binding), - /// An associated type bound: `Iterator<Item: Display>`. - Constraint(Constraint), - /// A const expression. Must be inside of a block. - /// - /// NOTE: Identity expressions are represented as Type arguments, as - /// they are indistinguishable syntactically. - Const(Expr), - } -} - -ast_struct! { - /// Angle bracketed arguments of a path segment: the `<K, V>` in `HashMap<K, - /// V>`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct AngleBracketedGenericArguments { - pub colon2_token: Option<Token![::]>, - pub lt_token: Token![<], - pub args: Punctuated<GenericArgument, Token![,]>, - pub gt_token: Token![>], - } -} - -ast_struct! { - /// A binding (equality constraint) on an associated type: `Item = u8`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct Binding { - pub ident: Ident, - pub eq_token: Token![=], - pub ty: Type, - } -} - -ast_struct! { - /// An associated type bound: `Iterator<Item: Display>`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct Constraint { - pub ident: Ident, - pub colon_token: Token![:], - pub bounds: Punctuated<TypeParamBound, Token![+]>, - } -} - -ast_struct! { - /// Arguments of a function path segment: the `(A, B) -> C` in `Fn(A,B) -> - /// C`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct ParenthesizedGenericArguments { - pub paren_token: token::Paren, - /// `(A, B)` - pub inputs: Punctuated<Type, Token![,]>, - /// `C` - pub output: ReturnType, - } -} - -ast_struct! { - /// The explicit Self type in a qualified path: the `T` in `<T as - /// Display>::fmt`. - /// - /// The actual path, including the trait and the associated item, is stored - /// separately. The `position` field represents the index of the associated - /// item qualified with this Self type. - /// - /// ```text - /// <Vec<T> as a::b::Trait>::AssociatedItem - /// ^~~~~~ ~~~~~~~~~~~~~~^ - /// ty position = 3 - /// - /// <Vec<T>>::AssociatedItem - /// ^~~~~~ ^ - /// ty position = 0 - /// ``` - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct QSelf { - pub lt_token: Token![<], - pub ty: Box<Type>, - pub position: usize, - pub as_token: Option<Token![as]>, - pub gt_token: Token![>], - } -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - #[cfg(feature = "full")] - use expr; - use ext::IdentExt; - use parse::{Parse, ParseStream, Result}; - - impl Parse for Path { - fn parse(input: ParseStream) -> Result<Self> { - Self::parse_helper(input, false) - } - } - - impl Parse for GenericArgument { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Lifetime) && !input.peek2(Token![+]) { - return Ok(GenericArgument::Lifetime(input.parse()?)); - } - - if input.peek(Ident) && input.peek2(Token![=]) { - return Ok(GenericArgument::Binding(input.parse()?)); - } - - #[cfg(feature = "full")] - { - if input.peek(Ident) && input.peek2(Token![:]) && !input.peek2(Token![::]) { - return Ok(GenericArgument::Constraint(input.parse()?)); - } - - if input.peek(Lit) { - let lit = input.parse()?; - return Ok(GenericArgument::Const(Expr::Lit(lit))); - } - - if input.peek(token::Brace) { - let block = input.call(expr::parsing::expr_block)?; - return Ok(GenericArgument::Const(Expr::Block(block))); - } - } - - input.parse().map(GenericArgument::Type) - } - } - - impl Parse for AngleBracketedGenericArguments { - fn parse(input: ParseStream) -> Result<Self> { - Ok(AngleBracketedGenericArguments { - colon2_token: input.parse()?, - lt_token: input.parse()?, - args: { - let mut args = Punctuated::new(); - loop { - if input.peek(Token![>]) { - break; - } - let value = input.parse()?; - args.push_value(value); - if input.peek(Token![>]) { - break; - } - let punct = input.parse()?; - args.push_punct(punct); - } - args - }, - gt_token: input.parse()?, - }) - } - } - - impl Parse for ParenthesizedGenericArguments { - fn parse(input: ParseStream) -> Result<Self> { - let content; - Ok(ParenthesizedGenericArguments { - paren_token: parenthesized!(content in input), - inputs: content.parse_terminated(Type::parse)?, - output: input.call(ReturnType::without_plus)?, - }) - } - } - - impl Parse for PathSegment { - fn parse(input: ParseStream) -> Result<Self> { - Self::parse_helper(input, false) - } - } - - impl PathSegment { - fn parse_helper(input: ParseStream, expr_style: bool) -> Result<Self> { - if input.peek(Token![super]) - || input.peek(Token![self]) - || input.peek(Token![crate]) - || input.peek(Token![extern]) - { - let ident = input.call(Ident::parse_any)?; - return Ok(PathSegment::from(ident)); - } - - let ident = if input.peek(Token![Self]) { - input.call(Ident::parse_any)? - } else { - input.parse()? - }; - - if !expr_style && input.peek(Token![<]) && !input.peek(Token![<=]) - || input.peek(Token![::]) && input.peek3(Token![<]) - { - Ok(PathSegment { - ident: ident, - arguments: PathArguments::AngleBracketed(input.parse()?), - }) - } else { - Ok(PathSegment::from(ident)) - } - } - } - - impl Parse for Binding { - fn parse(input: ParseStream) -> Result<Self> { - Ok(Binding { - ident: input.parse()?, - eq_token: input.parse()?, - ty: input.parse()?, - }) - } - } - - #[cfg(feature = "full")] - impl Parse for Constraint { - fn parse(input: ParseStream) -> Result<Self> { - Ok(Constraint { - ident: input.parse()?, - colon_token: input.parse()?, - bounds: { - let mut bounds = Punctuated::new(); - loop { - if input.peek(Token![,]) || input.peek(Token![>]) { - break; - } - let value = input.parse()?; - bounds.push_value(value); - if !input.peek(Token![+]) { - break; - } - let punct = input.parse()?; - bounds.push_punct(punct); - } - bounds - }, - }) - } - } - - impl Path { - /// Parse a `Path` containing no path arguments on any of its segments. - /// - /// *This function is available if Syn is built with the `"parsing"` - /// feature.* - /// - /// # Example - /// - /// ```edition2018 - /// use syn::{Path, Result, Token}; - /// use syn::parse::{Parse, ParseStream}; - /// - /// // A simplified single `use` statement like: - /// // - /// // use std::collections::HashMap; - /// // - /// // Note that generic parameters are not allowed in a `use` statement - /// // so the following must not be accepted. - /// // - /// // use a::<b>::c; - /// struct SingleUse { - /// use_token: Token![use], - /// path: Path, - /// } - /// - /// impl Parse for SingleUse { - /// fn parse(input: ParseStream) -> Result<Self> { - /// Ok(SingleUse { - /// use_token: input.parse()?, - /// path: input.call(Path::parse_mod_style)?, - /// }) - /// } - /// } - /// ``` - pub fn parse_mod_style(input: ParseStream) -> Result<Self> { - Ok(Path { - leading_colon: input.parse()?, - segments: { - let mut segments = Punctuated::new(); - loop { - if !input.peek(Ident) - && !input.peek(Token![super]) - && !input.peek(Token![self]) - && !input.peek(Token![Self]) - && !input.peek(Token![crate]) - && !input.peek(Token![extern]) - { - break; - } - let ident = Ident::parse_any(input)?; - segments.push_value(PathSegment::from(ident)); - if !input.peek(Token![::]) { - break; - } - let punct = input.parse()?; - segments.push_punct(punct); - } - if segments.is_empty() { - return Err(input.error("expected path")); - } else if segments.trailing_punct() { - return Err(input.error("expected path segment")); - } - segments - }, - }) - } - - /// Determines whether this is a path of length 1 equal to the given - /// ident. - /// - /// For them to compare equal, it must be the case that: - /// - /// - the path has no leading colon, - /// - the number of path segments is 1, - /// - the first path segment has no angle bracketed or parenthesized - /// path arguments - /// - and the ident of the first path segment is equal to the given one. - /// - /// *This function is available if Syn is built with the `"parsing"` - /// feature.* - pub fn is_ident<I>(&self, ident: I) -> bool - where - Ident: PartialEq<I>, - { - self.leading_colon.is_none() - && self.segments.len() == 1 - && self.segments[0].arguments.is_none() - && self.segments[0].ident == ident - } - - fn parse_helper(input: ParseStream, expr_style: bool) -> Result<Self> { - Ok(Path { - leading_colon: input.parse()?, - segments: { - let mut segments = Punctuated::new(); - let value = PathSegment::parse_helper(input, expr_style)?; - segments.push_value(value); - while input.peek(Token![::]) { - let punct: Token![::] = input.parse()?; - segments.push_punct(punct); - let value = PathSegment::parse_helper(input, expr_style)?; - segments.push_value(value); - } - segments - }, - }) - } - } - - pub fn qpath(input: ParseStream, expr_style: bool) -> Result<(Option<QSelf>, Path)> { - if input.peek(Token![<]) { - let lt_token: Token![<] = input.parse()?; - let this: Type = input.parse()?; - let path = if input.peek(Token![as]) { - let as_token: Token![as] = input.parse()?; - let path: Path = input.parse()?; - Some((as_token, path)) - } else { - None - }; - let gt_token: Token![>] = input.parse()?; - let colon2_token: Token![::] = input.parse()?; - let mut rest = Punctuated::new(); - loop { - let path = PathSegment::parse_helper(input, expr_style)?; - rest.push_value(path); - if !input.peek(Token![::]) { - break; - } - let punct: Token![::] = input.parse()?; - rest.push_punct(punct); - } - let (position, as_token, path) = match path { - Some((as_token, mut path)) => { - let pos = path.segments.len(); - path.segments.push_punct(colon2_token); - path.segments.extend(rest.into_pairs()); - (pos, Some(as_token), path) - } - None => { - let path = Path { - leading_colon: Some(colon2_token), - segments: rest, - }; - (0, None, path) - } - }; - let qself = QSelf { - lt_token: lt_token, - ty: Box::new(this), - position: position, - as_token: as_token, - gt_token: gt_token, - }; - Ok((Some(qself), path)) - } else { - let path = Path::parse_helper(input, expr_style)?; - Ok((None, path)) - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - - use proc_macro2::TokenStream; - use quote::ToTokens; - - use print::TokensOrDefault; - - impl ToTokens for Path { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.leading_colon.to_tokens(tokens); - self.segments.to_tokens(tokens); - } - } - - impl ToTokens for PathSegment { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.ident.to_tokens(tokens); - self.arguments.to_tokens(tokens); - } - } - - impl ToTokens for PathArguments { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - PathArguments::None => {} - PathArguments::AngleBracketed(ref arguments) => { - arguments.to_tokens(tokens); - } - PathArguments::Parenthesized(ref arguments) => { - arguments.to_tokens(tokens); - } - } - } - } - - impl ToTokens for GenericArgument { - #[cfg_attr(feature = "cargo-clippy", allow(match_same_arms))] - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - GenericArgument::Lifetime(ref lt) => lt.to_tokens(tokens), - GenericArgument::Type(ref ty) => ty.to_tokens(tokens), - GenericArgument::Binding(ref tb) => tb.to_tokens(tokens), - GenericArgument::Constraint(ref tc) => tc.to_tokens(tokens), - GenericArgument::Const(ref e) => match *e { - Expr::Lit(_) => e.to_tokens(tokens), - - // NOTE: We should probably support parsing blocks with only - // expressions in them without the full feature for const - // generics. - #[cfg(feature = "full")] - Expr::Block(_) => e.to_tokens(tokens), - - // ERROR CORRECTION: Add braces to make sure that the - // generated code is valid. - _ => token::Brace::default().surround(tokens, |tokens| { - e.to_tokens(tokens); - }), - }, - } - } - } - - 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 and consts, all before bindings, - // regardless of their order in self.args. - // - // TODO: ordering rules for const arguments vs type arguments have - // not been settled yet. https://github.com/rust-lang/rust/issues/44580 - 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::Binding(_) - | GenericArgument::Constraint(_) - | GenericArgument::Const(_) => {} - } - } - for param in self.args.pairs() { - match **param.value() { - GenericArgument::Type(_) | GenericArgument::Const(_) => { - if !trailing_or_empty { - <Token![,]>::default().to_tokens(tokens); - } - param.to_tokens(tokens); - trailing_or_empty = param.punct().is_some(); - } - GenericArgument::Lifetime(_) - | GenericArgument::Binding(_) - | GenericArgument::Constraint(_) => {} - } - } - for param in self.args.pairs() { - match **param.value() { - GenericArgument::Binding(_) | GenericArgument::Constraint(_) => { - if !trailing_or_empty { - <Token![,]>::default().to_tokens(tokens); - trailing_or_empty = true; - } - param.to_tokens(tokens); - } - GenericArgument::Lifetime(_) - | GenericArgument::Type(_) - | GenericArgument::Const(_) => {} - } - } - - self.gt_token.to_tokens(tokens); - } - } - - impl ToTokens for Binding { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.ident.to_tokens(tokens); - self.eq_token.to_tokens(tokens); - self.ty.to_tokens(tokens); - } - } - - impl ToTokens for Constraint { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.ident.to_tokens(tokens); - self.colon_token.to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - } - - 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); - } - } - - impl private { - pub fn print_path(tokens: &mut TokenStream, qself: &Option<QSelf>, path: &Path) { - let qself = match *qself { - Some(ref qself) => qself, - None => { - path.to_tokens(tokens); - return; - } - }; - qself.lt_token.to_tokens(tokens); - qself.ty.to_tokens(tokens); - - let pos = if qself.position > 0 && qself.position >= path.segments.len() { - path.segments.len() - 1 - } else { - qself.position - }; - let mut segments = path.segments.pairs(); - if pos > 0 { - TokensOrDefault(&qself.as_token).to_tokens(tokens); - path.leading_colon.to_tokens(tokens); - for (i, segment) in segments.by_ref().take(pos).enumerate() { - 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); - } - } - } else { - qself.gt_token.to_tokens(tokens); - path.leading_colon.to_tokens(tokens); - } - for segment in segments { - segment.to_tokens(tokens); - } - } - } -} diff --git a/0.15.42/src/print.rs b/0.15.42/src/print.rs deleted file mode 100644 index 90570a04..00000000 --- a/0.15.42/src/print.rs +++ /dev/null @@ -1,16 +0,0 @@ -use proc_macro2::TokenStream; -use quote::ToTokens; - -pub struct TokensOrDefault<'a, T: 'a>(pub &'a Option<T>); - -impl<'a, T> ToTokens for TokensOrDefault<'a, T> -where - T: ToTokens + Default, -{ - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self.0 { - Some(ref t) => t.to_tokens(tokens), - None => T::default().to_tokens(tokens), - } - } -} diff --git a/0.15.42/src/punctuated.rs b/0.15.42/src/punctuated.rs deleted file mode 100644 index 50f22af5..00000000 --- a/0.15.42/src/punctuated.rs +++ /dev/null @@ -1,836 +0,0 @@ -//! A punctuated sequence of syntax tree nodes separated by punctuation. -//! -//! Lots of things in Rust are punctuated sequences. -//! -//! - The fields of a struct are `Punctuated<Field, Token![,]>`. -//! - The segments of a path are `Punctuated<PathSegment, Token![::]>`. -//! - The bounds on a generic parameter are `Punctuated<TypeParamBound, -//! Token![+]>`. -//! - The arguments to a function call are `Punctuated<Expr, Token![,]>`. -//! -//! This module provides a common representation for these punctuated sequences -//! in the form of the [`Punctuated<T, P>`] type. We store a vector of pairs of -//! syntax tree node + punctuation, where every node in the sequence is followed -//! by punctuation except for possibly the final one. -//! -//! [`Punctuated<T, P>`]: struct.Punctuated.html -//! -//! ```text -//! a_function_call(arg1, arg2, arg3); -//! ^^^^^ ~~~~~ ^^^^ -//! ``` - -#[cfg(feature = "extra-traits")] -use std::fmt::{self, Debug}; -#[cfg(any(feature = "full", feature = "derive"))] -use std::iter; -use std::iter::FromIterator; -use std::marker::PhantomData; -use std::ops::{Index, IndexMut}; -use std::option; -use std::slice; -use std::vec; - -#[cfg(feature = "parsing")] -use parse::{Parse, ParseStream, Result}; -#[cfg(any(feature = "full", feature = "derive"))] -use private; -#[cfg(feature = "parsing")] -use token::Token; - -/// A punctuated sequence of syntax tree nodes of type `T` separated by -/// punctuation of type `P`. -/// -/// Refer to the [module documentation] for details about punctuated sequences. -/// -/// [module documentation]: self -#[cfg_attr(feature = "extra-traits", derive(Eq, PartialEq, Hash))] -#[cfg_attr(feature = "clone-impls", derive(Clone))] -pub struct Punctuated<T, P> { - inner: Vec<(T, P)>, - last: Option<Box<T>>, -} - -impl<T, P> Punctuated<T, P> { - /// Creates an empty punctuated sequence. - pub fn new() -> Punctuated<T, P> { - Punctuated { - inner: Vec::new(), - last: None, - } - } - - /// Determines whether this punctuated sequence is empty, meaning it - /// contains no syntax tree nodes or punctuation. - pub fn is_empty(&self) -> bool { - self.inner.len() == 0 && self.last.is_none() - } - - /// Returns the number of syntax tree nodes in this punctuated sequence. - /// - /// This is the number of nodes of type `T`, not counting the punctuation of - /// type `P`. - pub fn len(&self) -> usize { - self.inner.len() + if self.last.is_some() { 1 } else { 0 } - } - - /// Borrows the first punctuated pair in this sequence. - pub fn first(&self) -> Option<Pair<&T, &P>> { - self.pairs().next() - } - - /// Borrows the last punctuated pair in this sequence. - pub fn last(&self) -> Option<Pair<&T, &P>> { - if self.last.is_some() { - self.last.as_ref().map(|t| Pair::End(t.as_ref())) - } else { - self.inner - .last() - .map(|&(ref t, ref d)| Pair::Punctuated(t, d)) - } - } - - /// Mutably borrows the last punctuated pair in this sequence. - pub fn last_mut(&mut self) -> Option<Pair<&mut T, &mut P>> { - if self.last.is_some() { - self.last.as_mut().map(|t| Pair::End(t.as_mut())) - } else { - self.inner - .last_mut() - .map(|&mut (ref mut t, ref mut d)| Pair::Punctuated(t, d)) - } - } - - /// Returns an iterator over borrowed syntax tree nodes of type `&T`. - pub fn iter(&self) -> Iter<T> { - Iter { - inner: Box::new(PrivateIter { - inner: self.inner.iter(), - last: self.last.as_ref().map(Box::as_ref).into_iter(), - }), - } - } - - /// Returns an iterator over mutably borrowed syntax tree nodes of type - /// `&mut T`. - pub fn iter_mut(&mut self) -> IterMut<T> { - IterMut { - inner: Box::new(PrivateIterMut { - inner: self.inner.iter_mut(), - last: self.last.as_mut().map(Box::as_mut).into_iter(), - }), - } - } - - /// Returns an iterator over the contents of this sequence as borrowed - /// punctuated pairs. - pub fn pairs(&self) -> Pairs<T, P> { - Pairs { - inner: self.inner.iter(), - last: self.last.as_ref().map(Box::as_ref).into_iter(), - } - } - - /// Returns an iterator over the contents of this sequence as mutably - /// borrowed punctuated pairs. - pub fn pairs_mut(&mut self) -> PairsMut<T, P> { - PairsMut { - inner: self.inner.iter_mut(), - last: self.last.as_mut().map(Box::as_mut).into_iter(), - } - } - - /// Returns an iterator over the contents of this sequence as owned - /// punctuated pairs. - pub fn into_pairs(self) -> IntoPairs<T, P> { - IntoPairs { - inner: self.inner.into_iter(), - last: self.last.map(|t| *t).into_iter(), - } - } - - /// Appends a syntax tree node onto the end of this punctuated sequence. The - /// sequence must previously have a trailing punctuation. - /// - /// Use [`push`] instead if the punctuated sequence may or may not already - /// have trailing punctuation. - /// - /// [`push`]: Punctuated::push - /// - /// # Panics - /// - /// Panics if the sequence does not already have a trailing punctuation when - /// this method is called. - pub fn push_value(&mut self, value: T) { - assert!(self.empty_or_trailing()); - self.last = Some(Box::new(value)); - } - - /// Appends a trailing punctuation onto the end of this punctuated sequence. - /// The sequence must be non-empty and must not already have trailing - /// punctuation. - /// - /// # Panics - /// - /// Panics if the sequence is empty or already has a trailing punctuation. - pub fn push_punct(&mut self, punctuation: P) { - assert!(self.last.is_some()); - let last = self.last.take().unwrap(); - self.inner.push((*last, punctuation)); - } - - /// Removes the last punctuated pair from this sequence, or `None` if the - /// sequence is empty. - pub fn pop(&mut self) -> Option<Pair<T, P>> { - if self.last.is_some() { - self.last.take().map(|t| Pair::End(*t)) - } else { - self.inner.pop().map(|(t, d)| Pair::Punctuated(t, d)) - } - } - - /// Determines whether this punctuated sequence ends with a trailing - /// punctuation. - pub fn trailing_punct(&self) -> bool { - self.last.is_none() && !self.is_empty() - } - - /// Returns true if either this `Punctuated` is empty, or it has a trailing - /// punctuation. - /// - /// Equivalent to `punctuated.is_empty() || punctuated.trailing_punct()`. - pub fn empty_or_trailing(&self) -> bool { - self.last.is_none() - } - - /// Appends a syntax tree node onto the end of this punctuated sequence. - /// - /// If there is not a trailing punctuation in this sequence when this method - /// is called, the default value of punctuation type `P` is inserted before - /// the given value of type `T`. - pub fn push(&mut self, value: T) - where - P: Default, - { - if !self.empty_or_trailing() { - self.push_punct(Default::default()); - } - self.push_value(value); - } - - /// Inserts an element at position `index`. - /// - /// # Panics - /// - /// Panics if `index` is greater than the number of elements previously in - /// this punctuated sequence. - pub fn insert(&mut self, index: usize, value: T) - where - P: Default, - { - assert!(index <= self.len()); - - if index == self.len() { - self.push(value); - } else { - self.inner.insert(index, (value, Default::default())); - } - } - - /// Parses zero or more occurrences of `T` separated by punctuation of type - /// `P`, with optional trailing punctuation. - /// - /// Parsing continues until the end of this parse stream. The entire content - /// of this parse stream must consist of `T` and `P`. - /// - /// *This function is available if Syn is built with the `"parsing"` - /// feature.* - #[cfg(feature = "parsing")] - pub fn parse_terminated(input: ParseStream) -> Result<Self> - where - T: Parse, - P: Parse, - { - Self::parse_terminated_with(input, T::parse) - } - - /// Parses zero or more occurrences of `T` using the given parse function, - /// separated by punctuation of type `P`, with optional trailing - /// punctuation. - /// - /// Like [`parse_terminated`], the entire content of this stream is expected - /// to be parsed. - /// - /// [`parse_terminated`]: Punctuated::parse_terminated - /// - /// *This function is available if Syn is built with the `"parsing"` - /// feature.* - #[cfg(feature = "parsing")] - pub fn parse_terminated_with( - input: ParseStream, - parser: fn(ParseStream) -> Result<T>, - ) -> Result<Self> - where - P: Parse, - { - let mut punctuated = Punctuated::new(); - - loop { - if input.is_empty() { - break; - } - let value = parser(input)?; - punctuated.push_value(value); - if input.is_empty() { - break; - } - let punct = input.parse()?; - punctuated.push_punct(punct); - } - - Ok(punctuated) - } - - /// Parses one or more occurrences of `T` separated by punctuation of type - /// `P`, not accepting trailing punctuation. - /// - /// Parsing continues as long as punctuation `P` is present at the head of - /// the stream. This method returns upon parsing a `T` and observing that it - /// is not followed by a `P`, even if there are remaining tokens in the - /// stream. - /// - /// *This function is available if Syn is built with the `"parsing"` - /// feature.* - #[cfg(feature = "parsing")] - pub fn parse_separated_nonempty(input: ParseStream) -> Result<Self> - where - T: Parse, - P: Token + Parse, - { - Self::parse_separated_nonempty_with(input, T::parse) - } - - /// Parses one or more occurrences of `T` using the given parse function, - /// separated by punctuation of type `P`, not accepting trailing - /// punctuation. - /// - /// Like [`parse_separated_nonempty`], may complete early without parsing - /// the entire content of this stream. - /// - /// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty - /// - /// *This function is available if Syn is built with the `"parsing"` - /// feature.* - #[cfg(feature = "parsing")] - pub fn parse_separated_nonempty_with( - input: ParseStream, - parser: fn(ParseStream) -> Result<T>, - ) -> Result<Self> - where - P: Token + Parse, - { - let mut punctuated = Punctuated::new(); - - loop { - let value = parser(input)?; - punctuated.push_value(value); - if !P::peek(input.cursor()) { - break; - } - let punct = input.parse()?; - punctuated.push_punct(punct); - } - - Ok(punctuated) - } -} - -#[cfg(feature = "extra-traits")] -impl<T: Debug, P: Debug> Debug for Punctuated<T, P> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut list = f.debug_list(); - for &(ref t, ref p) in &self.inner { - list.entry(t); - list.entry(p); - } - if let Some(ref last) = self.last { - list.entry(last); - } - list.finish() - } -} - -impl<T, P> FromIterator<T> for Punctuated<T, P> -where - P: Default, -{ - fn from_iter<I: IntoIterator<Item = T>>(i: I) -> Self { - let mut ret = Punctuated::new(); - ret.extend(i); - ret - } -} - -impl<T, P> Extend<T> for Punctuated<T, P> -where - P: Default, -{ - fn extend<I: IntoIterator<Item = T>>(&mut self, i: I) { - for value in i { - self.push(value); - } - } -} - -impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P> { - fn from_iter<I: IntoIterator<Item = Pair<T, P>>>(i: I) -> Self { - let mut ret = Punctuated::new(); - ret.extend(i); - ret - } -} - -impl<T, P> Extend<Pair<T, P>> for Punctuated<T, P> { - fn extend<I: IntoIterator<Item = Pair<T, P>>>(&mut self, i: I) { - assert!(self.empty_or_trailing()); - let mut nomore = false; - for pair in i { - if nomore { - panic!("Punctuated extended with items after a Pair::End"); - } - match pair { - Pair::Punctuated(a, b) => self.inner.push((a, b)), - Pair::End(a) => { - self.last = Some(Box::new(a)); - nomore = true; - } - } - } - } -} - -impl<T, P> IntoIterator for Punctuated<T, P> { - type Item = T; - type IntoIter = IntoIter<T, P>; - - fn into_iter(self) -> Self::IntoIter { - let mut elements = Vec::with_capacity(self.len()); - elements.extend(self.inner.into_iter().map(|pair| pair.0)); - elements.extend(self.last.map(|t| *t)); - - IntoIter { - inner: elements.into_iter(), - marker: PhantomData, - } - } -} - -impl<'a, T, P> IntoIterator for &'a Punctuated<T, P> { - type Item = &'a T; - type IntoIter = Iter<'a, T>; - - fn into_iter(self) -> Self::IntoIter { - Punctuated::iter(self) - } -} - -impl<'a, T, P> IntoIterator for &'a mut Punctuated<T, P> { - type Item = &'a mut T; - type IntoIter = IterMut<'a, T>; - - fn into_iter(self) -> Self::IntoIter { - Punctuated::iter_mut(self) - } -} - -impl<T, P> Default for Punctuated<T, P> { - fn default() -> Self { - Punctuated::new() - } -} - -/// An iterator over borrowed pairs of type `Pair<&T, &P>`. -/// -/// Refer to the [module documentation] for details about punctuated sequences. -/// -/// [module documentation]: self -pub struct Pairs<'a, T: 'a, P: 'a> { - inner: slice::Iter<'a, (T, P)>, - last: option::IntoIter<&'a T>, -} - -impl<'a, T, P> Iterator for Pairs<'a, T, P> { - type Item = Pair<&'a T, &'a P>; - - fn next(&mut self) -> Option<Self::Item> { - self.inner - .next() - .map(|&(ref t, ref p)| Pair::Punctuated(t, p)) - .or_else(|| self.last.next().map(Pair::End)) - } -} - -impl<'a, T, P> ExactSizeIterator for Pairs<'a, T, P> { - fn len(&self) -> usize { - self.inner.len() + self.last.len() - } -} - -// No Clone bound on T or P. -impl<'a, T, P> Clone for Pairs<'a, T, P> { - fn clone(&self) -> Self { - Pairs { - inner: self.inner.clone(), - last: self.last.clone(), - } - } -} - -/// An iterator over mutably borrowed pairs of type `Pair<&mut T, &mut P>`. -/// -/// Refer to the [module documentation] for details about punctuated sequences. -/// -/// [module documentation]: self -pub struct PairsMut<'a, T: 'a, P: 'a> { - inner: slice::IterMut<'a, (T, P)>, - last: option::IntoIter<&'a mut T>, -} - -impl<'a, T, P> Iterator for PairsMut<'a, T, P> { - type Item = Pair<&'a mut T, &'a mut P>; - - fn next(&mut self) -> Option<Self::Item> { - self.inner - .next() - .map(|&mut (ref mut t, ref mut p)| Pair::Punctuated(t, p)) - .or_else(|| self.last.next().map(Pair::End)) - } -} - -impl<'a, T, P> ExactSizeIterator for PairsMut<'a, T, P> { - fn len(&self) -> usize { - self.inner.len() + self.last.len() - } -} - -/// An iterator over owned pairs of type `Pair<T, P>`. -/// -/// Refer to the [module documentation] for details about punctuated sequences. -/// -/// [module documentation]: self -#[derive(Clone)] -pub struct IntoPairs<T, P> { - inner: vec::IntoIter<(T, P)>, - last: option::IntoIter<T>, -} - -impl<T, P> Iterator for IntoPairs<T, P> { - type Item = Pair<T, P>; - - fn next(&mut self) -> Option<Self::Item> { - self.inner - .next() - .map(|(t, p)| Pair::Punctuated(t, p)) - .or_else(|| self.last.next().map(Pair::End)) - } -} - -impl<T, P> ExactSizeIterator for IntoPairs<T, P> { - fn len(&self) -> usize { - self.inner.len() + self.last.len() - } -} - -/// An iterator over owned values of type `T`. -/// -/// Refer to the [module documentation] for details about punctuated sequences. -/// -/// [module documentation]: self -#[derive(Clone)] -pub struct IntoIter<T, P> { - inner: vec::IntoIter<T>, - - // TODO: remove P type parameter in the next breaking change - marker: PhantomData<P>, -} - -impl<T, P> Iterator for IntoIter<T, P> { - type Item = T; - - fn next(&mut self) -> Option<Self::Item> { - self.inner.next() - } -} - -impl<T, P> ExactSizeIterator for IntoIter<T, P> { - fn len(&self) -> usize { - self.inner.len() - } -} - -/// An iterator over borrowed values of type `&T`. -/// -/// Refer to the [module documentation] for details about punctuated sequences. -/// -/// [module documentation]: self -pub struct Iter<'a, T: 'a> { - // The `Item = &'a T` needs to be specified to support rustc 1.31 and older. - // On modern compilers we would be able to write just IterTrait<'a, T> where - // Item can be inferred unambiguously from the supertrait. - inner: Box<IterTrait<'a, T, Item = &'a T> + 'a>, -} - -trait IterTrait<'a, T: 'a>: ExactSizeIterator<Item = &'a T> { - fn clone_box(&self) -> Box<IterTrait<'a, T, Item = &'a T> + 'a>; -} - -struct PrivateIter<'a, T: 'a, P: 'a> { - inner: slice::Iter<'a, (T, P)>, - last: option::IntoIter<&'a T>, -} - -#[cfg(any(feature = "full", feature = "derive"))] -impl private { - pub fn empty_punctuated_iter<'a, T>() -> Iter<'a, T> { - Iter { - inner: Box::new(iter::empty()), - } - } -} - -// No Clone bound on T. -impl<'a, T> Clone for Iter<'a, T> { - fn clone(&self) -> Self { - Iter { - inner: self.inner.clone_box(), - } - } -} - -impl<'a, T> Iterator for Iter<'a, T> { - type Item = &'a T; - - fn next(&mut self) -> Option<Self::Item> { - self.inner.next() - } -} - -impl<'a, T> ExactSizeIterator for Iter<'a, T> { - fn len(&self) -> usize { - self.inner.len() - } -} - -impl<'a, T, P> Iterator for PrivateIter<'a, T, P> { - type Item = &'a T; - - fn next(&mut self) -> Option<Self::Item> { - self.inner - .next() - .map(|pair| &pair.0) - .or_else(|| self.last.next()) - } -} - -impl<'a, T, P> ExactSizeIterator for PrivateIter<'a, T, P> { - fn len(&self) -> usize { - self.inner.len() + self.last.len() - } -} - -// No Clone bound on T or P. -impl<'a, T, P> Clone for PrivateIter<'a, T, P> { - fn clone(&self) -> Self { - PrivateIter { - inner: self.inner.clone(), - last: self.last.clone(), - } - } -} - -impl<'a, T: 'a, I: 'a> IterTrait<'a, T> for I -where - I: ExactSizeIterator<Item = &'a T> + Clone, -{ - fn clone_box(&self) -> Box<IterTrait<'a, T, Item = &'a T> + 'a> { - Box::new(self.clone()) - } -} - -/// An iterator over mutably borrowed values of type `&mut T`. -/// -/// Refer to the [module documentation] for details about punctuated sequences. -/// -/// [module documentation]: self -pub struct IterMut<'a, T: 'a> { - inner: Box<ExactSizeIterator<Item = &'a mut T> + 'a>, -} - -struct PrivateIterMut<'a, T: 'a, P: 'a> { - inner: slice::IterMut<'a, (T, P)>, - last: option::IntoIter<&'a mut T>, -} - -#[cfg(any(feature = "full", feature = "derive"))] -impl private { - pub fn empty_punctuated_iter_mut<'a, T>() -> IterMut<'a, T> { - IterMut { - inner: Box::new(iter::empty()), - } - } -} - -impl<'a, T> Iterator for IterMut<'a, T> { - type Item = &'a mut T; - - fn next(&mut self) -> Option<Self::Item> { - self.inner.next() - } -} - -impl<'a, T> ExactSizeIterator for IterMut<'a, T> { - fn len(&self) -> usize { - self.inner.len() - } -} - -impl<'a, T, P> Iterator for PrivateIterMut<'a, T, P> { - type Item = &'a mut T; - - fn next(&mut self) -> Option<Self::Item> { - self.inner - .next() - .map(|pair| &mut pair.0) - .or_else(|| self.last.next()) - } -} - -impl<'a, T, P> ExactSizeIterator for PrivateIterMut<'a, T, P> { - fn len(&self) -> usize { - self.inner.len() + self.last.len() - } -} - -/// A single syntax tree node of type `T` followed by its trailing punctuation -/// of type `P` if any. -/// -/// Refer to the [module documentation] for details about punctuated sequences. -/// -/// [module documentation]: self -#[cfg_attr(feature = "clone-impls", derive(Clone))] -pub enum Pair<T, P> { - Punctuated(T, P), - End(T), -} - -impl<T, P> Pair<T, P> { - /// Extracts the syntax tree node from this punctuated pair, discarding the - /// following punctuation. - pub fn into_value(self) -> T { - match self { - Pair::Punctuated(t, _) | Pair::End(t) => t, - } - } - - /// Borrows the syntax tree node from this punctuated pair. - pub fn value(&self) -> &T { - match *self { - Pair::Punctuated(ref t, _) | Pair::End(ref t) => t, - } - } - - /// Mutably borrows the syntax tree node from this punctuated pair. - pub fn value_mut(&mut self) -> &mut T { - match *self { - Pair::Punctuated(ref mut t, _) | Pair::End(ref mut t) => t, - } - } - - /// Borrows the punctuation from this punctuated pair, unless this pair is - /// the final one and there is no trailing punctuation. - pub fn punct(&self) -> Option<&P> { - match *self { - Pair::Punctuated(_, ref d) => Some(d), - Pair::End(_) => None, - } - } - - /// Creates a punctuated pair out of a syntax tree node and an optional - /// following punctuation. - pub fn new(t: T, d: Option<P>) -> Self { - match d { - Some(d) => Pair::Punctuated(t, d), - None => Pair::End(t), - } - } - - /// Produces this punctuated pair as a tuple of syntax tree node and - /// optional following punctuation. - pub fn into_tuple(self) -> (T, Option<P>) { - match self { - Pair::Punctuated(t, d) => (t, Some(d)), - Pair::End(t) => (t, None), - } - } -} - -impl<T, P> Index<usize> for Punctuated<T, P> { - type Output = T; - - fn index(&self, index: usize) -> &Self::Output { - if index == self.len() - 1 { - match self.last { - Some(ref t) => t, - None => &self.inner[index].0, - } - } else { - &self.inner[index].0 - } - } -} - -impl<T, P> IndexMut<usize> for Punctuated<T, P> { - fn index_mut(&mut self, index: usize) -> &mut Self::Output { - if index == self.len() - 1 { - match self.last { - Some(ref mut t) => t, - None => &mut self.inner[index].0, - } - } else { - &mut self.inner[index].0 - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - use proc_macro2::TokenStream; - use quote::{ToTokens, TokenStreamExt}; - - impl<T, P> ToTokens for Punctuated<T, P> - where - T: ToTokens, - P: ToTokens, - { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append_all(self.pairs()) - } - } - - impl<T, P> ToTokens for Pair<T, P> - where - T: ToTokens, - P: ToTokens, - { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - Pair::Punctuated(ref a, ref b) => { - a.to_tokens(tokens); - b.to_tokens(tokens); - } - Pair::End(ref a) => a.to_tokens(tokens), - } - } - } -} diff --git a/0.15.42/src/spanned.rs b/0.15.42/src/spanned.rs deleted file mode 100644 index e0dd834b..00000000 --- a/0.15.42/src/spanned.rs +++ /dev/null @@ -1,144 +0,0 @@ -//! A trait that can provide the `Span` of the complete contents of a syntax -//! tree node. -//! -//! *This module is available if Syn is built with both the `"parsing"` and -//! `"printing"` features.* -//! -//! # Example -//! -//! Suppose in a procedural macro we have a [`Type`] that we want to assert -//! implements the [`Sync`] trait. Maybe this is the type of one of the fields -//! of a struct for which we are deriving a trait implementation, and we need to -//! be able to pass a reference to one of those fields across threads. -//! -//! [`Type`]: ../enum.Type.html -//! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html -//! -//! If the field type does *not* implement `Sync` as required, we want the -//! compiler to report an error pointing out exactly which type it was. -//! -//! The following macro code takes a variable `ty` of type `Type` and produces a -//! static assertion that `Sync` is implemented for that type. -//! -//! ```edition2018 -//! # extern crate proc_macro; -//! # -//! use proc_macro::TokenStream; -//! use proc_macro2::Span; -//! use quote::quote_spanned; -//! use syn::Type; -//! use syn::spanned::Spanned; -//! -//! # const IGNORE_TOKENS: &str = stringify! { -//! #[proc_macro_derive(MyMacro)] -//! # }; -//! pub fn my_macro(input: TokenStream) -> TokenStream { -//! # let ty = get_a_type(); -//! /* ... */ -//! -//! let assert_sync = quote_spanned! {ty.span()=> -//! struct _AssertSync where #ty: Sync; -//! }; -//! -//! /* ... */ -//! # input -//! } -//! # -//! # fn get_a_type() -> Type { -//! # unimplemented!() -//! # } -//! ``` -//! -//! By inserting this `assert_sync` fragment into the output code generated by -//! our macro, the user's code will fail to compile if `ty` does not implement -//! `Sync`. The errors they would see look like the following. -//! -//! ```text -//! error[E0277]: the trait bound `*const i32: std::marker::Sync` is not satisfied -//! --> src/main.rs:10:21 -//! | -//! 10 | bad_field: *const i32, -//! | ^^^^^^^^^^ `*const i32` cannot be shared between threads safely -//! ``` -//! -//! In this technique, using the `Type`'s span for the error message makes the -//! error appear in the correct place underlining the right type. - -use proc_macro2::{Span, TokenStream}; -use quote::ToTokens; - -/// A trait that can provide the `Span` of the complete contents of a syntax -/// tree node. -/// -/// This trait is automatically implemented for all types that implement -/// [`ToTokens`] from the `quote` crate. It is sealed and cannot be implemented -/// outside of the Syn crate other than by implementing `ToTokens`. -/// -/// [`ToTokens`]: quote::ToTokens -/// -/// See the [module documentation] for an example. -/// -/// [module documentation]: self -/// -/// *This trait is available if Syn is built with both the `"parsing"` and -/// `"printing"` features.* -pub trait Spanned: private::Sealed { - /// Returns a `Span` covering the complete contents of this syntax tree - /// node, or [`Span::call_site()`] if this node is empty. - /// - /// [`Span::call_site()`]: proc_macro2::Span::call_site - fn span(&self) -> Span; -} - -mod private { - use quote::ToTokens; - pub trait Sealed {} - impl<T: ToTokens> Sealed for T {} -} - -impl<T> Spanned for T -where - T: ToTokens, -{ - fn span(&self) -> Span { - join_spans(self.into_token_stream()) - } -} - -fn join_spans(tokens: TokenStream) -> Span { - let mut iter = tokens.into_iter().filter_map(|tt| { - // FIXME: This shouldn't be required, since optimally spans should - // never be invalid. This filter_map can probably be removed when - // https://github.com/rust-lang/rust/issues/43081 is resolved. - let span = tt.span(); - let debug = format!("{:?}", span); - if debug.ends_with("bytes(0..0)") { - None - } else { - Some(span) - } - }); - - let mut joined = match iter.next() { - Some(span) => span, - None => return Span::call_site(), - }; - - #[cfg(procmacro2_semver_exempt)] - { - for next in iter { - if let Some(span) = joined.join(next) { - joined = span; - } - } - } - - #[cfg(not(procmacro2_semver_exempt))] - { - // We can't join spans without procmacro2_semver_exempt so just grab the - // first one. - joined = joined; - } - - joined -} diff --git a/0.15.42/src/thread.rs b/0.15.42/src/thread.rs deleted file mode 100644 index ff47e4af..00000000 --- a/0.15.42/src/thread.rs +++ /dev/null @@ -1,83 +0,0 @@ -use std::fmt::{self, Debug}; - -use self::thread_id::ThreadId; - -/// ThreadBound is a Sync-maker and Send-maker that allows accessing a value -/// of type T only from the original thread on which the ThreadBound was -/// constructed. -pub struct ThreadBound<T> { - value: T, - thread_id: ThreadId, -} - -unsafe impl<T> Sync for ThreadBound<T> {} - -// Send bound requires Copy, as otherwise Drop could run in the wrong place. -unsafe impl<T: Copy> Send for ThreadBound<T> {} - -impl<T> ThreadBound<T> { - pub fn new(value: T) -> Self { - ThreadBound { - value: value, - thread_id: thread_id::current(), - } - } - - pub fn get(&self) -> Option<&T> { - if thread_id::current() == self.thread_id { - Some(&self.value) - } else { - None - } - } -} - -impl<T: Debug> Debug for ThreadBound<T> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match self.get() { - Some(value) => Debug::fmt(value, formatter), - None => formatter.write_str("unknown"), - } - } -} - -#[cfg(syn_can_use_thread_id)] -mod thread_id { - use std::thread; - - pub use std::thread::ThreadId; - - pub fn current() -> ThreadId { - thread::current().id() - } -} - -#[cfg(not(syn_can_use_thread_id))] -mod thread_id { - #[allow(deprecated)] - use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; - - thread_local! { - static THREAD_ID: usize = { - #[allow(deprecated)] - static NEXT_THREAD_ID: AtomicUsize = ATOMIC_USIZE_INIT; - - // Ordering::Relaxed because our only requirement for the ids is - // that they are unique. It is okay for the compiler to rearrange - // other memory reads around this fetch. It's still an atomic - // fetch_add, so no two threads will be able to read the same value - // from it. - // - // The main thing which these orderings affect is other memory reads - // around the atomic read, which for our case are irrelevant as this - // atomic guards nothing. - NEXT_THREAD_ID.fetch_add(1, Ordering::Relaxed) - }; - } - - pub type ThreadId = usize; - - pub fn current() -> ThreadId { - THREAD_ID.with(|id| *id) - } -} diff --git a/0.15.42/src/token.rs b/0.15.42/src/token.rs deleted file mode 100644 index e1d1c8d3..00000000 --- a/0.15.42/src/token.rs +++ /dev/null @@ -1,961 +0,0 @@ -//! Tokens representing Rust punctuation, keywords, and delimiters. -//! -//! The type names in this module can be difficult to keep straight, so we -//! prefer to use the [`Token!`] macro instead. This is a type-macro that -//! expands to the token type of the given token. -//! -//! [`Token!`]: ../macro.Token.html -//! -//! # Example -//! -//! The [`ItemStatic`] syntax tree node is defined like this. -//! -//! [`ItemStatic`]: ../struct.ItemStatic.html -//! -//! ```edition2018 -//! # use syn::{Attribute, Expr, Ident, Token, Type, Visibility}; -//! # -//! pub struct ItemStatic { -//! pub attrs: Vec<Attribute>, -//! pub vis: Visibility, -//! pub static_token: Token![static], -//! pub mutability: Option<Token![mut]>, -//! pub ident: Ident, -//! pub colon_token: Token![:], -//! pub ty: Box<Type>, -//! pub eq_token: Token![=], -//! pub expr: Box<Expr>, -//! pub semi_token: Token![;], -//! } -//! ``` -//! -//! # Parsing -//! -//! Keywords and punctuation can be parsed through the [`ParseStream::parse`] -//! method. Delimiter tokens are parsed using the [`parenthesized!`], -//! [`bracketed!`] and [`braced!`] macros. -//! -//! [`ParseStream::parse`]: ../parse/struct.ParseBuffer.html#method.parse -//! [`parenthesized!`]: ../macro.parenthesized.html -//! [`bracketed!`]: ../macro.bracketed.html -//! [`braced!`]: ../macro.braced.html -//! -//! ```edition2018 -//! use syn::{Attribute, Result}; -//! use syn::parse::{Parse, ParseStream}; -//! # -//! # enum ItemStatic {} -//! -//! // Parse the ItemStatic struct shown above. -//! impl Parse for ItemStatic { -//! fn parse(input: ParseStream) -> Result<Self> { -//! # use syn::ItemStatic; -//! # fn parse(input: ParseStream) -> Result<ItemStatic> { -//! Ok(ItemStatic { -//! attrs: input.call(Attribute::parse_outer)?, -//! vis: input.parse()?, -//! static_token: input.parse()?, -//! mutability: input.parse()?, -//! ident: input.parse()?, -//! colon_token: input.parse()?, -//! ty: input.parse()?, -//! eq_token: input.parse()?, -//! expr: input.parse()?, -//! semi_token: input.parse()?, -//! }) -//! # } -//! # unimplemented!() -//! } -//! } -//! ``` -//! -//! # Other operations -//! -//! Every keyword and punctuation token supports the following operations. -//! -//! - [Peeking] — `input.peek(Token![...])` -//! -//! - [Parsing] — `input.parse::<Token![...]>()?` -//! -//! - [Printing] — `quote!( ... #the_token ... )` -//! -//! - Construction from a [`Span`] — `let the_token = Token![...](sp)` -//! -//! - Field access to its span — `let sp = the_token.span` -//! -//! [Peeking]: ../parse/struct.ParseBuffer.html#method.peek -//! [Parsing]: ../parse/struct.ParseBuffer.html#method.parse -//! [Printing]: https://docs.rs/quote/0.6/quote/trait.ToTokens.html -//! [`Span`]: https://docs.rs/proc-macro2/0.4/proc_macro2/struct.Span.html - -use std; -#[cfg(feature = "extra-traits")] -use std::cmp; -#[cfg(feature = "extra-traits")] -use std::fmt::{self, Debug}; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; -use std::ops::{Deref, DerefMut}; - -#[cfg(feature = "parsing")] -use proc_macro2::Delimiter; -#[cfg(any(feature = "parsing", feature = "printing"))] -use proc_macro2::Ident; -use proc_macro2::Span; -#[cfg(feature = "printing")] -use proc_macro2::TokenStream; -#[cfg(feature = "printing")] -use quote::{ToTokens, TokenStreamExt}; - -use self::private::WithSpan; -#[cfg(feature = "parsing")] -use buffer::Cursor; -#[cfg(feature = "parsing")] -use error::Result; -#[cfg(any(feature = "full", feature = "derive"))] -#[cfg(feature = "parsing")] -use lifetime::Lifetime; -#[cfg(any(feature = "full", feature = "derive"))] -#[cfg(feature = "parsing")] -use lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr}; -#[cfg(feature = "parsing")] -use lookahead; -#[cfg(feature = "parsing")] -use parse::{Parse, ParseStream}; -use span::IntoSpans; - -/// Marker trait for types that represent single tokens. -/// -/// This trait is sealed and cannot be implemented for types outside of Syn. -#[cfg(feature = "parsing")] -pub trait Token: private::Sealed { - // Not public API. - #[doc(hidden)] - fn peek(cursor: Cursor) -> bool; - - // Not public API. - #[doc(hidden)] - fn display() -> &'static str; -} - -mod private { - use proc_macro2::Span; - - #[cfg(feature = "parsing")] - pub trait Sealed {} - - /// Support writing `token.span` rather than `token.spans[0]` on tokens that - /// hold a single span. - #[repr(C)] - pub struct WithSpan { - pub span: Span, - } -} - -#[cfg(feature = "parsing")] -impl private::Sealed for Ident {} - -#[cfg(any(feature = "full", feature = "derive"))] -#[cfg(feature = "parsing")] -fn peek_impl(cursor: Cursor, peek: fn(ParseStream) -> bool) -> bool { - use std::cell::Cell; - use std::rc::Rc; - - let scope = Span::call_site(); - let unexpected = Rc::new(Cell::new(None)); - let buffer = ::private::new_parse_buffer(scope, cursor, unexpected); - peek(&buffer) -} - -#[cfg(any(feature = "full", feature = "derive"))] -macro_rules! impl_token { - ($name:ident $display:expr) => { - #[cfg(feature = "parsing")] - impl Token for $name { - fn peek(cursor: Cursor) -> bool { - fn peek(input: ParseStream) -> bool { - <$name as Parse>::parse(input).is_ok() - } - peek_impl(cursor, peek) - } - - fn display() -> &'static str { - $display - } - } - - #[cfg(feature = "parsing")] - impl private::Sealed for $name {} - }; -} - -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(Lifetime "lifetime"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(Lit "literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitStr "string literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitByteStr "byte string literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitByte "byte literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitChar "character literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitInt "integer literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitFloat "floating point literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitBool "boolean literal"); - -// Not public API. -#[doc(hidden)] -#[cfg(feature = "parsing")] -pub trait CustomToken { - fn peek(cursor: Cursor) -> bool; - fn display() -> &'static str; -} - -#[cfg(feature = "parsing")] -impl<T: CustomToken> private::Sealed for T {} - -#[cfg(feature = "parsing")] -impl<T: CustomToken> Token for T { - fn peek(cursor: Cursor) -> bool { - <Self as CustomToken>::peek(cursor) - } - - fn display() -> &'static str { - <Self as CustomToken>::display() - } -} - -macro_rules! define_keywords { - ($($token:tt pub struct $name:ident #[$doc:meta])*) => { - $( - #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))] - #[$doc] - /// - /// Don't try to remember the name of this type -- use the [`Token!`] - /// macro instead. - /// - /// [`Token!`]: crate::token - pub struct $name { - pub span: Span, - } - - #[doc(hidden)] - #[allow(non_snake_case)] - pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name { - $name { - span: span.into_spans()[0], - } - } - - impl std::default::Default for $name { - fn default() -> Self { - $name { - span: Span::call_site(), - } - } - } - - #[cfg(feature = "extra-traits")] - impl Debug for $name { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str(stringify!($name)) - } - } - - #[cfg(feature = "extra-traits")] - impl cmp::Eq for $name {} - - #[cfg(feature = "extra-traits")] - impl PartialEq for $name { - fn eq(&self, _other: &$name) -> bool { - true - } - } - - #[cfg(feature = "extra-traits")] - impl Hash for $name { - fn hash<H: Hasher>(&self, _state: &mut H) {} - } - - #[cfg(feature = "printing")] - impl ToTokens for $name { - fn to_tokens(&self, tokens: &mut TokenStream) { - printing::keyword($token, self.span, tokens); - } - } - - #[cfg(feature = "parsing")] - impl Parse for $name { - fn parse(input: ParseStream) -> Result<Self> { - Ok($name { - span: parsing::keyword(input, $token)?, - }) - } - } - - #[cfg(feature = "parsing")] - impl Token for $name { - fn peek(cursor: Cursor) -> bool { - parsing::peek_keyword(cursor, $token) - } - - fn display() -> &'static str { - concat!("`", $token, "`") - } - } - - #[cfg(feature = "parsing")] - impl private::Sealed for $name {} - )* - }; -} - -macro_rules! impl_deref_if_len_is_1 { - ($name:ident/1) => { - impl Deref for $name { - type Target = WithSpan; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self as *const Self as *const WithSpan) } - } - } - - impl DerefMut for $name { - fn deref_mut(&mut self) -> &mut Self::Target { - unsafe { &mut *(self as *mut Self as *mut WithSpan) } - } - } - }; - - ($name:ident/$len:tt) => {}; -} - -macro_rules! define_punctuation_structs { - ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => { - $( - #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))] - #[repr(C)] - #[$doc] - /// - /// Don't try to remember the name of this type -- use the [`Token!`] - /// macro instead. - /// - /// [`Token!`]: crate::token - pub struct $name { - pub spans: [Span; $len], - } - - #[doc(hidden)] - #[allow(non_snake_case)] - pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name { - $name { - spans: spans.into_spans(), - } - } - - impl std::default::Default for $name { - fn default() -> Self { - $name { - spans: [Span::call_site(); $len], - } - } - } - - #[cfg(feature = "extra-traits")] - impl Debug for $name { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str(stringify!($name)) - } - } - - #[cfg(feature = "extra-traits")] - impl cmp::Eq for $name {} - - #[cfg(feature = "extra-traits")] - impl PartialEq for $name { - fn eq(&self, _other: &$name) -> bool { - true - } - } - - #[cfg(feature = "extra-traits")] - impl Hash for $name { - fn hash<H: Hasher>(&self, _state: &mut H) {} - } - - impl_deref_if_len_is_1!($name/$len); - )* - }; -} - -macro_rules! define_punctuation { - ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => { - $( - define_punctuation_structs! { - $token pub struct $name/$len #[$doc] - } - - #[cfg(feature = "printing")] - impl ToTokens for $name { - fn to_tokens(&self, tokens: &mut TokenStream) { - printing::punct($token, &self.spans, tokens); - } - } - - #[cfg(feature = "parsing")] - impl Parse for $name { - fn parse(input: ParseStream) -> Result<Self> { - Ok($name { - spans: parsing::punct(input, $token)?, - }) - } - } - - #[cfg(feature = "parsing")] - impl Token for $name { - fn peek(cursor: Cursor) -> bool { - parsing::peek_punct(cursor, $token) - } - - fn display() -> &'static str { - concat!("`", $token, "`") - } - } - - #[cfg(feature = "parsing")] - impl private::Sealed for $name {} - )* - }; -} - -macro_rules! define_delimiters { - ($($token:tt pub struct $name:ident #[$doc:meta])*) => { - $( - #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))] - #[$doc] - pub struct $name { - pub span: Span, - } - - #[doc(hidden)] - #[allow(non_snake_case)] - pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name { - $name { - span: span.into_spans()[0], - } - } - - impl std::default::Default for $name { - fn default() -> Self { - $name { - span: Span::call_site(), - } - } - } - - #[cfg(feature = "extra-traits")] - impl Debug for $name { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str(stringify!($name)) - } - } - - #[cfg(feature = "extra-traits")] - impl cmp::Eq for $name {} - - #[cfg(feature = "extra-traits")] - impl PartialEq for $name { - fn eq(&self, _other: &$name) -> bool { - true - } - } - - #[cfg(feature = "extra-traits")] - impl Hash for $name { - fn hash<H: Hasher>(&self, _state: &mut H) {} - } - - impl $name { - #[cfg(feature = "printing")] - pub fn surround<F>(&self, tokens: &mut TokenStream, f: F) - where - F: FnOnce(&mut TokenStream), - { - printing::delim($token, self.span, tokens, f); - } - } - - #[cfg(feature = "parsing")] - impl private::Sealed for $name {} - )* - }; -} - -define_punctuation_structs! { - "_" pub struct Underscore/1 /// `_` -} - -#[cfg(feature = "printing")] -impl ToTokens for Underscore { - fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.append(Ident::new("_", self.span)); - } -} - -#[cfg(feature = "parsing")] -impl Parse for Underscore { - fn parse(input: ParseStream) -> Result<Self> { - input.step(|cursor| { - if let Some((ident, rest)) = cursor.ident() { - if ident == "_" { - return Ok((Underscore(ident.span()), rest)); - } - } - if let Some((punct, rest)) = cursor.punct() { - if punct.as_char() == '_' { - return Ok((Underscore(punct.span()), rest)); - } - } - Err(cursor.error("expected `_`")) - }) - } -} - -#[cfg(feature = "parsing")] -impl Token for Underscore { - fn peek(cursor: Cursor) -> bool { - if let Some((ident, _rest)) = cursor.ident() { - return ident == "_"; - } - if let Some((punct, _rest)) = cursor.punct() { - return punct.as_char() == '_'; - } - false - } - - fn display() -> &'static str { - "`_`" - } -} - -#[cfg(feature = "parsing")] -impl private::Sealed for Underscore {} - -#[cfg(feature = "parsing")] -impl Token for Paren { - fn peek(cursor: Cursor) -> bool { - lookahead::is_delimiter(cursor, Delimiter::Parenthesis) - } - - fn display() -> &'static str { - "parentheses" - } -} - -#[cfg(feature = "parsing")] -impl Token for Brace { - fn peek(cursor: Cursor) -> bool { - lookahead::is_delimiter(cursor, Delimiter::Brace) - } - - fn display() -> &'static str { - "curly braces" - } -} - -#[cfg(feature = "parsing")] -impl Token for Bracket { - fn peek(cursor: Cursor) -> bool { - lookahead::is_delimiter(cursor, Delimiter::Bracket) - } - - fn display() -> &'static str { - "square brackets" - } -} - -#[cfg(feature = "parsing")] -impl Token for Group { - fn peek(cursor: Cursor) -> bool { - lookahead::is_delimiter(cursor, Delimiter::None) - } - - fn display() -> &'static str { - "invisible group" - } -} - -define_keywords! { - "abstract" pub struct Abstract /// `abstract` - "as" pub struct As /// `as` - "async" pub struct Async /// `async` - "auto" pub struct Auto /// `auto` - "become" pub struct Become /// `become` - "box" pub struct Box /// `box` - "break" pub struct Break /// `break` - "const" pub struct Const /// `const` - "continue" pub struct Continue /// `continue` - "crate" pub struct Crate /// `crate` - "default" pub struct Default /// `default` - "do" pub struct Do /// `do` - "dyn" pub struct Dyn /// `dyn` - "else" pub struct Else /// `else` - "enum" pub struct Enum /// `enum` - "existential" pub struct Existential /// `existential` - "extern" pub struct Extern /// `extern` - "final" pub struct Final /// `final` - "fn" pub struct Fn /// `fn` - "for" pub struct For /// `for` - "if" pub struct If /// `if` - "impl" pub struct Impl /// `impl` - "in" pub struct In /// `in` - "let" pub struct Let /// `let` - "loop" pub struct Loop /// `loop` - "macro" pub struct Macro /// `macro` - "match" pub struct Match /// `match` - "mod" pub struct Mod /// `mod` - "move" pub struct Move /// `move` - "mut" pub struct Mut /// `mut` - "override" pub struct Override /// `override` - "priv" pub struct Priv /// `priv` - "pub" pub struct Pub /// `pub` - "ref" pub struct Ref /// `ref` - "return" pub struct Return /// `return` - "Self" pub struct SelfType /// `Self` - "self" pub struct SelfValue /// `self` - "static" pub struct Static /// `static` - "struct" pub struct Struct /// `struct` - "super" pub struct Super /// `super` - "trait" pub struct Trait /// `trait` - "try" pub struct Try /// `try` - "type" pub struct Type /// `type` - "typeof" pub struct Typeof /// `typeof` - "union" pub struct Union /// `union` - "unsafe" pub struct Unsafe /// `unsafe` - "unsized" pub struct Unsized /// `unsized` - "use" pub struct Use /// `use` - "virtual" pub struct Virtual /// `virtual` - "where" pub struct Where /// `where` - "while" pub struct While /// `while` - "yield" pub struct Yield /// `yield` -} - -define_punctuation! { - "+" pub struct Add/1 /// `+` - "+=" pub struct AddEq/2 /// `+=` - "&" pub struct And/1 /// `&` - "&&" pub struct AndAnd/2 /// `&&` - "&=" pub struct AndEq/2 /// `&=` - "@" pub struct At/1 /// `@` - "!" pub struct Bang/1 /// `!` - "^" pub struct Caret/1 /// `^` - "^=" pub struct CaretEq/2 /// `^=` - ":" pub struct Colon/1 /// `:` - "::" pub struct Colon2/2 /// `::` - "," pub struct Comma/1 /// `,` - "/" pub struct Div/1 /// `/` - "/=" pub struct DivEq/2 /// `/=` - "$" pub struct Dollar/1 /// `$` - "." pub struct Dot/1 /// `.` - ".." pub struct Dot2/2 /// `..` - "..." pub struct Dot3/3 /// `...` - "..=" pub struct DotDotEq/3 /// `..=` - "=" pub struct Eq/1 /// `=` - "==" pub struct EqEq/2 /// `==` - ">=" pub struct Ge/2 /// `>=` - ">" pub struct Gt/1 /// `>` - "<=" pub struct Le/2 /// `<=` - "<" pub struct Lt/1 /// `<` - "*=" pub struct MulEq/2 /// `*=` - "!=" pub struct Ne/2 /// `!=` - "|" pub struct Or/1 /// `|` - "|=" pub struct OrEq/2 /// `|=` - "||" pub struct OrOr/2 /// `||` - "#" pub struct Pound/1 /// `#` - "?" pub struct Question/1 /// `?` - "->" pub struct RArrow/2 /// `->` - "<-" pub struct LArrow/2 /// `<-` - "%" pub struct Rem/1 /// `%` - "%=" pub struct RemEq/2 /// `%=` - "=>" pub struct FatArrow/2 /// `=>` - ";" pub struct Semi/1 /// `;` - "<<" pub struct Shl/2 /// `<<` - "<<=" pub struct ShlEq/3 /// `<<=` - ">>" pub struct Shr/2 /// `>>` - ">>=" pub struct ShrEq/3 /// `>>=` - "*" pub struct Star/1 /// `*` - "-" pub struct Sub/1 /// `-` - "-=" pub struct SubEq/2 /// `-=` - "~" pub struct Tilde/1 /// `~` -} - -define_delimiters! { - "{" pub struct Brace /// `{...}` - "[" pub struct Bracket /// `[...]` - "(" pub struct Paren /// `(...)` - " " pub struct Group /// None-delimited group -} - -macro_rules! export_token_macro { - ($($dollar:tt)*) => { - /// A type-macro that expands to the name of the Rust type representation of a - /// given token. - /// - /// See the [token module] documentation for details and examples. - /// - /// [token module]: crate::token - // Unfortunate duplication due to a rustdoc bug. - // https://github.com/rust-lang/rust/issues/45939 - #[macro_export] - macro_rules! Token { - (abstract) => { $crate::token::Abstract }; - (as) => { $crate::token::As }; - (async) => { $crate::token::Async }; - (auto) => { $crate::token::Auto }; - (become) => { $crate::token::Become }; - (box) => { $crate::token::Box }; - (break) => { $crate::token::Break }; - (const) => { $crate::token::Const }; - (continue) => { $crate::token::Continue }; - (crate) => { $crate::token::Crate }; - (default) => { $crate::token::Default }; - (do) => { $crate::token::Do }; - (dyn) => { $crate::token::Dyn }; - (else) => { $crate::token::Else }; - (enum) => { $crate::token::Enum }; - (existential) => { $crate::token::Existential }; - (extern) => { $crate::token::Extern }; - (final) => { $crate::token::Final }; - (fn) => { $crate::token::Fn }; - (for) => { $crate::token::For }; - (if) => { $crate::token::If }; - (impl) => { $crate::token::Impl }; - (in) => { $crate::token::In }; - (let) => { $crate::token::Let }; - (loop) => { $crate::token::Loop }; - (macro) => { $crate::token::Macro }; - (match) => { $crate::token::Match }; - (mod) => { $crate::token::Mod }; - (move) => { $crate::token::Move }; - (mut) => { $crate::token::Mut }; - (override) => { $crate::token::Override }; - (priv) => { $crate::token::Priv }; - (pub) => { $crate::token::Pub }; - (ref) => { $crate::token::Ref }; - (return) => { $crate::token::Return }; - (Self) => { $crate::token::SelfType }; - (self) => { $crate::token::SelfValue }; - (static) => { $crate::token::Static }; - (struct) => { $crate::token::Struct }; - (super) => { $crate::token::Super }; - (trait) => { $crate::token::Trait }; - (try) => { $crate::token::Try }; - (type) => { $crate::token::Type }; - (typeof) => { $crate::token::Typeof }; - (union) => { $crate::token::Union }; - (unsafe) => { $crate::token::Unsafe }; - (unsized) => { $crate::token::Unsized }; - (use) => { $crate::token::Use }; - (virtual) => { $crate::token::Virtual }; - (where) => { $crate::token::Where }; - (while) => { $crate::token::While }; - (yield) => { $crate::token::Yield }; - (+) => { $crate::token::Add }; - (+=) => { $crate::token::AddEq }; - (&) => { $crate::token::And }; - (&&) => { $crate::token::AndAnd }; - (&=) => { $crate::token::AndEq }; - (@) => { $crate::token::At }; - (!) => { $crate::token::Bang }; - (^) => { $crate::token::Caret }; - (^=) => { $crate::token::CaretEq }; - (:) => { $crate::token::Colon }; - (::) => { $crate::token::Colon2 }; - (,) => { $crate::token::Comma }; - (/) => { $crate::token::Div }; - (/=) => { $crate::token::DivEq }; - (.) => { $crate::token::Dot }; - (..) => { $crate::token::Dot2 }; - (...) => { $crate::token::Dot3 }; - (..=) => { $crate::token::DotDotEq }; - (=) => { $crate::token::Eq }; - (==) => { $crate::token::EqEq }; - (>=) => { $crate::token::Ge }; - (>) => { $crate::token::Gt }; - (<=) => { $crate::token::Le }; - (<) => { $crate::token::Lt }; - (*=) => { $crate::token::MulEq }; - (!=) => { $crate::token::Ne }; - (|) => { $crate::token::Or }; - (|=) => { $crate::token::OrEq }; - (||) => { $crate::token::OrOr }; - (#) => { $crate::token::Pound }; - (?) => { $crate::token::Question }; - (->) => { $crate::token::RArrow }; - (<-) => { $crate::token::LArrow }; - (%) => { $crate::token::Rem }; - (%=) => { $crate::token::RemEq }; - (=>) => { $crate::token::FatArrow }; - (;) => { $crate::token::Semi }; - (<<) => { $crate::token::Shl }; - (<<=) => { $crate::token::ShlEq }; - (>>) => { $crate::token::Shr }; - (>>=) => { $crate::token::ShrEq }; - (*) => { $crate::token::Star }; - (-) => { $crate::token::Sub }; - (-=) => { $crate::token::SubEq }; - (~) => { $crate::token::Tilde }; - (_) => { $crate::token::Underscore }; - $($dollar => { $crate::token::Dollar };)* - } - }; -} - -#[cfg(syn_can_match_trailing_dollar)] -export_token_macro![($)]; - -// Old rustc does not support ($) => {...} as a macro rule. -#[cfg(not(syn_can_match_trailing_dollar))] -export_token_macro![]; - -// Old names. TODO: remove these re-exports in a breaking change. -// https://github.com/dtolnay/syn/issues/486 -#[doc(hidden)] -pub use self::SelfType as CapSelf; -#[doc(hidden)] -pub use self::SelfValue as Self_; - -// Not public API. -#[doc(hidden)] -#[cfg(feature = "parsing")] -pub mod parsing { - use proc_macro2::{Spacing, Span}; - - use buffer::Cursor; - use error::{Error, Result}; - use parse::ParseStream; - use span::FromSpans; - - pub fn keyword(input: ParseStream, token: &str) -> Result<Span> { - input.step(|cursor| { - if let Some((ident, rest)) = cursor.ident() { - if ident == token { - return Ok((ident.span(), rest)); - } - } - Err(cursor.error(format!("expected `{}`", token))) - }) - } - - pub fn peek_keyword(cursor: Cursor, token: &str) -> bool { - if let Some((ident, _rest)) = cursor.ident() { - ident == token - } else { - false - } - } - - pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> { - let mut spans = [input.cursor().span(); 3]; - punct_helper(input, token, &mut spans)?; - Ok(S::from_spans(&spans)) - } - - fn punct_helper(input: ParseStream, token: &str, spans: &mut [Span; 3]) -> Result<()> { - input.step(|cursor| { - let mut cursor = *cursor; - assert!(token.len() <= spans.len()); - - for (i, ch) in token.chars().enumerate() { - match cursor.punct() { - Some((punct, rest)) => { - spans[i] = punct.span(); - if punct.as_char() != ch { - break; - } else if i == token.len() - 1 { - return Ok(((), rest)); - } else if punct.spacing() != Spacing::Joint { - break; - } - cursor = rest; - } - None => break, - } - } - - Err(Error::new(spans[0], format!("expected `{}`", token))) - }) - } - - pub fn peek_punct(mut cursor: Cursor, token: &str) -> bool { - for (i, ch) in token.chars().enumerate() { - match cursor.punct() { - Some((punct, rest)) => { - if punct.as_char() != ch { - break; - } else if i == token.len() - 1 { - return true; - } else if punct.spacing() != Spacing::Joint { - break; - } - cursor = rest; - } - None => break, - } - } - false - } -} - -// Not public API. -#[doc(hidden)] -#[cfg(feature = "printing")] -pub mod printing { - use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream}; - use quote::TokenStreamExt; - - pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) { - assert_eq!(s.len(), spans.len()); - - let mut chars = s.chars(); - let mut spans = spans.iter(); - let ch = chars.next_back().unwrap(); - let span = spans.next_back().unwrap(); - for (ch, span) in chars.zip(spans) { - let mut op = Punct::new(ch, Spacing::Joint); - op.set_span(*span); - tokens.append(op); - } - - let mut op = Punct::new(ch, Spacing::Alone); - op.set_span(*span); - tokens.append(op); - } - - pub fn keyword(s: &str, span: Span, tokens: &mut TokenStream) { - tokens.append(Ident::new(s, span)); - } - - pub fn delim<F>(s: &str, span: Span, tokens: &mut TokenStream, f: F) - where - F: FnOnce(&mut TokenStream), - { - let delim = match s { - "(" => Delimiter::Parenthesis, - "[" => Delimiter::Bracket, - "{" => Delimiter::Brace, - " " => Delimiter::None, - _ => panic!("unknown delimiter: {}", s), - }; - let mut inner = TokenStream::new(); - f(&mut inner); - let mut g = Group::new(delim, inner); - g.set_span(span); - tokens.append(g); - } -} diff --git a/0.15.42/src/tt.rs b/0.15.42/src/tt.rs deleted file mode 100644 index 72bc3c11..00000000 --- a/0.15.42/src/tt.rs +++ /dev/null @@ -1,110 +0,0 @@ -use std::hash::{Hash, Hasher}; - -use proc_macro2::{Delimiter, TokenStream, TokenTree}; - -pub struct TokenTreeHelper<'a>(pub &'a TokenTree); - -impl<'a> PartialEq for TokenTreeHelper<'a> { - fn eq(&self, other: &Self) -> bool { - use proc_macro2::Spacing; - - match (self.0, other.0) { - (&TokenTree::Group(ref g1), &TokenTree::Group(ref g2)) => { - match (g1.delimiter(), g2.delimiter()) { - (Delimiter::Parenthesis, Delimiter::Parenthesis) - | (Delimiter::Brace, Delimiter::Brace) - | (Delimiter::Bracket, Delimiter::Bracket) - | (Delimiter::None, Delimiter::None) => {} - _ => return false, - } - - let s1 = g1.stream().clone().into_iter(); - let mut s2 = g2.stream().clone().into_iter(); - - for item1 in s1 { - let item2 = match s2.next() { - Some(item) => item, - None => return false, - }; - if TokenTreeHelper(&item1) != TokenTreeHelper(&item2) { - return false; - } - } - s2.next().is_none() - } - (&TokenTree::Punct(ref o1), &TokenTree::Punct(ref o2)) => { - o1.as_char() == o2.as_char() - && match (o1.spacing(), o2.spacing()) { - (Spacing::Alone, Spacing::Alone) | (Spacing::Joint, Spacing::Joint) => true, - _ => false, - } - } - (&TokenTree::Literal(ref l1), &TokenTree::Literal(ref l2)) => { - l1.to_string() == l2.to_string() - } - (&TokenTree::Ident(ref s1), &TokenTree::Ident(ref s2)) => s1 == s2, - _ => false, - } - } -} - -impl<'a> Hash for TokenTreeHelper<'a> { - fn hash<H: Hasher>(&self, h: &mut H) { - use proc_macro2::Spacing; - - match *self.0 { - TokenTree::Group(ref g) => { - 0u8.hash(h); - match g.delimiter() { - Delimiter::Parenthesis => 0u8.hash(h), - Delimiter::Brace => 1u8.hash(h), - Delimiter::Bracket => 2u8.hash(h), - Delimiter::None => 3u8.hash(h), - } - - for item in g.stream().clone() { - TokenTreeHelper(&item).hash(h); - } - 0xffu8.hash(h); // terminator w/ a variant we don't normally hash - } - TokenTree::Punct(ref op) => { - 1u8.hash(h); - op.as_char().hash(h); - match op.spacing() { - Spacing::Alone => 0u8.hash(h), - Spacing::Joint => 1u8.hash(h), - } - } - TokenTree::Literal(ref lit) => (2u8, lit.to_string()).hash(h), - TokenTree::Ident(ref word) => (3u8, word).hash(h), - } - } -} - -pub struct TokenStreamHelper<'a>(pub &'a TokenStream); - -impl<'a> PartialEq for TokenStreamHelper<'a> { - fn eq(&self, other: &Self) -> bool { - let left = self.0.clone().into_iter().collect::<Vec<_>>(); - let right = other.0.clone().into_iter().collect::<Vec<_>>(); - if left.len() != right.len() { - return false; - } - for (a, b) in left.into_iter().zip(right) { - if TokenTreeHelper(&a) != TokenTreeHelper(&b) { - return false; - } - } - true - } -} - -impl<'a> Hash for TokenStreamHelper<'a> { - fn hash<H: Hasher>(&self, state: &mut H) { - let tts = self.0.clone().into_iter().collect::<Vec<_>>(); - tts.len().hash(state); - for tt in tts { - TokenTreeHelper(&tt).hash(state); - } - } -} diff --git a/0.15.42/src/ty.rs b/0.15.42/src/ty.rs deleted file mode 100644 index 9e6e3f3e..00000000 --- a/0.15.42/src/ty.rs +++ /dev/null @@ -1,997 +0,0 @@ -use super::*; -use proc_macro2::TokenStream; -use punctuated::Punctuated; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; -#[cfg(feature = "extra-traits")] -use tt::TokenStreamHelper; - -ast_enum_of_structs! { - /// The possible types that a Rust value could have. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// - /// # Syntax tree enum - /// - /// This type is a [syntax tree enum]. - /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Type { - /// A dynamically sized slice type: `[T]`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Slice(TypeSlice { - pub bracket_token: token::Bracket, - pub elem: Box<Type>, - }), - - /// A fixed size array type: `[T; n]`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Array(TypeArray { - pub bracket_token: token::Bracket, - pub elem: Box<Type>, - pub semi_token: Token![;], - pub len: Expr, - }), - - /// A raw pointer type: `*const T` or `*mut T`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Ptr(TypePtr { - pub star_token: Token![*], - pub const_token: Option<Token![const]>, - pub mutability: Option<Token![mut]>, - pub elem: Box<Type>, - }), - - /// A reference type: `&'a T` or `&'a mut T`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Reference(TypeReference { - pub and_token: Token![&], - pub lifetime: Option<Lifetime>, - pub mutability: Option<Token![mut]>, - pub elem: Box<Type>, - }), - - /// A bare function type: `fn(usize) -> bool`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub BareFn(TypeBareFn { - pub lifetimes: Option<BoundLifetimes>, - pub unsafety: Option<Token![unsafe]>, - pub abi: Option<Abi>, - pub fn_token: Token![fn], - pub paren_token: token::Paren, - pub inputs: Punctuated<BareFnArg, Token![,]>, - pub variadic: Option<Token![...]>, - pub output: ReturnType, - }), - - /// The never type: `!`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Never(TypeNever { - pub bang_token: Token![!], - }), - - /// A tuple type: `(A, B, C, String)`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Tuple(TypeTuple { - pub paren_token: token::Paren, - pub elems: Punctuated<Type, Token![,]>, - }), - - /// A path like `std::slice::Iter`, optionally qualified with a - /// self-type as in `<Vec<T> as SomeTrait>::Associated`. - /// - /// Type arguments are stored in the Path itself. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Path(TypePath { - pub qself: Option<QSelf>, - pub path: Path, - }), - - /// A trait object type `Bound1 + Bound2 + Bound3` where `Bound` is a - /// trait or a lifetime. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub TraitObject(TypeTraitObject { - pub dyn_token: Option<Token![dyn]>, - pub bounds: Punctuated<TypeParamBound, Token![+]>, - }), - - /// An `impl Bound1 + Bound2 + Bound3` type where `Bound` is a trait or - /// a lifetime. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub ImplTrait(TypeImplTrait { - pub impl_token: Token![impl], - pub bounds: Punctuated<TypeParamBound, Token![+]>, - }), - - /// A parenthesized type equivalent to the inner type. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Paren(TypeParen { - pub paren_token: token::Paren, - pub elem: Box<Type>, - }), - - /// A type contained within invisible delimiters. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Group(TypeGroup { - pub group_token: token::Group, - pub elem: Box<Type>, - }), - - /// Indication that a type should be inferred by the compiler: `_`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Infer(TypeInfer { - pub underscore_token: Token![_], - }), - - /// A macro in the type position. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Macro(TypeMacro { - pub mac: Macro, - }), - - /// Tokens in type position not interpreted by Syn. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub Verbatim(TypeVerbatim #manual_extra_traits { - pub tts: TokenStream, - }), - } -} - -#[cfg(feature = "extra-traits")] -impl Eq for TypeVerbatim {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for TypeVerbatim { - fn eq(&self, other: &Self) -> bool { - TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for TypeVerbatim { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - TokenStreamHelper(&self.tts).hash(state); - } -} - -ast_struct! { - /// The binary interface of a function: `extern "C"`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct Abi { - pub extern_token: Token![extern], - pub name: Option<LitStr>, - } -} - -ast_struct! { - /// An argument in a function type: the `usize` in `fn(usize) -> bool`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub struct BareFnArg { - pub name: Option<(BareFnArgName, Token![:])>, - pub ty: Type, - } -} - -ast_enum! { - /// Name of an argument in a function type: the `n` in `fn(n: usize)`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum BareFnArgName { - /// Argument given a name. - Named(Ident), - /// Argument not given a name, matched with `_`. - Wild(Token![_]), - } -} - -ast_enum! { - /// Return type of a function signature. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - pub enum ReturnType { - /// Return type is not specified. - /// - /// Functions default to `()` and closures default to type inference. - Default, - /// A particular type is returned. - Type(Token![->], Box<Type>), - } -} - -#[cfg(feature = "parsing")] -pub mod parsing { - use super::*; - - use parse::{Parse, ParseStream, Result}; - use path; - - impl Parse for Type { - fn parse(input: ParseStream) -> Result<Self> { - ambig_ty(input, true) - } - } - - impl Type { - /// In some positions, types may not contain the `+` character, to - /// disambiguate them. For example in the expression `1 as T`, T may not - /// contain a `+` character. - /// - /// This parser does not allow a `+`, while the default parser does. - pub fn without_plus(input: ParseStream) -> Result<Self> { - ambig_ty(input, false) - } - } - - fn ambig_ty(input: ParseStream, allow_plus: bool) -> Result<Type> { - if input.peek(token::Group) { - return input.parse().map(Type::Group); - } - - let mut lifetimes = None::<BoundLifetimes>; - let mut lookahead = input.lookahead1(); - if lookahead.peek(Token![for]) { - lifetimes = input.parse()?; - lookahead = input.lookahead1(); - if !lookahead.peek(Ident) - && !lookahead.peek(Token![fn]) - && !lookahead.peek(Token![unsafe]) - && !lookahead.peek(Token![extern]) - && !lookahead.peek(Token![super]) - && !lookahead.peek(Token![self]) - && !lookahead.peek(Token![Self]) - && !lookahead.peek(Token![crate]) - { - return Err(lookahead.error()); - } - } - - if lookahead.peek(token::Paren) { - let content; - let paren_token = parenthesized!(content in input); - if content.is_empty() { - return Ok(Type::Tuple(TypeTuple { - paren_token: paren_token, - elems: Punctuated::new(), - })); - } - if content.peek(Lifetime) { - return Ok(Type::Paren(TypeParen { - paren_token: paren_token, - elem: Box::new(Type::TraitObject(content.parse()?)), - })); - } - if content.peek(Token![?]) { - return Ok(Type::TraitObject(TypeTraitObject { - dyn_token: None, - bounds: { - let mut bounds = Punctuated::new(); - bounds.push_value(TypeParamBound::Trait(TraitBound { - paren_token: Some(paren_token), - ..content.parse()? - })); - while let Some(plus) = input.parse()? { - bounds.push_punct(plus); - bounds.push_value(input.parse()?); - } - bounds - }, - })); - } - let first: Type = content.parse()?; - if content.peek(Token![,]) { - return Ok(Type::Tuple(TypeTuple { - paren_token: paren_token, - elems: { - let mut elems = Punctuated::new(); - elems.push_value(first); - elems.push_punct(content.parse()?); - let rest: Punctuated<Type, Token![,]> = - content.parse_terminated(Parse::parse)?; - elems.extend(rest); - elems - }, - })); - } - if allow_plus && input.peek(Token![+]) { - loop { - let first = match first { - Type::Path(TypePath { qself: None, path }) => { - TypeParamBound::Trait(TraitBound { - paren_token: Some(paren_token), - modifier: TraitBoundModifier::None, - lifetimes: None, - path: path, - }) - } - Type::TraitObject(TypeTraitObject { - dyn_token: None, - ref bounds, - }) => { - if bounds.len() > 1 || bounds.trailing_punct() { - break; - } - match first { - Type::TraitObject(TypeTraitObject { bounds, .. }) => { - match bounds.into_iter().next().unwrap() { - TypeParamBound::Trait(trait_bound) => { - TypeParamBound::Trait(TraitBound { - paren_token: Some(paren_token), - ..trait_bound - }) - } - other => other, - } - } - _ => unreachable!(), - } - } - _ => break, - }; - return Ok(Type::TraitObject(TypeTraitObject { - dyn_token: None, - bounds: { - let mut bounds = Punctuated::new(); - bounds.push_value(first); - while let Some(plus) = input.parse()? { - bounds.push_punct(plus); - bounds.push_value(input.parse()?); - } - bounds - }, - })); - } - } - Ok(Type::Paren(TypeParen { - paren_token: paren_token, - elem: Box::new(first), - })) - } else if lookahead.peek(Token![fn]) - || lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![extern]) && !input.peek2(Token![::]) - { - let mut bare_fn: TypeBareFn = input.parse()?; - bare_fn.lifetimes = lifetimes; - Ok(Type::BareFn(bare_fn)) - } else if lookahead.peek(Ident) - || input.peek(Token![super]) - || input.peek(Token![self]) - || input.peek(Token![Self]) - || input.peek(Token![crate]) - || input.peek(Token![extern]) - || lookahead.peek(Token![::]) - || lookahead.peek(Token![<]) - { - if input.peek(Token![dyn]) { - let mut trait_object: TypeTraitObject = input.parse()?; - if lifetimes.is_some() { - match *trait_object.bounds.iter_mut().next().unwrap() { - TypeParamBound::Trait(ref mut trait_bound) => { - trait_bound.lifetimes = lifetimes; - } - TypeParamBound::Lifetime(_) => unreachable!(), - } - } - return Ok(Type::TraitObject(trait_object)); - } - - let ty: TypePath = input.parse()?; - if ty.qself.is_some() { - return Ok(Type::Path(ty)); - } - - if input.peek(Token![!]) && !input.peek(Token![!=]) { - let mut contains_arguments = false; - for segment in &ty.path.segments { - match segment.arguments { - PathArguments::None => {} - PathArguments::AngleBracketed(_) | PathArguments::Parenthesized(_) => { - contains_arguments = true; - } - } - } - - if !contains_arguments { - let bang_token: Token![!] = input.parse()?; - let (delimiter, tts) = mac::parse_delimiter(input)?; - return Ok(Type::Macro(TypeMacro { - mac: Macro { - path: ty.path, - bang_token: bang_token, - delimiter: delimiter, - tts: tts, - }, - })); - } - } - - if lifetimes.is_some() || allow_plus && input.peek(Token![+]) { - let mut bounds = Punctuated::new(); - bounds.push_value(TypeParamBound::Trait(TraitBound { - paren_token: None, - modifier: TraitBoundModifier::None, - lifetimes: lifetimes, - path: ty.path, - })); - if allow_plus { - while input.peek(Token![+]) { - bounds.push_punct(input.parse()?); - if input.peek(Token![>]) { - break; - } - bounds.push_value(input.parse()?); - } - } - return Ok(Type::TraitObject(TypeTraitObject { - dyn_token: None, - bounds: bounds, - })); - } - - Ok(Type::Path(ty)) - } else if lookahead.peek(token::Bracket) { - let content; - let bracket_token = bracketed!(content in input); - let elem: Type = content.parse()?; - if content.peek(Token![;]) { - Ok(Type::Array(TypeArray { - bracket_token: bracket_token, - elem: Box::new(elem), - semi_token: content.parse()?, - len: content.parse()?, - })) - } else { - Ok(Type::Slice(TypeSlice { - bracket_token: bracket_token, - elem: Box::new(elem), - })) - } - } else if lookahead.peek(Token![*]) { - input.parse().map(Type::Ptr) - } else if lookahead.peek(Token![&]) { - input.parse().map(Type::Reference) - } else if lookahead.peek(Token![!]) && !input.peek(Token![=]) { - input.parse().map(Type::Never) - } else if lookahead.peek(Token![impl]) { - input.parse().map(Type::ImplTrait) - } else if lookahead.peek(Token![_]) { - input.parse().map(Type::Infer) - } else if lookahead.peek(Lifetime) { - input.parse().map(Type::TraitObject) - } else { - Err(lookahead.error()) - } - } - - impl Parse for TypeSlice { - fn parse(input: ParseStream) -> Result<Self> { - let content; - Ok(TypeSlice { - bracket_token: bracketed!(content in input), - elem: content.parse()?, - }) - } - } - - impl Parse for TypeArray { - fn parse(input: ParseStream) -> Result<Self> { - let content; - Ok(TypeArray { - bracket_token: bracketed!(content in input), - elem: content.parse()?, - semi_token: content.parse()?, - len: content.parse()?, - }) - } - } - - impl Parse for TypePtr { - fn parse(input: ParseStream) -> Result<Self> { - let star_token: Token![*] = input.parse()?; - - let lookahead = input.lookahead1(); - let (const_token, mutability) = if lookahead.peek(Token![const]) { - (Some(input.parse()?), None) - } else if lookahead.peek(Token![mut]) { - (None, Some(input.parse()?)) - } else { - return Err(lookahead.error()); - }; - - Ok(TypePtr { - star_token: star_token, - const_token: const_token, - mutability: mutability, - elem: Box::new(input.call(Type::without_plus)?), - }) - } - } - - impl Parse for TypeReference { - fn parse(input: ParseStream) -> Result<Self> { - Ok(TypeReference { - and_token: input.parse()?, - lifetime: input.parse()?, - mutability: input.parse()?, - // & binds tighter than +, so we don't allow + here. - elem: Box::new(input.call(Type::without_plus)?), - }) - } - } - - impl Parse for TypeBareFn { - fn parse(input: ParseStream) -> Result<Self> { - let args; - let allow_variadic; - Ok(TypeBareFn { - lifetimes: input.parse()?, - unsafety: input.parse()?, - abi: input.parse()?, - fn_token: input.parse()?, - paren_token: parenthesized!(args in input), - inputs: { - let mut inputs = Punctuated::new(); - while !args.is_empty() && !args.peek(Token![...]) { - inputs.push_value(args.parse()?); - if args.is_empty() { - break; - } - inputs.push_punct(args.parse()?); - } - allow_variadic = inputs.empty_or_trailing(); - inputs - }, - variadic: { - if allow_variadic && args.peek(Token![...]) { - Some(args.parse()?) - } else { - None - } - }, - output: input.call(ReturnType::without_plus)?, - }) - } - } - - impl Parse for TypeNever { - fn parse(input: ParseStream) -> Result<Self> { - Ok(TypeNever { - bang_token: input.parse()?, - }) - } - } - - impl Parse for TypeInfer { - fn parse(input: ParseStream) -> Result<Self> { - Ok(TypeInfer { - underscore_token: input.parse()?, - }) - } - } - - impl Parse for TypeTuple { - fn parse(input: ParseStream) -> Result<Self> { - let content; - Ok(TypeTuple { - paren_token: parenthesized!(content in input), - elems: content.parse_terminated(Type::parse)?, - }) - } - } - - impl Parse for TypeMacro { - fn parse(input: ParseStream) -> Result<Self> { - Ok(TypeMacro { - mac: input.parse()?, - }) - } - } - - impl Parse for TypePath { - fn parse(input: ParseStream) -> Result<Self> { - let (qself, mut path) = path::parsing::qpath(input, false)?; - - if path.segments.last().unwrap().value().arguments.is_empty() - && input.peek(token::Paren) - { - let args: ParenthesizedGenericArguments = input.parse()?; - let parenthesized = PathArguments::Parenthesized(args); - path.segments.last_mut().unwrap().value_mut().arguments = parenthesized; - } - - Ok(TypePath { - qself: qself, - path: path, - }) - } - } - - impl ReturnType { - pub fn without_plus(input: ParseStream) -> Result<Self> { - Self::parse(input, false) - } - - pub fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> { - if input.peek(Token![->]) { - let arrow = input.parse()?; - let ty = ambig_ty(input, allow_plus)?; - Ok(ReturnType::Type(arrow, Box::new(ty))) - } else { - Ok(ReturnType::Default) - } - } - } - - impl Parse for ReturnType { - fn parse(input: ParseStream) -> Result<Self> { - Self::parse(input, true) - } - } - - impl Parse for TypeTraitObject { - fn parse(input: ParseStream) -> Result<Self> { - Self::parse(input, true) - } - } - - fn at_least_one_type(bounds: &Punctuated<TypeParamBound, Token![+]>) -> bool { - for bound in bounds { - if let TypeParamBound::Trait(_) = *bound { - return true; - } - } - false - } - - impl TypeTraitObject { - pub fn without_plus(input: ParseStream) -> Result<Self> { - Self::parse(input, false) - } - - // Only allow multiple trait references if allow_plus is true. - pub fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> { - Ok(TypeTraitObject { - dyn_token: input.parse()?, - bounds: { - let mut bounds = Punctuated::new(); - if allow_plus { - loop { - bounds.push_value(input.parse()?); - if !input.peek(Token![+]) { - break; - } - bounds.push_punct(input.parse()?); - if input.peek(Token![>]) { - break; - } - } - } else { - bounds.push_value(input.parse()?); - } - // Just lifetimes like `'a + 'b` is not a TraitObject. - if !at_least_one_type(&bounds) { - return Err(input.error("expected at least one type")); - } - bounds - }, - }) - } - } - - impl Parse for TypeImplTrait { - fn parse(input: ParseStream) -> Result<Self> { - Ok(TypeImplTrait { - impl_token: input.parse()?, - // NOTE: rust-lang/rust#34511 includes discussion about whether - // or not + should be allowed in ImplTrait directly without (). - bounds: { - let mut bounds = Punctuated::new(); - loop { - bounds.push_value(input.parse()?); - if !input.peek(Token![+]) { - break; - } - bounds.push_punct(input.parse()?); - } - bounds - }, - }) - } - } - - impl Parse for TypeGroup { - fn parse(input: ParseStream) -> Result<Self> { - let group = private::parse_group(input)?; - Ok(TypeGroup { - group_token: group.token, - elem: group.content.parse()?, - }) - } - } - - impl Parse for TypeParen { - fn parse(input: ParseStream) -> Result<Self> { - Self::parse(input, false) - } - } - - impl TypeParen { - fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> { - let content; - Ok(TypeParen { - paren_token: parenthesized!(content in input), - elem: Box::new(ambig_ty(&content, allow_plus)?), - }) - } - } - - impl Parse for BareFnArg { - fn parse(input: ParseStream) -> Result<Self> { - Ok(BareFnArg { - name: { - if (input.peek(Ident) || input.peek(Token![_])) - && !input.peek2(Token![::]) - && input.peek2(Token![:]) - { - let name: BareFnArgName = input.parse()?; - let colon: Token![:] = input.parse()?; - Some((name, colon)) - } else { - None - } - }, - ty: input.parse()?, - }) - } - } - - impl Parse for BareFnArgName { - fn parse(input: ParseStream) -> Result<Self> { - let lookahead = input.lookahead1(); - if lookahead.peek(Ident) { - input.parse().map(BareFnArgName::Named) - } else if lookahead.peek(Token![_]) { - input.parse().map(BareFnArgName::Wild) - } else { - Err(lookahead.error()) - } - } - } - - impl Parse for Abi { - fn parse(input: ParseStream) -> Result<Self> { - Ok(Abi { - extern_token: input.parse()?, - name: input.parse()?, - }) - } - } - - impl Parse for Option<Abi> { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Token![extern]) { - input.parse().map(Some) - } else { - Ok(None) - } - } - } -} - -#[cfg(feature = "printing")] -mod printing { - use super::*; - - use proc_macro2::TokenStream; - use quote::ToTokens; - - use print::TokensOrDefault; - - impl ToTokens for TypeSlice { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.bracket_token.surround(tokens, |tokens| { - self.elem.to_tokens(tokens); - }); - } - } - - impl ToTokens for TypeArray { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.bracket_token.surround(tokens, |tokens| { - self.elem.to_tokens(tokens); - self.semi_token.to_tokens(tokens); - self.len.to_tokens(tokens); - }); - } - } - - impl ToTokens for TypePtr { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.star_token.to_tokens(tokens); - match self.mutability { - Some(ref tok) => tok.to_tokens(tokens), - None => { - TokensOrDefault(&self.const_token).to_tokens(tokens); - } - } - self.elem.to_tokens(tokens); - } - } - - impl ToTokens for TypeReference { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.and_token.to_tokens(tokens); - self.lifetime.to_tokens(tokens); - self.mutability.to_tokens(tokens); - self.elem.to_tokens(tokens); - } - } - - impl ToTokens for TypeBareFn { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.lifetimes.to_tokens(tokens); - self.unsafety.to_tokens(tokens); - self.abi.to_tokens(tokens); - self.fn_token.to_tokens(tokens); - self.paren_token.surround(tokens, |tokens| { - self.inputs.to_tokens(tokens); - if let Some(ref variadic) = self.variadic { - if !self.inputs.empty_or_trailing() { - let span = variadic.spans[0]; - Token![,](span).to_tokens(tokens); - } - variadic.to_tokens(tokens); - } - }); - self.output.to_tokens(tokens); - } - } - - impl ToTokens for TypeNever { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.bang_token.to_tokens(tokens); - } - } - - impl ToTokens for TypeTuple { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.paren_token.surround(tokens, |tokens| { - self.elems.to_tokens(tokens); - }); - } - } - - impl ToTokens for TypePath { - fn to_tokens(&self, tokens: &mut TokenStream) { - private::print_path(tokens, &self.qself, &self.path); - } - } - - impl ToTokens for TypeTraitObject { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.dyn_token.to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - } - - impl ToTokens for TypeImplTrait { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.impl_token.to_tokens(tokens); - self.bounds.to_tokens(tokens); - } - } - - impl ToTokens for TypeGroup { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.group_token.surround(tokens, |tokens| { - self.elem.to_tokens(tokens); - }); - } - } - - impl ToTokens for TypeParen { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.paren_token.surround(tokens, |tokens| { - self.elem.to_tokens(tokens); - }); - } - } - - impl ToTokens for TypeInfer { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.underscore_token.to_tokens(tokens); - } - } - - impl ToTokens for TypeMacro { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.mac.to_tokens(tokens); - } - } - - impl ToTokens for TypeVerbatim { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.tts.to_tokens(tokens); - } - } - - impl ToTokens for ReturnType { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - ReturnType::Default => {} - ReturnType::Type(ref arrow, ref ty) => { - arrow.to_tokens(tokens); - ty.to_tokens(tokens); - } - } - } - } - - impl ToTokens for BareFnArg { - fn to_tokens(&self, tokens: &mut TokenStream) { - if let Some((ref name, ref colon)) = self.name { - name.to_tokens(tokens); - colon.to_tokens(tokens); - } - self.ty.to_tokens(tokens); - } - } - - impl ToTokens for BareFnArgName { - fn to_tokens(&self, tokens: &mut TokenStream) { - match *self { - BareFnArgName::Named(ref t) => t.to_tokens(tokens), - BareFnArgName::Wild(ref t) => t.to_tokens(tokens), - } - } - } - - impl ToTokens for Abi { - fn to_tokens(&self, tokens: &mut TokenStream) { - self.extern_token.to_tokens(tokens); - self.name.to_tokens(tokens); - } - } -} diff --git a/0.15.42/tests/clone.sh b/0.15.42/tests/clone.sh deleted file mode 100755 index 39379b30..00000000 --- a/0.15.42/tests/clone.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -REV=d132f544f9d74e3cc047ef211e57eae60b78e5c5 - -set -euo pipefail -cd "$(dirname "${BASH_SOURCE[0]}")" -mkdir -p rust -touch rust/COMMIT - -if [ "$(cat rust/COMMIT)" != "$REV" ]; then - rm -rf rust - mkdir rust - curl -L "https://github.com/rust-lang/rust/archive/${REV}.tar.gz" \ - | tar xz --directory rust --strip-components 1 - echo "$REV" > rust/COMMIT -fi diff --git a/0.15.42/tests/common/eq.rs b/0.15.42/tests/common/eq.rs deleted file mode 100644 index fc12072f..00000000 --- a/0.15.42/tests/common/eq.rs +++ /dev/null @@ -1,458 +0,0 @@ -extern crate rustc_data_structures; -extern crate rustc_target; -extern crate syntax; -extern crate syntax_pos; - -use std::mem; - -use self::rustc_data_structures::sync::Lrc; -use self::rustc_data_structures::thin_vec::ThinVec; -use self::rustc_target::abi::FloatTy; -use self::rustc_target::spec::abi::Abi; -use self::syntax::ast::{ - AngleBracketedArgs, AnonConst, Arg, Arm, AsmDialect, AssocTyConstraint, AssocTyConstraintKind, - AttrId, AttrStyle, Attribute, AwaitOrigin, BareFnTy, BinOpKind, BindingMode, Block, - BlockCheckMode, CaptureBy, Constness, Crate, CrateSugar, Defaultness, EnumDef, Expr, ExprKind, - Field, FieldPat, FnDecl, FnHeader, ForeignItem, ForeignItemKind, ForeignMod, FunctionRetTy, - GenericArg, GenericArgs, GenericBound, GenericParam, GenericParamKind, Generics, GlobalAsm, - Ident, ImplItem, ImplItemKind, ImplPolarity, InlineAsm, InlineAsmOutput, IntTy, IsAsync, - IsAuto, Item, ItemKind, Label, Lifetime, Lit, LitIntType, LitKind, Local, MacDelimiter, - MacStmtStyle, Mac_, MacroDef, MethodSig, Mod, Movability, MutTy, Mutability, NodeId, - ParenthesizedArgs, Pat, PatKind, Path, PathSegment, PolyTraitRef, QSelf, RangeEnd, RangeLimits, - RangeSyntax, Stmt, StmtKind, StrStyle, StructField, TraitBoundModifier, TraitItem, - TraitItemKind, TraitObjectSyntax, TraitRef, Ty, TyKind, UintTy, UnOp, UnsafeSource, Unsafety, - UseTree, UseTreeKind, VariantData, Variant_, VisibilityKind, WhereBoundPredicate, WhereClause, - WhereEqPredicate, WherePredicate, WhereRegionPredicate, -}; -use self::syntax::parse::lexer::comments; -use self::syntax::parse::token::{self, DelimToken, Token, TokenKind}; -use self::syntax::ptr::P; -use self::syntax::source_map::Spanned; -use self::syntax::symbol::{sym, Symbol}; -use self::syntax::tokenstream::{DelimSpan, TokenStream, TokenTree}; -use self::syntax_pos::{Span, SyntaxContext, DUMMY_SP}; - -pub trait SpanlessEq { - fn eq(&self, other: &Self) -> bool; -} - -impl<T: SpanlessEq> SpanlessEq for P<T> { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&**self, &**other) - } -} - -impl<T: SpanlessEq> SpanlessEq for Lrc<T> { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&**self, &**other) - } -} - -impl<T: SpanlessEq> SpanlessEq for Option<T> { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (None, None) => true, - (Some(this), Some(other)) => SpanlessEq::eq(this, other), - _ => false, - } - } -} - -impl<T: SpanlessEq> SpanlessEq for Vec<T> { - fn eq(&self, other: &Self) -> bool { - self.len() == other.len() && self.iter().zip(other).all(|(a, b)| SpanlessEq::eq(a, b)) - } -} - -impl<T: SpanlessEq> SpanlessEq for ThinVec<T> { - fn eq(&self, other: &Self) -> bool { - self.len() == other.len() - && self - .iter() - .zip(other.iter()) - .all(|(a, b)| SpanlessEq::eq(a, b)) - } -} - -impl<T: SpanlessEq> SpanlessEq for Spanned<T> { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&self.node, &other.node) - } -} - -impl<A: SpanlessEq, B: SpanlessEq> SpanlessEq for (A, B) { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&self.0, &other.0) && SpanlessEq::eq(&self.1, &other.1) - } -} - -impl<A: SpanlessEq, B: SpanlessEq, C: SpanlessEq> SpanlessEq for (A, B, C) { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&self.0, &other.0) - && SpanlessEq::eq(&self.1, &other.1) - && SpanlessEq::eq(&self.2, &other.2) - } -} - -macro_rules! spanless_eq_true { - ($name:ident) => { - impl SpanlessEq for $name { - fn eq(&self, _other: &Self) -> bool { - true - } - } - }; -} - -spanless_eq_true!(Span); -spanless_eq_true!(DelimSpan); -spanless_eq_true!(AttrId); -spanless_eq_true!(NodeId); -spanless_eq_true!(SyntaxContext); - -macro_rules! spanless_eq_partial_eq { - ($name:ident) => { - impl SpanlessEq for $name { - fn eq(&self, other: &Self) -> bool { - PartialEq::eq(self, other) - } - } - }; -} - -spanless_eq_partial_eq!(bool); -spanless_eq_partial_eq!(u8); -spanless_eq_partial_eq!(u16); -spanless_eq_partial_eq!(u128); -spanless_eq_partial_eq!(usize); -spanless_eq_partial_eq!(char); -spanless_eq_partial_eq!(Symbol); -spanless_eq_partial_eq!(Abi); -spanless_eq_partial_eq!(DelimToken); - -macro_rules! spanless_eq_struct { - { - $name:ident; - $([$field:ident $other:ident])* - $(![$ignore:ident])* - } => { - impl SpanlessEq for $name { - fn eq(&self, other: &Self) -> bool { - let $name { $($field,)* $($ignore: _,)* } = self; - let $name { $($field: $other,)* $($ignore: _,)* } = other; - $(SpanlessEq::eq($field, $other))&&* - } - } - }; - - { - $name:ident; - $([$field:ident $other:ident])* - $next:ident - $($rest:ident)* - $(!$ignore:ident)* - } => { - spanless_eq_struct! { - $name; - $([$field $other])* - [$next other] - $($rest)* - $(!$ignore)* - } - }; - - { - $name:ident; - $([$field:ident $other:ident])* - $(![$ignore:ident])* - !$next:ident - $(!$rest:ident)* - } => { - spanless_eq_struct! { - $name; - $([$field $other])* - $(![$ignore])* - ![$next] - $(!$rest)* - } - }; -} - -macro_rules! spanless_eq_enum { - { - $name:ident; - $([$variant:ident $([$field:tt $this:ident $other:ident])*])* - } => { - impl SpanlessEq for $name { - fn eq(&self, other: &Self) -> bool { - match self { - $( - $name::$variant { .. } => {} - )* - } - #[allow(unreachable_patterns)] - match (self, other) { - $( - ( - $name::$variant { $($field: $this),* }, - $name::$variant { $($field: $other),* }, - ) => { - true $(&& SpanlessEq::eq($this, $other))* - } - )* - _ => false, - } - } - } - }; - - { - $name:ident; - $([$variant:ident $($fields:tt)*])* - $next:ident [$($named:tt)*] ( $i:tt $($field:tt)* ) - $($rest:tt)* - } => { - spanless_eq_enum! { - $name; - $([$variant $($fields)*])* - $next [$($named)* [$i this other]] ( $($field)* ) - $($rest)* - } - }; - - { - $name:ident; - $([$variant:ident $($fields:tt)*])* - $next:ident [$($named:tt)*] () - $($rest:tt)* - } => { - spanless_eq_enum! { - $name; - $([$variant $($fields)*])* - [$next $($named)*] - $($rest)* - } - }; - - { - $name:ident; - $([$variant:ident $($fields:tt)*])* - $next:ident ( $($field:tt)* ) - $($rest:tt)* - } => { - spanless_eq_enum! { - $name; - $([$variant $($fields)*])* - $next [] ( $($field)* ) - $($rest)* - } - }; - - { - $name:ident; - $([$variant:ident $($fields:tt)*])* - $next:ident - $($rest:tt)* - } => { - spanless_eq_enum! { - $name; - $([$variant $($fields)*])* - [$next] - $($rest)* - } - }; -} - -spanless_eq_struct!(AngleBracketedArgs; span args constraints); -spanless_eq_struct!(AnonConst; id value); -spanless_eq_struct!(Arg; attrs ty pat id); -spanless_eq_struct!(Arm; attrs pats guard body span); -spanless_eq_struct!(AssocTyConstraint; id ident kind span); -spanless_eq_struct!(Attribute; id style path tokens span !is_sugared_doc); -spanless_eq_struct!(BareFnTy; unsafety abi generic_params decl); -spanless_eq_struct!(Block; stmts id rules span); -spanless_eq_struct!(Crate; module attrs span); -spanless_eq_struct!(EnumDef; variants); -spanless_eq_struct!(Expr; id node span attrs); -spanless_eq_struct!(Field; ident expr span is_shorthand attrs); -spanless_eq_struct!(FieldPat; ident pat is_shorthand attrs); -spanless_eq_struct!(FnDecl; inputs output c_variadic); -spanless_eq_struct!(FnHeader; constness asyncness unsafety abi); -spanless_eq_struct!(ForeignItem; ident attrs node id span vis); -spanless_eq_struct!(ForeignMod; abi items); -spanless_eq_struct!(GenericParam; id ident attrs bounds kind); -spanless_eq_struct!(Generics; params where_clause span); -spanless_eq_struct!(GlobalAsm; asm ctxt); -spanless_eq_struct!(ImplItem; id ident vis defaultness attrs generics node span !tokens); -spanless_eq_struct!(InlineAsm; asm asm_str_style outputs inputs clobbers volatile alignstack dialect ctxt); -spanless_eq_struct!(InlineAsmOutput; constraint expr is_rw is_indirect); -spanless_eq_struct!(Item; ident attrs id node vis span !tokens); -spanless_eq_struct!(Label; ident); -spanless_eq_struct!(Lifetime; id ident); -spanless_eq_struct!(Lit; token node span); -spanless_eq_struct!(Local; pat ty init id span attrs); -spanless_eq_struct!(Mac_; path delim tts); -spanless_eq_struct!(MacroDef; tokens legacy); -spanless_eq_struct!(MethodSig; header decl); -spanless_eq_struct!(Mod; inner items inline); -spanless_eq_struct!(MutTy; ty mutbl); -spanless_eq_struct!(ParenthesizedArgs; span inputs output); -spanless_eq_struct!(Pat; id node span); -spanless_eq_struct!(Path; span segments); -spanless_eq_struct!(PathSegment; ident id args); -spanless_eq_struct!(PolyTraitRef; bound_generic_params trait_ref span); -spanless_eq_struct!(QSelf; ty path_span position); -spanless_eq_struct!(Stmt; id node span); -spanless_eq_struct!(StructField; span ident vis id ty attrs); -spanless_eq_struct!(Token; kind span); -spanless_eq_struct!(TraitItem; id ident attrs generics node span !tokens); -spanless_eq_struct!(TraitRef; path ref_id); -spanless_eq_struct!(Ty; id node span); -spanless_eq_struct!(UseTree; prefix kind span); -spanless_eq_struct!(Variant_; ident attrs id data disr_expr); -spanless_eq_struct!(WhereBoundPredicate; span bound_generic_params bounded_ty bounds); -spanless_eq_struct!(WhereClause; predicates span); -spanless_eq_struct!(WhereEqPredicate; id span lhs_ty rhs_ty); -spanless_eq_struct!(WhereRegionPredicate; span lifetime bounds); -spanless_eq_enum!(AsmDialect; Att Intel); -spanless_eq_enum!(AssocTyConstraintKind; Equality(ty) Bound(bounds)); -spanless_eq_enum!(AttrStyle; Outer Inner); -spanless_eq_enum!(AwaitOrigin; FieldLike MacroLike); -spanless_eq_enum!(BinOpKind; Add Sub Mul Div Rem And Or BitXor BitAnd BitOr Shl Shr Eq Lt Le Ne Ge Gt); -spanless_eq_enum!(BindingMode; ByRef(0) ByValue(0)); -spanless_eq_enum!(BlockCheckMode; Default Unsafe(0)); -spanless_eq_enum!(CaptureBy; Value Ref); -spanless_eq_enum!(Constness; Const NotConst); -spanless_eq_enum!(CrateSugar; PubCrate JustCrate); -spanless_eq_enum!(Defaultness; Default Final); -spanless_eq_enum!(FloatTy; F32 F64); -spanless_eq_enum!(ForeignItemKind; Fn(0 1) Static(0 1) Ty Macro(0)); -spanless_eq_enum!(FunctionRetTy; Default(0) Ty(0)); -spanless_eq_enum!(GenericArg; Lifetime(0) Type(0) Const(0)); -spanless_eq_enum!(GenericArgs; AngleBracketed(0) Parenthesized(0)); -spanless_eq_enum!(GenericBound; Trait(0 1) Outlives(0)); -spanless_eq_enum!(GenericParamKind; Lifetime Type(default) Const(ty)); -spanless_eq_enum!(ImplItemKind; Const(0 1) Method(0 1) Type(0) Existential(0) Macro(0)); -spanless_eq_enum!(ImplPolarity; Positive Negative); -spanless_eq_enum!(IntTy; Isize I8 I16 I32 I64 I128); -spanless_eq_enum!(IsAsync; Async(closure_id return_impl_trait_id) NotAsync); -spanless_eq_enum!(IsAuto; Yes No); -spanless_eq_enum!(LitIntType; Signed(0) Unsigned(0) Unsuffixed); -spanless_eq_enum!(MacDelimiter; Parenthesis Bracket Brace); -spanless_eq_enum!(MacStmtStyle; Semicolon Braces NoBraces); -spanless_eq_enum!(Movability; Static Movable); -spanless_eq_enum!(Mutability; Mutable Immutable); -spanless_eq_enum!(RangeEnd; Included(0) Excluded); -spanless_eq_enum!(RangeLimits; HalfOpen Closed); -spanless_eq_enum!(StmtKind; Local(0) Item(0) Expr(0) Semi(0) Mac(0)); -spanless_eq_enum!(StrStyle; Cooked Raw(0)); -spanless_eq_enum!(TokenTree; Token(0) Delimited(0 1 2)); -spanless_eq_enum!(TraitBoundModifier; None Maybe); -spanless_eq_enum!(TraitItemKind; Const(0 1) Method(0 1) Type(0 1) Macro(0)); -spanless_eq_enum!(TraitObjectSyntax; Dyn None); -spanless_eq_enum!(UintTy; Usize U8 U16 U32 U64 U128); -spanless_eq_enum!(UnOp; Deref Not Neg); -spanless_eq_enum!(UnsafeSource; CompilerGenerated UserProvided); -spanless_eq_enum!(Unsafety; Unsafe Normal); -spanless_eq_enum!(UseTreeKind; Simple(0 1 2) Nested(0) Glob); -spanless_eq_enum!(VariantData; Struct(0 1) Tuple(0 1) Unit(0)); -spanless_eq_enum!(VisibilityKind; Public Crate(0) Restricted(path id) Inherited); -spanless_eq_enum!(WherePredicate; BoundPredicate(0) RegionPredicate(0) EqPredicate(0)); -spanless_eq_enum!(ExprKind; Box(0) Array(0) Call(0 1) MethodCall(0 1) Tup(0) - Binary(0 1 2) Unary(0 1) Lit(0) Cast(0 1) Type(0 1) Let(0 1) If(0 1 2) - While(0 1 2) ForLoop(0 1 2 3) Loop(0 1) Match(0 1) Closure(0 1 2 3 4 5) - Block(0 1) Async(0 1 2) Await(0 1) TryBlock(0) Assign(0 1) AssignOp(0 1 2) - Field(0 1) Index(0 1) Range(0 1 2) Path(0 1) AddrOf(0 1) Break(0 1) - Continue(0) Ret(0) InlineAsm(0) Mac(0) Struct(0 1 2) Repeat(0 1) Paren(0) - Try(0) Yield(0) Err); -spanless_eq_enum!(ItemKind; ExternCrate(0) Use(0) Static(0 1 2) Const(0 1) - Fn(0 1 2 3) Mod(0) ForeignMod(0) GlobalAsm(0) Ty(0 1) Existential(0 1) - Enum(0 1) Struct(0 1) Union(0 1) Trait(0 1 2 3 4) TraitAlias(0 1) - Impl(0 1 2 3 4 5 6) Mac(0) MacroDef(0)); -spanless_eq_enum!(LitKind; Str(0 1) ByteStr(0) Byte(0) Char(0) Int(0 1) - Float(0 1) FloatUnsuffixed(0) Bool(0) Err(0)); -spanless_eq_enum!(PatKind; Wild Ident(0 1 2) Struct(0 1 2) TupleStruct(0 1 2) - Path(0 1) Tuple(0 1) Box(0) Ref(0 1) Lit(0) Range(0 1 2) Slice(0 1 2) - Paren(0) Mac(0)); -spanless_eq_enum!(TyKind; Slice(0) Array(0 1) Ptr(0) Rptr(0 1) BareFn(0) Never - Tup(0) Path(0 1) TraitObject(0 1) ImplTrait(0 1) Paren(0) Typeof(0) Infer - ImplicitSelf Mac(0) Err CVarArgs); - -impl SpanlessEq for Ident { - fn eq(&self, other: &Self) -> bool { - self.as_str() == other.as_str() - } -} - -// Give up on comparing literals inside of macros because there are so many -// equivalent representations of the same literal; they are tested elsewhere -impl SpanlessEq for token::Lit { - fn eq(&self, other: &Self) -> bool { - mem::discriminant(self) == mem::discriminant(other) - } -} - -impl SpanlessEq for RangeSyntax { - fn eq(&self, _other: &Self) -> bool { - match self { - RangeSyntax::DotDotDot | RangeSyntax::DotDotEq => true, - } - } -} - -impl SpanlessEq for TokenKind { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (TokenKind::Literal(this), TokenKind::Literal(other)) => SpanlessEq::eq(this, other), - (TokenKind::DotDotEq, _) | (TokenKind::DotDotDot, _) => match other { - TokenKind::DotDotEq | TokenKind::DotDotDot => true, - _ => false, - }, - _ => self == other, - } - } -} - -impl SpanlessEq for TokenStream { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&expand_tts(self), &expand_tts(other)) - } -} - -fn expand_tts(tts: &TokenStream) -> Vec<TokenTree> { - let mut tokens = Vec::new(); - for tt in tts.clone().into_trees() { - let c = match tt { - TokenTree::Token(Token { - kind: TokenKind::DocComment(c), - .. - }) => c, - _ => { - tokens.push(tt); - continue; - } - }; - let contents = comments::strip_doc_comment_decoration(&c.as_str()); - let style = comments::doc_comment_style(&c.as_str()); - tokens.push(TokenTree::token(TokenKind::Pound, DUMMY_SP)); - if style == AttrStyle::Inner { - tokens.push(TokenTree::token(TokenKind::Not, DUMMY_SP)); - } - let lit = token::Lit { - kind: token::LitKind::Str, - symbol: Symbol::intern(&contents), - suffix: None, - }; - let tts = vec![ - TokenTree::token(TokenKind::Ident(sym::doc, false), DUMMY_SP), - TokenTree::token(TokenKind::Eq, DUMMY_SP), - TokenTree::token(TokenKind::Literal(lit), DUMMY_SP), - ]; - tokens.push(TokenTree::Delimited( - DelimSpan::dummy(), - DelimToken::Bracket, - tts.into_iter().collect::<TokenStream>().into(), - )); - } - tokens -} diff --git a/0.15.42/tests/common/mod.rs b/0.15.42/tests/common/mod.rs deleted file mode 100644 index 8b784bee..00000000 --- a/0.15.42/tests/common/mod.rs +++ /dev/null @@ -1,14 +0,0 @@ -#![allow(dead_code)] - -use std::env; - -pub mod eq; -pub mod parse; - -/// Read the `ABORT_AFTER_FAILURE` environment variable, and parse it. -pub fn abort_after() -> usize { - match env::var("ABORT_AFTER_FAILURE") { - Ok(s) => s.parse().expect("failed to parse ABORT_AFTER_FAILURE"), - Err(_) => usize::max_value(), - } -} diff --git a/0.15.42/tests/common/parse.rs b/0.15.42/tests/common/parse.rs deleted file mode 100644 index 41d192f6..00000000 --- a/0.15.42/tests/common/parse.rs +++ /dev/null @@ -1,49 +0,0 @@ -extern crate proc_macro2; -extern crate syn; -extern crate syntax; -extern crate syntax_pos; - -use self::syntax::ast; -use self::syntax::parse::{self, ParseSess}; -use self::syntax::ptr::P; -use self::syntax::source_map::FilePathMapping; -use self::syntax_pos::FileName; - -use std::panic; - -pub fn libsyntax_expr(input: &str) -> Option<P<ast::Expr>> { - match panic::catch_unwind(|| { - let sess = ParseSess::new(FilePathMapping::empty()); - sess.span_diagnostic.set_continue_after_error(false); - let e = parse::new_parser_from_source_str( - &sess, - FileName::Custom("test_precedence".to_string()), - input.to_string(), - ) - .parse_expr(); - match e { - Ok(expr) => Some(expr), - Err(mut diagnostic) => { - diagnostic.emit(); - None - } - } - }) { - Ok(Some(e)) => Some(e), - Ok(None) => None, - Err(_) => { - errorf!("libsyntax panicked\n"); - None - } - } -} - -pub fn syn_expr(input: &str) -> Option<syn::Expr> { - match syn::parse_str(input) { - Ok(e) => Some(e), - Err(msg) => { - errorf!("syn failed to parse\n{:?}\n", msg); - None - } - } -} diff --git a/0.15.42/tests/debug/gen.rs b/0.15.42/tests/debug/gen.rs deleted file mode 100644 index f055126a..00000000 --- a/0.15.42/tests/debug/gen.rs +++ /dev/null @@ -1,5934 +0,0 @@ -// This file is @generated by syn-internal-codegen. -// It is not intended for manual editing. - -use super::{Lite, RefCast}; -use std::fmt::{self, Debug}; -impl Debug for Lite<syn::Abi> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Abi"); - if let Some(val) = &_val.name { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::LitStr); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("name", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::AngleBracketedGenericArguments> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("AngleBracketedGenericArguments"); - if let Some(val) = &_val.colon2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon2_token", Print::ref_cast(val)); - } - if !_val.args.is_empty() { - formatter.field("args", Lite(&_val.args)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ArgCaptured> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ArgCaptured"); - formatter.field("pat", Lite(&_val.pat)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::ArgSelf> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ArgSelf"); - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ArgSelfRef> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ArgSelfRef"); - if let Some(val) = &_val.lifetime { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Lifetime); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("lifetime", Print::ref_cast(val)); - } - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::Arm> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Arm"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.leading_vert { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Or); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("leading_vert", Print::ref_cast(val)); - } - if !_val.pats.is_empty() { - formatter.field("pats", Lite(&_val.pats)); - } - if let Some(val) = &_val.guard { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::If, Box<syn::Expr>)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("guard", Print::ref_cast(val)); - } - formatter.field("body", Lite(&_val.body)); - if let Some(val) = &_val.comma { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Comma); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("comma", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::AttrStyle> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::AttrStyle::Outer => formatter.write_str("Outer"), - syn::AttrStyle::Inner(_val) => { - formatter.write_str("Inner")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::Attribute> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Attribute"); - formatter.field("style", Lite(&_val.style)); - formatter.field("path", Lite(&_val.path)); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } -} -impl Debug for Lite<syn::BareFnArg> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("BareFnArg"); - if let Some(val) = &_val.name { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::BareFnArgName, syn::token::Colon)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.0), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("name", Print::ref_cast(val)); - } - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::BareFnArgName> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::BareFnArgName::Named(_val) => { - formatter.write_str("Named")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::BareFnArgName::Wild(_val) => { - formatter.write_str("Wild")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::BinOp> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::BinOp::Add(_val) => { - formatter.write_str("Add")?; - Ok(()) - } - syn::BinOp::Sub(_val) => { - formatter.write_str("Sub")?; - Ok(()) - } - syn::BinOp::Mul(_val) => { - formatter.write_str("Mul")?; - Ok(()) - } - syn::BinOp::Div(_val) => { - formatter.write_str("Div")?; - Ok(()) - } - syn::BinOp::Rem(_val) => { - formatter.write_str("Rem")?; - Ok(()) - } - syn::BinOp::And(_val) => { - formatter.write_str("And")?; - Ok(()) - } - syn::BinOp::Or(_val) => { - formatter.write_str("Or")?; - Ok(()) - } - syn::BinOp::BitXor(_val) => { - formatter.write_str("BitXor")?; - Ok(()) - } - syn::BinOp::BitAnd(_val) => { - formatter.write_str("BitAnd")?; - Ok(()) - } - syn::BinOp::BitOr(_val) => { - formatter.write_str("BitOr")?; - Ok(()) - } - syn::BinOp::Shl(_val) => { - formatter.write_str("Shl")?; - Ok(()) - } - syn::BinOp::Shr(_val) => { - formatter.write_str("Shr")?; - Ok(()) - } - syn::BinOp::Eq(_val) => { - formatter.write_str("Eq")?; - Ok(()) - } - syn::BinOp::Lt(_val) => { - formatter.write_str("Lt")?; - Ok(()) - } - syn::BinOp::Le(_val) => { - formatter.write_str("Le")?; - Ok(()) - } - syn::BinOp::Ne(_val) => { - formatter.write_str("Ne")?; - Ok(()) - } - syn::BinOp::Ge(_val) => { - formatter.write_str("Ge")?; - Ok(()) - } - syn::BinOp::Gt(_val) => { - formatter.write_str("Gt")?; - Ok(()) - } - syn::BinOp::AddEq(_val) => { - formatter.write_str("AddEq")?; - Ok(()) - } - syn::BinOp::SubEq(_val) => { - formatter.write_str("SubEq")?; - Ok(()) - } - syn::BinOp::MulEq(_val) => { - formatter.write_str("MulEq")?; - Ok(()) - } - syn::BinOp::DivEq(_val) => { - formatter.write_str("DivEq")?; - Ok(()) - } - syn::BinOp::RemEq(_val) => { - formatter.write_str("RemEq")?; - Ok(()) - } - syn::BinOp::BitXorEq(_val) => { - formatter.write_str("BitXorEq")?; - Ok(()) - } - syn::BinOp::BitAndEq(_val) => { - formatter.write_str("BitAndEq")?; - Ok(()) - } - syn::BinOp::BitOrEq(_val) => { - formatter.write_str("BitOrEq")?; - Ok(()) - } - syn::BinOp::ShlEq(_val) => { - formatter.write_str("ShlEq")?; - Ok(()) - } - syn::BinOp::ShrEq(_val) => { - formatter.write_str("ShrEq")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::Binding> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Binding"); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::Block> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Block"); - if !_val.stmts.is_empty() { - formatter.field("stmts", Lite(&_val.stmts)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::BoundLifetimes> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("BoundLifetimes"); - if !_val.lifetimes.is_empty() { - formatter.field("lifetimes", Lite(&_val.lifetimes)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ConstParam> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ConstParam"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - if let Some(val) = &_val.eq_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Eq); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("eq_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.default { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Expr); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("default", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::Constraint> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Constraint"); - formatter.field("ident", Lite(&_val.ident)); - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::Data> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Data::Struct(_val) => { - let mut formatter = formatter.debug_struct("Data::Struct"); - formatter.field("fields", Lite(&_val.fields)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Data::Enum(_val) => { - let mut formatter = formatter.debug_struct("Data::Enum"); - if !_val.variants.is_empty() { - formatter.field("variants", Lite(&_val.variants)); - } - formatter.finish() - } - syn::Data::Union(_val) => { - let mut formatter = formatter.debug_struct("Data::Union"); - formatter.field("fields", Lite(&_val.fields)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::DataEnum> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("DataEnum"); - if !_val.variants.is_empty() { - formatter.field("variants", Lite(&_val.variants)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::DataStruct> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("DataStruct"); - formatter.field("fields", Lite(&_val.fields)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::DataUnion> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("DataUnion"); - formatter.field("fields", Lite(&_val.fields)); - formatter.finish() - } -} -impl Debug for Lite<syn::DeriveInput> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("DeriveInput"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - formatter.field("data", Lite(&_val.data)); - formatter.finish() - } -} -impl Debug for Lite<syn::Expr> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Expr::Box(_val) => { - let mut formatter = formatter.debug_struct("Expr::Box"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Expr::InPlace(_val) => { - let mut formatter = formatter.debug_struct("Expr::InPlace"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("place", Lite(&_val.place)); - formatter.field("value", Lite(&_val.value)); - formatter.finish() - } - syn::Expr::Array(_val) => { - let mut formatter = formatter.debug_struct("Expr::Array"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if !_val.elems.is_empty() { - formatter.field("elems", Lite(&_val.elems)); - } - formatter.finish() - } - syn::Expr::Call(_val) => { - let mut formatter = formatter.debug_struct("Expr::Call"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("func", Lite(&_val.func)); - if !_val.args.is_empty() { - formatter.field("args", Lite(&_val.args)); - } - formatter.finish() - } - syn::Expr::MethodCall(_val) => { - let mut formatter = formatter.debug_struct("Expr::MethodCall"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("receiver", Lite(&_val.receiver)); - formatter.field("method", Lite(&_val.method)); - if let Some(val) = &_val.turbofish { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::MethodTurbofish); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("turbofish", Print::ref_cast(val)); - } - if !_val.args.is_empty() { - formatter.field("args", Lite(&_val.args)); - } - formatter.finish() - } - syn::Expr::Tuple(_val) => { - let mut formatter = formatter.debug_struct("Expr::Tuple"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if !_val.elems.is_empty() { - formatter.field("elems", Lite(&_val.elems)); - } - formatter.finish() - } - syn::Expr::Binary(_val) => { - let mut formatter = formatter.debug_struct("Expr::Binary"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("left", Lite(&_val.left)); - formatter.field("op", Lite(&_val.op)); - formatter.field("right", Lite(&_val.right)); - formatter.finish() - } - syn::Expr::Unary(_val) => { - let mut formatter = formatter.debug_struct("Expr::Unary"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("op", Lite(&_val.op)); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Expr::Lit(_val) => { - let mut formatter = formatter.debug_struct("Expr::Lit"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("lit", Lite(&_val.lit)); - formatter.finish() - } - syn::Expr::Cast(_val) => { - let mut formatter = formatter.debug_struct("Expr::Cast"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } - syn::Expr::Type(_val) => { - let mut formatter = formatter.debug_struct("Expr::Type"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } - syn::Expr::Let(_val) => { - let mut formatter = formatter.debug_struct("Expr::Let"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if !_val.pats.is_empty() { - formatter.field("pats", Lite(&_val.pats)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Expr::If(_val) => { - let mut formatter = formatter.debug_struct("Expr::If"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("cond", Lite(&_val.cond)); - formatter.field("then_branch", Lite(&_val.then_branch)); - if let Some(val) = &_val.else_branch { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Else, Box<syn::Expr>)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("else_branch", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Expr::While(_val) => { - let mut formatter = formatter.debug_struct("Expr::While"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Label); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.field("cond", Lite(&_val.cond)); - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } - syn::Expr::ForLoop(_val) => { - let mut formatter = formatter.debug_struct("Expr::ForLoop"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Label); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.field("pat", Lite(&_val.pat)); - formatter.field("expr", Lite(&_val.expr)); - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } - syn::Expr::Loop(_val) => { - let mut formatter = formatter.debug_struct("Expr::Loop"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Label); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } - syn::Expr::Match(_val) => { - let mut formatter = formatter.debug_struct("Expr::Match"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - if !_val.arms.is_empty() { - formatter.field("arms", Lite(&_val.arms)); - } - formatter.finish() - } - syn::Expr::Closure(_val) => { - let mut formatter = formatter.debug_struct("Expr::Closure"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.asyncness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Async); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("asyncness", Print::ref_cast(val)); - } - if let Some(val) = &_val.movability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Static); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("movability", Print::ref_cast(val)); - } - if let Some(val) = &_val.capture { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Move); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("capture", Print::ref_cast(val)); - } - if !_val.inputs.is_empty() { - formatter.field("inputs", Lite(&_val.inputs)); - } - formatter.field("output", Lite(&_val.output)); - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } - syn::Expr::Unsafe(_val) => { - let mut formatter = formatter.debug_struct("Expr::Unsafe"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } - syn::Expr::Block(_val) => { - let mut formatter = formatter.debug_struct("Expr::Block"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Label); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } - syn::Expr::Assign(_val) => { - let mut formatter = formatter.debug_struct("Expr::Assign"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("left", Lite(&_val.left)); - formatter.field("right", Lite(&_val.right)); - formatter.finish() - } - syn::Expr::AssignOp(_val) => { - let mut formatter = formatter.debug_struct("Expr::AssignOp"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("left", Lite(&_val.left)); - formatter.field("op", Lite(&_val.op)); - formatter.field("right", Lite(&_val.right)); - formatter.finish() - } - syn::Expr::Field(_val) => { - let mut formatter = formatter.debug_struct("Expr::Field"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("base", Lite(&_val.base)); - formatter.field("member", Lite(&_val.member)); - formatter.finish() - } - syn::Expr::Index(_val) => { - let mut formatter = formatter.debug_struct("Expr::Index"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.field("index", Lite(&_val.index)); - formatter.finish() - } - syn::Expr::Range(_val) => { - let mut formatter = formatter.debug_struct("Expr::Range"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.from { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("from", Print::ref_cast(val)); - } - formatter.field("limits", Lite(&_val.limits)); - if let Some(val) = &_val.to { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("to", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Expr::Path(_val) => { - let mut formatter = formatter.debug_struct("Expr::Path"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.qself { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::QSelf); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("qself", Print::ref_cast(val)); - } - formatter.field("path", Lite(&_val.path)); - formatter.finish() - } - syn::Expr::Reference(_val) => { - let mut formatter = formatter.debug_struct("Expr::Reference"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Expr::Break(_val) => { - let mut formatter = formatter.debug_struct("Expr::Break"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Lifetime); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - if let Some(val) = &_val.expr { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("expr", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Expr::Continue(_val) => { - let mut formatter = formatter.debug_struct("Expr::Continue"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Lifetime); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Expr::Return(_val) => { - let mut formatter = formatter.debug_struct("Expr::Return"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.expr { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("expr", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Expr::Macro(_val) => { - let mut formatter = formatter.debug_struct("Expr::Macro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("mac", Lite(&_val.mac)); - formatter.finish() - } - syn::Expr::Struct(_val) => { - let mut formatter = formatter.debug_struct("Expr::Struct"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("path", Lite(&_val.path)); - if !_val.fields.is_empty() { - formatter.field("fields", Lite(&_val.fields)); - } - if let Some(val) = &_val.dot2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dot2_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.rest { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("rest", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Expr::Repeat(_val) => { - let mut formatter = formatter.debug_struct("Expr::Repeat"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.field("len", Lite(&_val.len)); - formatter.finish() - } - syn::Expr::Paren(_val) => { - let mut formatter = formatter.debug_struct("Expr::Paren"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Expr::Group(_val) => { - let mut formatter = formatter.debug_struct("Expr::Group"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Expr::Try(_val) => { - let mut formatter = formatter.debug_struct("Expr::Try"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Expr::Async(_val) => { - let mut formatter = formatter.debug_struct("Expr::Async"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.capture { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Move); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("capture", Print::ref_cast(val)); - } - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } - syn::Expr::TryBlock(_val) => { - let mut formatter = formatter.debug_struct("Expr::TryBlock"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } - syn::Expr::Yield(_val) => { - let mut formatter = formatter.debug_struct("Expr::Yield"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.expr { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("expr", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Expr::Verbatim(_val) => { - let mut formatter = formatter.debug_struct("Expr::Verbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::ExprArray> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprArray"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if !_val.elems.is_empty() { - formatter.field("elems", Lite(&_val.elems)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprAssign> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprAssign"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("left", Lite(&_val.left)); - formatter.field("right", Lite(&_val.right)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprAssignOp> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprAssignOp"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("left", Lite(&_val.left)); - formatter.field("op", Lite(&_val.op)); - formatter.field("right", Lite(&_val.right)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprAsync> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprAsync"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.capture { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Move); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("capture", Print::ref_cast(val)); - } - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprBinary> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprBinary"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("left", Lite(&_val.left)); - formatter.field("op", Lite(&_val.op)); - formatter.field("right", Lite(&_val.right)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprBlock> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprBlock"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Label); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprBox> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprBox"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprBreak> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprBreak"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Lifetime); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - if let Some(val) = &_val.expr { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("expr", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprCall> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprCall"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("func", Lite(&_val.func)); - if !_val.args.is_empty() { - formatter.field("args", Lite(&_val.args)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprCast> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprCast"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprClosure> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprClosure"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.asyncness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Async); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("asyncness", Print::ref_cast(val)); - } - if let Some(val) = &_val.movability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Static); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("movability", Print::ref_cast(val)); - } - if let Some(val) = &_val.capture { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Move); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("capture", Print::ref_cast(val)); - } - if !_val.inputs.is_empty() { - formatter.field("inputs", Lite(&_val.inputs)); - } - formatter.field("output", Lite(&_val.output)); - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprContinue> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprContinue"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Lifetime); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprField> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprField"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("base", Lite(&_val.base)); - formatter.field("member", Lite(&_val.member)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprForLoop> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprForLoop"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Label); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.field("pat", Lite(&_val.pat)); - formatter.field("expr", Lite(&_val.expr)); - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprGroup> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprGroup"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprIf> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprIf"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("cond", Lite(&_val.cond)); - formatter.field("then_branch", Lite(&_val.then_branch)); - if let Some(val) = &_val.else_branch { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Else, Box<syn::Expr>)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("else_branch", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprInPlace> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprInPlace"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("place", Lite(&_val.place)); - formatter.field("value", Lite(&_val.value)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprIndex> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprIndex"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.field("index", Lite(&_val.index)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprLet> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprLet"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if !_val.pats.is_empty() { - formatter.field("pats", Lite(&_val.pats)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprLit> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprLit"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("lit", Lite(&_val.lit)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprLoop> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprLoop"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Label); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprMacro> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprMacro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("mac", Lite(&_val.mac)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprMatch> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprMatch"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - if !_val.arms.is_empty() { - formatter.field("arms", Lite(&_val.arms)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprMethodCall> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprMethodCall"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("receiver", Lite(&_val.receiver)); - formatter.field("method", Lite(&_val.method)); - if let Some(val) = &_val.turbofish { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::MethodTurbofish); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("turbofish", Print::ref_cast(val)); - } - if !_val.args.is_empty() { - formatter.field("args", Lite(&_val.args)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprParen> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprParen"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprPath> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprPath"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.qself { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::QSelf); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("qself", Print::ref_cast(val)); - } - formatter.field("path", Lite(&_val.path)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprRange> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprRange"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.from { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("from", Print::ref_cast(val)); - } - formatter.field("limits", Lite(&_val.limits)); - if let Some(val) = &_val.to { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("to", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprReference> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprReference"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprRepeat> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprRepeat"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.field("len", Lite(&_val.len)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprReturn> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprReturn"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.expr { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("expr", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprStruct> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprStruct"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("path", Lite(&_val.path)); - if !_val.fields.is_empty() { - formatter.field("fields", Lite(&_val.fields)); - } - if let Some(val) = &_val.dot2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dot2_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.rest { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("rest", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprTry> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprTry"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprTryBlock> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprTryBlock"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprTuple> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprTuple"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if !_val.elems.is_empty() { - formatter.field("elems", Lite(&_val.elems)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ExprType> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprType"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprUnary> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprUnary"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("op", Lite(&_val.op)); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprUnsafe> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprUnsafe"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprVerbatim> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprVerbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprWhile> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprWhile"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.label { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Label); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("label", Print::ref_cast(val)); - } - formatter.field("cond", Lite(&_val.cond)); - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } -} -impl Debug for Lite<syn::ExprYield> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ExprYield"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.expr { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Expr>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("expr", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::Field> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Field"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.ident { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(proc_macro2::Ident); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("ident", Print::ref_cast(val)); - } - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::FieldPat> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("FieldPat"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("member", Lite(&_val.member)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - formatter.field("pat", Lite(&_val.pat)); - formatter.finish() - } -} -impl Debug for Lite<syn::FieldValue> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("FieldValue"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("member", Lite(&_val.member)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::Fields> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Fields::Named(_val) => { - let mut formatter = formatter.debug_struct("Fields::Named"); - if !_val.named.is_empty() { - formatter.field("named", Lite(&_val.named)); - } - formatter.finish() - } - syn::Fields::Unnamed(_val) => { - let mut formatter = formatter.debug_struct("Fields::Unnamed"); - if !_val.unnamed.is_empty() { - formatter.field("unnamed", Lite(&_val.unnamed)); - } - formatter.finish() - } - syn::Fields::Unit => formatter.write_str("Unit"), - } - } -} -impl Debug for Lite<syn::FieldsNamed> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("FieldsNamed"); - if !_val.named.is_empty() { - formatter.field("named", Lite(&_val.named)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::FieldsUnnamed> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("FieldsUnnamed"); - if !_val.unnamed.is_empty() { - formatter.field("unnamed", Lite(&_val.unnamed)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::File> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("File"); - if let Some(val) = &_val.shebang { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(String); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("shebang", Print::ref_cast(val)); - } - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if !_val.items.is_empty() { - formatter.field("items", Lite(&_val.items)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::FnArg> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::FnArg::SelfRef(_val) => { - formatter.write_str("SelfRef")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::FnArg::SelfValue(_val) => { - formatter.write_str("SelfValue")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::FnArg::Captured(_val) => { - formatter.write_str("Captured")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::FnArg::Inferred(_val) => { - formatter.write_str("Inferred")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::FnArg::Ignored(_val) => { - formatter.write_str("Ignored")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::FnDecl> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("FnDecl"); - formatter.field("generics", Lite(&_val.generics)); - if !_val.inputs.is_empty() { - formatter.field("inputs", Lite(&_val.inputs)); - } - if let Some(val) = &_val.variadic { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot3); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("variadic", Print::ref_cast(val)); - } - formatter.field("output", Lite(&_val.output)); - formatter.finish() - } -} -impl Debug for Lite<syn::ForeignItem> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::ForeignItem::Fn(_val) => { - let mut formatter = formatter.debug_struct("ForeignItem::Fn"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("decl", Lite(&_val.decl)); - formatter.finish() - } - syn::ForeignItem::Static(_val) => { - let mut formatter = formatter.debug_struct("ForeignItem::Static"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } - syn::ForeignItem::Type(_val) => { - let mut formatter = formatter.debug_struct("ForeignItem::Type"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.finish() - } - syn::ForeignItem::Macro(_val) => { - let mut formatter = formatter.debug_struct("ForeignItem::Macro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("mac", Lite(&_val.mac)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } - syn::ForeignItem::Verbatim(_val) => { - let mut formatter = formatter.debug_struct("ForeignItem::Verbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::ForeignItemFn> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ForeignItemFn"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("decl", Lite(&_val.decl)); - formatter.finish() - } -} -impl Debug for Lite<syn::ForeignItemMacro> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ForeignItemMacro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("mac", Lite(&_val.mac)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ForeignItemStatic> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ForeignItemStatic"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::ForeignItemType> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ForeignItemType"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.finish() - } -} -impl Debug for Lite<syn::ForeignItemVerbatim> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ForeignItemVerbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } -} -impl Debug for Lite<syn::GenericArgument> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::GenericArgument::Lifetime(_val) => { - formatter.write_str("Lifetime")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::GenericArgument::Type(_val) => { - formatter.write_str("Type")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::GenericArgument::Binding(_val) => { - formatter.write_str("Binding")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::GenericArgument::Constraint(_val) => { - formatter.write_str("Constraint")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::GenericArgument::Const(_val) => { - formatter.write_str("Const")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::GenericMethodArgument> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::GenericMethodArgument::Type(_val) => { - formatter.write_str("Type")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::GenericMethodArgument::Const(_val) => { - formatter.write_str("Const")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::GenericParam> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::GenericParam::Type(_val) => { - formatter.write_str("Type")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::GenericParam::Lifetime(_val) => { - formatter.write_str("Lifetime")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::GenericParam::Const(_val) => { - formatter.write_str("Const")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::Generics> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Generics"); - if let Some(val) = &_val.lt_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Lt); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("lt_token", Print::ref_cast(val)); - } - if !_val.params.is_empty() { - formatter.field("params", Lite(&_val.params)); - } - if let Some(val) = &_val.gt_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Gt); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("gt_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.where_clause { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::WhereClause); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("where_clause", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ImplItem> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::ImplItem::Const(_val) => { - let mut formatter = formatter.debug_struct("ImplItem::Const"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.defaultness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Default); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("defaultness", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::ImplItem::Method(_val) => { - let mut formatter = formatter.debug_struct("ImplItem::Method"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.defaultness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Default); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("defaultness", Print::ref_cast(val)); - } - formatter.field("sig", Lite(&_val.sig)); - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } - syn::ImplItem::Type(_val) => { - let mut formatter = formatter.debug_struct("ImplItem::Type"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.defaultness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Default); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("defaultness", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } - syn::ImplItem::Existential(_val) => { - let mut formatter = formatter.debug_struct("ImplItem::Existential"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } - syn::ImplItem::Macro(_val) => { - let mut formatter = formatter.debug_struct("ImplItem::Macro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("mac", Lite(&_val.mac)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } - syn::ImplItem::Verbatim(_val) => { - let mut formatter = formatter.debug_struct("ImplItem::Verbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::ImplItemConst> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ImplItemConst"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.defaultness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Default); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("defaultness", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ImplItemExistential> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ImplItemExistential"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ImplItemMacro> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ImplItemMacro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("mac", Lite(&_val.mac)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ImplItemMethod> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ImplItemMethod"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.defaultness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Default); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("defaultness", Print::ref_cast(val)); - } - formatter.field("sig", Lite(&_val.sig)); - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } -} -impl Debug for Lite<syn::ImplItemType> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ImplItemType"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.defaultness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Default); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("defaultness", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::ImplItemVerbatim> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ImplItemVerbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } -} -impl Debug for Lite<syn::Index> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Index"); - formatter.field("index", Lite(&_val.index)); - formatter.finish() - } -} -impl Debug for Lite<syn::Item> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Item::ExternCrate(_val) => { - let mut formatter = formatter.debug_struct("Item::ExternCrate"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - if let Some(val) = &_val.rename { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::As, proc_macro2::Ident)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("rename", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Item::Use(_val) => { - let mut formatter = formatter.debug_struct("Item::Use"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.leading_colon { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("leading_colon", Print::ref_cast(val)); - } - formatter.field("tree", Lite(&_val.tree)); - formatter.finish() - } - syn::Item::Static(_val) => { - let mut formatter = formatter.debug_struct("Item::Static"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Item::Const(_val) => { - let mut formatter = formatter.debug_struct("Item::Const"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Item::Fn(_val) => { - let mut formatter = formatter.debug_struct("Item::Fn"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.constness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Const); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("constness", Print::ref_cast(val)); - } - if let Some(val) = &_val.asyncness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Async); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("asyncness", Print::ref_cast(val)); - } - if let Some(val) = &_val.unsafety { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Unsafe); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("unsafety", Print::ref_cast(val)); - } - if let Some(val) = &_val.abi { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Abi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("abi", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("decl", Lite(&_val.decl)); - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } - syn::Item::Mod(_val) => { - let mut formatter = formatter.debug_struct("Item::Mod"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - if let Some(val) = &_val.content { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Brace, Vec<syn::Item>)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("content", Print::ref_cast(val)); - } - if let Some(val) = &_val.semi { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Item::ForeignMod(_val) => { - let mut formatter = formatter.debug_struct("Item::ForeignMod"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("abi", Lite(&_val.abi)); - if !_val.items.is_empty() { - formatter.field("items", Lite(&_val.items)); - } - formatter.finish() - } - syn::Item::Type(_val) => { - let mut formatter = formatter.debug_struct("Item::Type"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } - syn::Item::Existential(_val) => { - let mut formatter = formatter.debug_struct("Item::Existential"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } - syn::Item::Struct(_val) => { - let mut formatter = formatter.debug_struct("Item::Struct"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - formatter.field("fields", Lite(&_val.fields)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Item::Enum(_val) => { - let mut formatter = formatter.debug_struct("Item::Enum"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if !_val.variants.is_empty() { - formatter.field("variants", Lite(&_val.variants)); - } - formatter.finish() - } - syn::Item::Union(_val) => { - let mut formatter = formatter.debug_struct("Item::Union"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - formatter.field("fields", Lite(&_val.fields)); - formatter.finish() - } - syn::Item::Trait(_val) => { - let mut formatter = formatter.debug_struct("Item::Trait"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.unsafety { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Unsafe); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("unsafety", Print::ref_cast(val)); - } - if let Some(val) = &_val.auto_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Auto); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("auto_token", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.supertraits.is_empty() { - formatter.field("supertraits", Lite(&_val.supertraits)); - } - if !_val.items.is_empty() { - formatter.field("items", Lite(&_val.items)); - } - formatter.finish() - } - syn::Item::TraitAlias(_val) => { - let mut formatter = formatter.debug_struct("Item::TraitAlias"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } - syn::Item::Impl(_val) => { - let mut formatter = formatter.debug_struct("Item::Impl"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.defaultness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Default); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("defaultness", Print::ref_cast(val)); - } - if let Some(val) = &_val.unsafety { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Unsafe); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("unsafety", Print::ref_cast(val)); - } - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.trait_ { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((Option<syn::token::Bang>, syn::Path, syn::token::For)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt( - &( - { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Option<syn::token::Bang>); - impl Debug for Print { - fn fmt( - &self, - formatter: &mut fmt::Formatter, - ) -> fmt::Result - { - match &self.0 { - Some(_val) => { - formatter.write_str("Some")?; - Ok(()) - } - None => formatter.write_str("None"), - } - } - } - Print::ref_cast(&_val.0) - }, - Lite(&_val.1), - ), - formatter, - )?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("trait_", Print::ref_cast(val)); - } - formatter.field("self_ty", Lite(&_val.self_ty)); - if !_val.items.is_empty() { - formatter.field("items", Lite(&_val.items)); - } - formatter.finish() - } - syn::Item::Macro(_val) => { - let mut formatter = formatter.debug_struct("Item::Macro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.ident { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(proc_macro2::Ident); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("ident", Print::ref_cast(val)); - } - formatter.field("mac", Lite(&_val.mac)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Item::Macro2(_val) => { - let mut formatter = formatter.debug_struct("Item::Macro2"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("args", Lite(&_val.args)); - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } - syn::Item::Verbatim(_val) => { - let mut formatter = formatter.debug_struct("Item::Verbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::ItemConst> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemConst"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ItemEnum> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemEnum"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if !_val.variants.is_empty() { - formatter.field("variants", Lite(&_val.variants)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemExistential> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemExistential"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemExternCrate> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemExternCrate"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - if let Some(val) = &_val.rename { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::As, proc_macro2::Ident)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("rename", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemFn> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemFn"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.constness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Const); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("constness", Print::ref_cast(val)); - } - if let Some(val) = &_val.asyncness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Async); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("asyncness", Print::ref_cast(val)); - } - if let Some(val) = &_val.unsafety { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Unsafe); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("unsafety", Print::ref_cast(val)); - } - if let Some(val) = &_val.abi { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Abi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("abi", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("decl", Lite(&_val.decl)); - formatter.field("block", Lite(&_val.block)); - formatter.finish() - } -} -impl Debug for Lite<syn::ItemForeignMod> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemForeignMod"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("abi", Lite(&_val.abi)); - if !_val.items.is_empty() { - formatter.field("items", Lite(&_val.items)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemImpl> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemImpl"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.defaultness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Default); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("defaultness", Print::ref_cast(val)); - } - if let Some(val) = &_val.unsafety { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Unsafe); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("unsafety", Print::ref_cast(val)); - } - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.trait_ { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((Option<syn::token::Bang>, syn::Path, syn::token::For)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt( - &( - { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Option<syn::token::Bang>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match &self.0 { - Some(_val) => { - formatter.write_str("Some")?; - Ok(()) - } - None => formatter.write_str("None"), - } - } - } - Print::ref_cast(&_val.0) - }, - Lite(&_val.1), - ), - formatter, - )?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("trait_", Print::ref_cast(val)); - } - formatter.field("self_ty", Lite(&_val.self_ty)); - if !_val.items.is_empty() { - formatter.field("items", Lite(&_val.items)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemMacro> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemMacro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if let Some(val) = &_val.ident { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(proc_macro2::Ident); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("ident", Print::ref_cast(val)); - } - formatter.field("mac", Lite(&_val.mac)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemMacro2> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemMacro2"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("args", Lite(&_val.args)); - formatter.field("body", Lite(&_val.body)); - formatter.finish() - } -} -impl Debug for Lite<syn::ItemMod> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemMod"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - if let Some(val) = &_val.content { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Brace, Vec<syn::Item>)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("content", Print::ref_cast(val)); - } - if let Some(val) = &_val.semi { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemStatic> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemStatic"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::ItemStruct> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemStruct"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - formatter.field("fields", Lite(&_val.fields)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemTrait> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemTrait"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.unsafety { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Unsafe); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("unsafety", Print::ref_cast(val)); - } - if let Some(val) = &_val.auto_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Auto); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("auto_token", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.supertraits.is_empty() { - formatter.field("supertraits", Lite(&_val.supertraits)); - } - if !_val.items.is_empty() { - formatter.field("items", Lite(&_val.items)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemTraitAlias> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemTraitAlias"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::ItemType> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemType"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - formatter.field("ty", Lite(&_val.ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::ItemUnion> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemUnion"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - formatter.field("fields", Lite(&_val.fields)); - formatter.finish() - } -} -impl Debug for Lite<syn::ItemUse> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemUse"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.leading_colon { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("leading_colon", Print::ref_cast(val)); - } - formatter.field("tree", Lite(&_val.tree)); - formatter.finish() - } -} -impl Debug for Lite<syn::ItemVerbatim> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ItemVerbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } -} -impl Debug for Lite<syn::Label> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Label"); - formatter.field("name", Lite(&_val.name)); - formatter.finish() - } -} -impl Debug for Lite<syn::Lifetime> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Lifetime"); - formatter.field("ident", Lite(&_val.ident)); - formatter.finish() - } -} -impl Debug for Lite<syn::LifetimeDef> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("LifetimeDef"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("lifetime", Lite(&_val.lifetime)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::Lit> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Lit::Str(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::ByteStr(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::Byte(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::Char(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::Int(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::Float(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::Bool(_val) => { - let mut formatter = formatter.debug_struct("Lit::Bool"); - formatter.field("value", Lite(&_val.value)); - formatter.finish() - } - syn::Lit::Verbatim(_val) => { - let mut formatter = formatter.debug_struct("Lit::Verbatim"); - formatter.field("token", Lite(&_val.token)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::LitBool> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("LitBool"); - formatter.field("value", Lite(&_val.value)); - formatter.finish() - } -} -impl Debug for Lite<syn::LitByte> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - write!(formatter, "{:?}", _val.value()) - } -} -impl Debug for Lite<syn::LitByteStr> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - write!(formatter, "{:?}", _val.value()) - } -} -impl Debug for Lite<syn::LitChar> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - write!(formatter, "{:?}", _val.value()) - } -} -impl Debug for Lite<syn::LitFloat> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - write!(formatter, "{:?}", _val.value()) - } -} -impl Debug for Lite<syn::LitInt> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - write!(formatter, "{:?}", _val.value()) - } -} -impl Debug for Lite<syn::LitStr> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - write!(formatter, "{:?}", _val.value()) - } -} -impl Debug for Lite<syn::LitVerbatim> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("LitVerbatim"); - formatter.field("token", Lite(&_val.token)); - formatter.finish() - } -} -impl Debug for Lite<syn::Local> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Local"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - if !_val.pats.is_empty() { - formatter.field("pats", Lite(&_val.pats)); - } - if let Some(val) = &_val.ty { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Colon, Box<syn::Type>)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("ty", Print::ref_cast(val)); - } - if let Some(val) = &_val.init { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Eq, Box<syn::Expr>)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("init", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::Macro> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Macro"); - formatter.field("path", Lite(&_val.path)); - formatter.field("delimiter", Lite(&_val.delimiter)); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } -} -impl Debug for Lite<syn::MacroDelimiter> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::MacroDelimiter::Paren(_val) => { - formatter.write_str("Paren")?; - Ok(()) - } - syn::MacroDelimiter::Brace(_val) => { - formatter.write_str("Brace")?; - Ok(()) - } - syn::MacroDelimiter::Bracket(_val) => { - formatter.write_str("Bracket")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::Member> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Member::Named(_val) => { - formatter.write_str("Named")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::Member::Unnamed(_val) => { - formatter.write_str("Unnamed")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::Meta> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Meta::Word(_val) => { - formatter.write_str("Word")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::Meta::List(_val) => { - let mut formatter = formatter.debug_struct("Meta::List"); - formatter.field("ident", Lite(&_val.ident)); - if !_val.nested.is_empty() { - formatter.field("nested", Lite(&_val.nested)); - } - formatter.finish() - } - syn::Meta::NameValue(_val) => { - let mut formatter = formatter.debug_struct("Meta::NameValue"); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("lit", Lite(&_val.lit)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::MetaList> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("MetaList"); - formatter.field("ident", Lite(&_val.ident)); - if !_val.nested.is_empty() { - formatter.field("nested", Lite(&_val.nested)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::MetaNameValue> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("MetaNameValue"); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("lit", Lite(&_val.lit)); - formatter.finish() - } -} -impl Debug for Lite<syn::MethodSig> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("MethodSig"); - if let Some(val) = &_val.constness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Const); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("constness", Print::ref_cast(val)); - } - if let Some(val) = &_val.asyncness { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Async); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("asyncness", Print::ref_cast(val)); - } - if let Some(val) = &_val.unsafety { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Unsafe); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("unsafety", Print::ref_cast(val)); - } - if let Some(val) = &_val.abi { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Abi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("abi", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("decl", Lite(&_val.decl)); - formatter.finish() - } -} -impl Debug for Lite<syn::MethodTurbofish> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("MethodTurbofish"); - if !_val.args.is_empty() { - formatter.field("args", Lite(&_val.args)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::NestedMeta> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::NestedMeta::Meta(_val) => { - formatter.write_str("Meta")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::NestedMeta::Literal(_val) => { - formatter.write_str("Literal")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::ParenthesizedGenericArguments> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("ParenthesizedGenericArguments"); - if !_val.inputs.is_empty() { - formatter.field("inputs", Lite(&_val.inputs)); - } - formatter.field("output", Lite(&_val.output)); - formatter.finish() - } -} -impl Debug for Lite<syn::Pat> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Pat::Wild(_val) => { - let mut formatter = formatter.debug_struct("Pat::Wild"); - formatter.finish() - } - syn::Pat::Ident(_val) => { - let mut formatter = formatter.debug_struct("Pat::Ident"); - if let Some(val) = &_val.by_ref { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Ref); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("by_ref", Print::ref_cast(val)); - } - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - if let Some(val) = &_val.subpat { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::At, Box<syn::Pat>)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("subpat", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Pat::Struct(_val) => { - let mut formatter = formatter.debug_struct("Pat::Struct"); - formatter.field("path", Lite(&_val.path)); - if !_val.fields.is_empty() { - formatter.field("fields", Lite(&_val.fields)); - } - if let Some(val) = &_val.dot2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dot2_token", Print::ref_cast(val)); - } - formatter.finish() - } - syn::Pat::TupleStruct(_val) => { - let mut formatter = formatter.debug_struct("Pat::TupleStruct"); - formatter.field("path", Lite(&_val.path)); - formatter.field("pat", Lite(&_val.pat)); - formatter.finish() - } - syn::Pat::Path(_val) => { - let mut formatter = formatter.debug_struct("Pat::Path"); - if let Some(val) = &_val.qself { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::QSelf); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("qself", Print::ref_cast(val)); - } - formatter.field("path", Lite(&_val.path)); - formatter.finish() - } - syn::Pat::Tuple(_val) => { - let mut formatter = formatter.debug_struct("Pat::Tuple"); - if !_val.front.is_empty() { - formatter.field("front", Lite(&_val.front)); - } - if let Some(val) = &_val.dot2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dot2_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.comma_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Comma); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("comma_token", Print::ref_cast(val)); - } - if !_val.back.is_empty() { - formatter.field("back", Lite(&_val.back)); - } - formatter.finish() - } - syn::Pat::Box(_val) => { - let mut formatter = formatter.debug_struct("Pat::Box"); - formatter.field("pat", Lite(&_val.pat)); - formatter.finish() - } - syn::Pat::Ref(_val) => { - let mut formatter = formatter.debug_struct("Pat::Ref"); - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("pat", Lite(&_val.pat)); - formatter.finish() - } - syn::Pat::Lit(_val) => { - let mut formatter = formatter.debug_struct("Pat::Lit"); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } - syn::Pat::Range(_val) => { - let mut formatter = formatter.debug_struct("Pat::Range"); - formatter.field("lo", Lite(&_val.lo)); - formatter.field("limits", Lite(&_val.limits)); - formatter.field("hi", Lite(&_val.hi)); - formatter.finish() - } - syn::Pat::Slice(_val) => { - let mut formatter = formatter.debug_struct("Pat::Slice"); - if !_val.front.is_empty() { - formatter.field("front", Lite(&_val.front)); - } - if let Some(val) = &_val.middle { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Pat>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("middle", Print::ref_cast(val)); - } - if let Some(val) = &_val.dot2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dot2_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.comma_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Comma); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("comma_token", Print::ref_cast(val)); - } - if !_val.back.is_empty() { - formatter.field("back", Lite(&_val.back)); - } - formatter.finish() - } - syn::Pat::Macro(_val) => { - let mut formatter = formatter.debug_struct("Pat::Macro"); - formatter.field("mac", Lite(&_val.mac)); - formatter.finish() - } - syn::Pat::Verbatim(_val) => { - let mut formatter = formatter.debug_struct("Pat::Verbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::PatBox> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatBox"); - formatter.field("pat", Lite(&_val.pat)); - formatter.finish() - } -} -impl Debug for Lite<syn::PatIdent> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatIdent"); - if let Some(val) = &_val.by_ref { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Ref); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("by_ref", Print::ref_cast(val)); - } - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("ident", Lite(&_val.ident)); - if let Some(val) = &_val.subpat { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::At, Box<syn::Pat>)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("subpat", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::PatLit> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatLit"); - formatter.field("expr", Lite(&_val.expr)); - formatter.finish() - } -} -impl Debug for Lite<syn::PatMacro> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatMacro"); - formatter.field("mac", Lite(&_val.mac)); - formatter.finish() - } -} -impl Debug for Lite<syn::PatPath> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatPath"); - if let Some(val) = &_val.qself { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::QSelf); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("qself", Print::ref_cast(val)); - } - formatter.field("path", Lite(&_val.path)); - formatter.finish() - } -} -impl Debug for Lite<syn::PatRange> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatRange"); - formatter.field("lo", Lite(&_val.lo)); - formatter.field("limits", Lite(&_val.limits)); - formatter.field("hi", Lite(&_val.hi)); - formatter.finish() - } -} -impl Debug for Lite<syn::PatRef> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatRef"); - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("pat", Lite(&_val.pat)); - formatter.finish() - } -} -impl Debug for Lite<syn::PatSlice> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatSlice"); - if !_val.front.is_empty() { - formatter.field("front", Lite(&_val.front)); - } - if let Some(val) = &_val.middle { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(Box<syn::Pat>); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("middle", Print::ref_cast(val)); - } - if let Some(val) = &_val.dot2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dot2_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.comma_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Comma); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("comma_token", Print::ref_cast(val)); - } - if !_val.back.is_empty() { - formatter.field("back", Lite(&_val.back)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::PatStruct> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatStruct"); - formatter.field("path", Lite(&_val.path)); - if !_val.fields.is_empty() { - formatter.field("fields", Lite(&_val.fields)); - } - if let Some(val) = &_val.dot2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dot2_token", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::PatTuple> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatTuple"); - if !_val.front.is_empty() { - formatter.field("front", Lite(&_val.front)); - } - if let Some(val) = &_val.dot2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dot2_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.comma_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Comma); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("comma_token", Print::ref_cast(val)); - } - if !_val.back.is_empty() { - formatter.field("back", Lite(&_val.back)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::PatTupleStruct> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatTupleStruct"); - formatter.field("path", Lite(&_val.path)); - formatter.field("pat", Lite(&_val.pat)); - formatter.finish() - } -} -impl Debug for Lite<syn::PatVerbatim> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatVerbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } -} -impl Debug for Lite<syn::PatWild> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PatWild"); - formatter.finish() - } -} -impl Debug for Lite<syn::Path> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Path"); - if let Some(val) = &_val.leading_colon { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("leading_colon", Print::ref_cast(val)); - } - if !_val.segments.is_empty() { - formatter.field("segments", Lite(&_val.segments)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::PathArguments> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::PathArguments::None => formatter.write_str("None"), - syn::PathArguments::AngleBracketed(_val) => { - let mut formatter = formatter.debug_struct("PathArguments::AngleBracketed"); - if let Some(val) = &_val.colon2_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon2); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon2_token", Print::ref_cast(val)); - } - if !_val.args.is_empty() { - formatter.field("args", Lite(&_val.args)); - } - formatter.finish() - } - syn::PathArguments::Parenthesized(_val) => { - let mut formatter = formatter.debug_struct("PathArguments::Parenthesized"); - if !_val.inputs.is_empty() { - formatter.field("inputs", Lite(&_val.inputs)); - } - formatter.field("output", Lite(&_val.output)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::PathSegment> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PathSegment"); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("arguments", Lite(&_val.arguments)); - formatter.finish() - } -} -impl Debug for Lite<syn::PredicateEq> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PredicateEq"); - formatter.field("lhs_ty", Lite(&_val.lhs_ty)); - formatter.field("rhs_ty", Lite(&_val.rhs_ty)); - formatter.finish() - } -} -impl Debug for Lite<syn::PredicateLifetime> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PredicateLifetime"); - formatter.field("lifetime", Lite(&_val.lifetime)); - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::PredicateType> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("PredicateType"); - if let Some(val) = &_val.lifetimes { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::BoundLifetimes); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("lifetimes", Print::ref_cast(val)); - } - formatter.field("bounded_ty", Lite(&_val.bounded_ty)); - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::QSelf> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("QSelf"); - formatter.field("ty", Lite(&_val.ty)); - formatter.field("position", Lite(&_val.position)); - if let Some(val) = &_val.as_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::As); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("as_token", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::RangeLimits> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::RangeLimits::HalfOpen(_val) => { - formatter.write_str("HalfOpen")?; - Ok(()) - } - syn::RangeLimits::Closed(_val) => { - formatter.write_str("Closed")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::ReturnType> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::ReturnType::Default => formatter.write_str("Default"), - syn::ReturnType::Type(_v0, _v1) => { - let mut formatter = formatter.debug_tuple("Type"); - formatter.field(Lite(_v1)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::Stmt> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Stmt::Local(_val) => { - formatter.write_str("Local")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::Stmt::Item(_val) => { - formatter.write_str("Item")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::Stmt::Expr(_val) => { - formatter.write_str("Expr")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::Stmt::Semi(_v0, _v1) => { - let mut formatter = formatter.debug_tuple("Semi"); - formatter.field(Lite(_v0)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::TraitBound> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TraitBound"); - if let Some(val) = &_val.paren_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Paren); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("paren_token", Print::ref_cast(val)); - } - formatter.field("modifier", Lite(&_val.modifier)); - if let Some(val) = &_val.lifetimes { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::BoundLifetimes); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("lifetimes", Print::ref_cast(val)); - } - formatter.field("path", Lite(&_val.path)); - formatter.finish() - } -} -impl Debug for Lite<syn::TraitBoundModifier> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::TraitBoundModifier::None => formatter.write_str("None"), - syn::TraitBoundModifier::Maybe(_val) => { - formatter.write_str("Maybe")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::TraitItem> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::TraitItem::Const(_val) => { - let mut formatter = formatter.debug_struct("TraitItem::Const"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - if let Some(val) = &_val.default { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Eq, syn::Expr)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("default", Print::ref_cast(val)); - } - formatter.finish() - } - syn::TraitItem::Method(_val) => { - let mut formatter = formatter.debug_struct("TraitItem::Method"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("sig", Lite(&_val.sig)); - if let Some(val) = &_val.default { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Block); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("default", Print::ref_cast(val)); - } - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } - syn::TraitItem::Type(_val) => { - let mut formatter = formatter.debug_struct("TraitItem::Type"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - if let Some(val) = &_val.default { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Eq, syn::Type)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("default", Print::ref_cast(val)); - } - formatter.finish() - } - syn::TraitItem::Macro(_val) => { - let mut formatter = formatter.debug_struct("TraitItem::Macro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("mac", Lite(&_val.mac)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } - syn::TraitItem::Verbatim(_val) => { - let mut formatter = formatter.debug_struct("TraitItem::Verbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::TraitItemConst> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TraitItemConst"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("ty", Lite(&_val.ty)); - if let Some(val) = &_val.default { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Eq, syn::Expr)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("default", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::TraitItemMacro> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TraitItemMacro"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("mac", Lite(&_val.mac)); - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::TraitItemMethod> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TraitItemMethod"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("sig", Lite(&_val.sig)); - if let Some(val) = &_val.default { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Block); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("default", Print::ref_cast(val)); - } - if let Some(val) = &_val.semi_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Semi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("semi_token", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::TraitItemType> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TraitItemType"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("generics", Lite(&_val.generics)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - if let Some(val) = &_val.default { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Eq, syn::Type)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("default", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::TraitItemVerbatim> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TraitItemVerbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } -} -impl Debug for Lite<syn::Type> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Type::Slice(_val) => { - let mut formatter = formatter.debug_struct("Type::Slice"); - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } - syn::Type::Array(_val) => { - let mut formatter = formatter.debug_struct("Type::Array"); - formatter.field("elem", Lite(&_val.elem)); - formatter.field("len", Lite(&_val.len)); - formatter.finish() - } - syn::Type::Ptr(_val) => { - let mut formatter = formatter.debug_struct("Type::Ptr"); - if let Some(val) = &_val.const_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Const); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("const_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } - syn::Type::Reference(_val) => { - let mut formatter = formatter.debug_struct("Type::Reference"); - if let Some(val) = &_val.lifetime { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Lifetime); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("lifetime", Print::ref_cast(val)); - } - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } - syn::Type::BareFn(_val) => { - let mut formatter = formatter.debug_struct("Type::BareFn"); - if let Some(val) = &_val.lifetimes { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::BoundLifetimes); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("lifetimes", Print::ref_cast(val)); - } - if let Some(val) = &_val.unsafety { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Unsafe); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("unsafety", Print::ref_cast(val)); - } - if let Some(val) = &_val.abi { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Abi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("abi", Print::ref_cast(val)); - } - if !_val.inputs.is_empty() { - formatter.field("inputs", Lite(&_val.inputs)); - } - if let Some(val) = &_val.variadic { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot3); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("variadic", Print::ref_cast(val)); - } - formatter.field("output", Lite(&_val.output)); - formatter.finish() - } - syn::Type::Never(_val) => { - let mut formatter = formatter.debug_struct("Type::Never"); - formatter.finish() - } - syn::Type::Tuple(_val) => { - let mut formatter = formatter.debug_struct("Type::Tuple"); - if !_val.elems.is_empty() { - formatter.field("elems", Lite(&_val.elems)); - } - formatter.finish() - } - syn::Type::Path(_val) => { - let mut formatter = formatter.debug_struct("Type::Path"); - if let Some(val) = &_val.qself { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::QSelf); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("qself", Print::ref_cast(val)); - } - formatter.field("path", Lite(&_val.path)); - formatter.finish() - } - syn::Type::TraitObject(_val) => { - let mut formatter = formatter.debug_struct("Type::TraitObject"); - if let Some(val) = &_val.dyn_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dyn); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dyn_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } - syn::Type::ImplTrait(_val) => { - let mut formatter = formatter.debug_struct("Type::ImplTrait"); - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } - syn::Type::Paren(_val) => { - let mut formatter = formatter.debug_struct("Type::Paren"); - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } - syn::Type::Group(_val) => { - let mut formatter = formatter.debug_struct("Type::Group"); - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } - syn::Type::Infer(_val) => { - let mut formatter = formatter.debug_struct("Type::Infer"); - formatter.finish() - } - syn::Type::Macro(_val) => { - let mut formatter = formatter.debug_struct("Type::Macro"); - formatter.field("mac", Lite(&_val.mac)); - formatter.finish() - } - syn::Type::Verbatim(_val) => { - let mut formatter = formatter.debug_struct("Type::Verbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } - } - } -} -impl Debug for Lite<syn::TypeArray> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeArray"); - formatter.field("elem", Lite(&_val.elem)); - formatter.field("len", Lite(&_val.len)); - formatter.finish() - } -} -impl Debug for Lite<syn::TypeBareFn> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeBareFn"); - if let Some(val) = &_val.lifetimes { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::BoundLifetimes); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("lifetimes", Print::ref_cast(val)); - } - if let Some(val) = &_val.unsafety { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Unsafe); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("unsafety", Print::ref_cast(val)); - } - if let Some(val) = &_val.abi { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Abi); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("abi", Print::ref_cast(val)); - } - if !_val.inputs.is_empty() { - formatter.field("inputs", Lite(&_val.inputs)); - } - if let Some(val) = &_val.variadic { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dot3); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("variadic", Print::ref_cast(val)); - } - formatter.field("output", Lite(&_val.output)); - formatter.finish() - } -} -impl Debug for Lite<syn::TypeGroup> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeGroup"); - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } -} -impl Debug for Lite<syn::TypeImplTrait> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeImplTrait"); - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::TypeInfer> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeInfer"); - formatter.finish() - } -} -impl Debug for Lite<syn::TypeMacro> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeMacro"); - formatter.field("mac", Lite(&_val.mac)); - formatter.finish() - } -} -impl Debug for Lite<syn::TypeNever> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeNever"); - formatter.finish() - } -} -impl Debug for Lite<syn::TypeParam> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeParam"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("ident", Lite(&_val.ident)); - if let Some(val) = &_val.colon_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Colon); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("colon_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - if let Some(val) = &_val.eq_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Eq); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("eq_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.default { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Type); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("default", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::TypeParamBound> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::TypeParamBound::Trait(_val) => { - formatter.write_str("Trait")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::TypeParamBound::Lifetime(_val) => { - formatter.write_str("Lifetime")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::TypeParen> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeParen"); - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } -} -impl Debug for Lite<syn::TypePath> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypePath"); - if let Some(val) = &_val.qself { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::QSelf); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("qself", Print::ref_cast(val)); - } - formatter.field("path", Lite(&_val.path)); - formatter.finish() - } -} -impl Debug for Lite<syn::TypePtr> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypePtr"); - if let Some(val) = &_val.const_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Const); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("const_token", Print::ref_cast(val)); - } - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } -} -impl Debug for Lite<syn::TypeReference> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeReference"); - if let Some(val) = &_val.lifetime { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Lifetime); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("lifetime", Print::ref_cast(val)); - } - if let Some(val) = &_val.mutability { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Mut); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("mutability", Print::ref_cast(val)); - } - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } -} -impl Debug for Lite<syn::TypeSlice> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeSlice"); - formatter.field("elem", Lite(&_val.elem)); - formatter.finish() - } -} -impl Debug for Lite<syn::TypeTraitObject> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeTraitObject"); - if let Some(val) = &_val.dyn_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::Dyn); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("dyn_token", Print::ref_cast(val)); - } - if !_val.bounds.is_empty() { - formatter.field("bounds", Lite(&_val.bounds)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::TypeTuple> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeTuple"); - if !_val.elems.is_empty() { - formatter.field("elems", Lite(&_val.elems)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::TypeVerbatim> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("TypeVerbatim"); - formatter.field("tts", Lite(&_val.tts)); - formatter.finish() - } -} -impl Debug for Lite<syn::UnOp> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::UnOp::Deref(_val) => { - formatter.write_str("Deref")?; - Ok(()) - } - syn::UnOp::Not(_val) => { - formatter.write_str("Not")?; - Ok(()) - } - syn::UnOp::Neg(_val) => { - formatter.write_str("Neg")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::UseGlob> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("UseGlob"); - formatter.finish() - } -} -impl Debug for Lite<syn::UseGroup> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("UseGroup"); - if !_val.items.is_empty() { - formatter.field("items", Lite(&_val.items)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::UseName> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("UseName"); - formatter.field("ident", Lite(&_val.ident)); - formatter.finish() - } -} -impl Debug for Lite<syn::UsePath> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("UsePath"); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("tree", Lite(&_val.tree)); - formatter.finish() - } -} -impl Debug for Lite<syn::UseRename> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("UseRename"); - formatter.field("ident", Lite(&_val.ident)); - formatter.field("rename", Lite(&_val.rename)); - formatter.finish() - } -} -impl Debug for Lite<syn::UseTree> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::UseTree::Path(_val) => { - formatter.write_str("Path")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::UseTree::Name(_val) => { - formatter.write_str("Name")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::UseTree::Rename(_val) => { - formatter.write_str("Rename")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::UseTree::Glob(_val) => { - formatter.write_str("Glob")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::UseTree::Group(_val) => { - formatter.write_str("Group")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} -impl Debug for Lite<syn::Variant> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("Variant"); - if !_val.attrs.is_empty() { - formatter.field("attrs", Lite(&_val.attrs)); - } - formatter.field("ident", Lite(&_val.ident)); - formatter.field("fields", Lite(&_val.fields)); - if let Some(val) = &_val.discriminant { - #[derive(RefCast)] - #[repr(transparent)] - struct Print((syn::token::Eq, syn::Expr)); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(&_val.1), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("discriminant", Print::ref_cast(val)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::VisCrate> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("VisCrate"); - formatter.finish() - } -} -impl Debug for Lite<syn::VisPublic> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("VisPublic"); - formatter.finish() - } -} -impl Debug for Lite<syn::VisRestricted> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("VisRestricted"); - if let Some(val) = &_val.in_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::In); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("in_token", Print::ref_cast(val)); - } - formatter.field("path", Lite(&_val.path)); - formatter.finish() - } -} -impl Debug for Lite<syn::Visibility> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::Visibility::Public(_val) => { - let mut formatter = formatter.debug_struct("Visibility::Public"); - formatter.finish() - } - syn::Visibility::Crate(_val) => { - let mut formatter = formatter.debug_struct("Visibility::Crate"); - formatter.finish() - } - syn::Visibility::Restricted(_val) => { - let mut formatter = formatter.debug_struct("Visibility::Restricted"); - if let Some(val) = &_val.in_token { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::token::In); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - Ok(()) - } - } - formatter.field("in_token", Print::ref_cast(val)); - } - formatter.field("path", Lite(&_val.path)); - formatter.finish() - } - syn::Visibility::Inherited => formatter.write_str("Inherited"), - } - } -} -impl Debug for Lite<syn::WhereClause> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - let mut formatter = formatter.debug_struct("WhereClause"); - if !_val.predicates.is_empty() { - formatter.field("predicates", Lite(&_val.predicates)); - } - formatter.finish() - } -} -impl Debug for Lite<syn::WherePredicate> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::WherePredicate::Type(_val) => { - formatter.write_str("Type")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::WherePredicate::Lifetime(_val) => { - formatter.write_str("Lifetime")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::WherePredicate::Eq(_val) => { - formatter.write_str("Eq")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} diff --git a/0.15.42/tests/debug/mod.rs b/0.15.42/tests/debug/mod.rs deleted file mode 100644 index c1180532..00000000 --- a/0.15.42/tests/debug/mod.rs +++ /dev/null @@ -1,113 +0,0 @@ -extern crate proc_macro2; -extern crate ref_cast; - -mod gen; - -use self::proc_macro2::{Ident, Literal, TokenStream}; -use self::ref_cast::RefCast; -use std::fmt::{self, Debug}; -use std::ops::Deref; -use syn::punctuated::Punctuated; - -#[derive(RefCast)] -#[repr(transparent)] -pub struct Lite<T: ?Sized> { - value: T, -} - -#[allow(non_snake_case)] -pub fn Lite<T: ?Sized>(value: &T) -> &Lite<T> { - Lite::ref_cast(value) -} - -impl<T: ?Sized> Deref for Lite<T> { - type Target = T; - - fn deref(&self) -> &Self::Target { - &self.value - } -} - -impl Debug for Lite<bool> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "{}", self.value) - } -} - -impl Debug for Lite<u32> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "{}", self.value) - } -} - -impl Debug for Lite<usize> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "{}", self.value) - } -} - -impl Debug for Lite<String> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "{:?}", self.value) - } -} - -impl Debug for Lite<Ident> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "{:?}", self.value.to_string()) - } -} - -impl Debug for Lite<Literal> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "{}", self.value) - } -} - -impl Debug for Lite<TokenStream> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "`{}`", self.value) - } -} - -impl<'a, T> Debug for Lite<&'a T> -where - Lite<T>: Debug, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - Debug::fmt(Lite(&*self.value), formatter) - } -} - -impl<T> Debug for Lite<Box<T>> -where - Lite<T>: Debug, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - Debug::fmt(Lite(&*self.value), formatter) - } -} - -impl<T> Debug for Lite<Vec<T>> -where - Lite<T>: Debug, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter - .debug_list() - .entries(self.value.iter().map(Lite)) - .finish() - } -} - -impl<T, P> Debug for Lite<Punctuated<T, P>> -where - Lite<T>: Debug, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter - .debug_list() - .entries(self.value.iter().map(Lite)) - .finish() - } -} diff --git a/0.15.42/tests/features/error.rs b/0.15.42/tests/features/error.rs deleted file mode 100644 index 10ac8896..00000000 --- a/0.15.42/tests/features/error.rs +++ /dev/null @@ -1 +0,0 @@ -"Hello! You want: cargo test --release --all-features" diff --git a/0.15.42/tests/features/mod.rs b/0.15.42/tests/features/mod.rs deleted file mode 100644 index 83fbe13e..00000000 --- a/0.15.42/tests/features/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -#[allow(unused_macros)] -macro_rules! hide_from_rustfmt { - ($mod:item) => { - $mod - }; -} - -#[cfg(not(all( - feature = "derive", - feature = "full", - feature = "parsing", - feature = "printing", - feature = "visit", - feature = "visit-mut", - feature = "fold", - feature = "clone-impls", - feature = "extra-traits", - feature = "proc-macro", -)))] -hide_from_rustfmt! { - mod error; -} diff --git a/0.15.42/tests/macros/mod.rs b/0.15.42/tests/macros/mod.rs deleted file mode 100644 index e35872af..00000000 --- a/0.15.42/tests/macros/mod.rs +++ /dev/null @@ -1,78 +0,0 @@ -extern crate proc_macro2; - -#[path = "../debug/mod.rs"] -pub mod debug; - -use syn; -use syn::parse::{Parse, Result}; - -#[macro_export] -macro_rules! errorf { - ($($tt:tt)*) => {{ - use ::std::io::Write; - let stderr = ::std::io::stderr(); - write!(stderr.lock(), $($tt)*).unwrap(); - }}; -} - -#[macro_export] -macro_rules! punctuated { - ($($e:expr,)+) => {{ - let mut seq = ::syn::punctuated::Punctuated::new(); - $( - seq.push($e); - )+ - seq - }}; - - ($($e:expr),+) => { - punctuated!($($e,)+) - }; -} - -#[macro_export] -macro_rules! snapshot { - ($($args:tt)*) => { - snapshot_impl!(() $($args)*) - }; -} - -#[macro_export] -macro_rules! snapshot_impl { - (($expr:ident) as $t:ty, @$snapshot:literal) => { - let $expr = ::macros::Tokens::parse::<$t>($expr).unwrap(); - let debug = crate::macros::debug::Lite(&$expr); - insta::assert_debug_snapshot_matches!(debug, @$snapshot); - }; - (($($expr:tt)*) as $t:ty, @$snapshot:literal) => {{ - let syntax_tree = ::macros::Tokens::parse::<$t>($($expr)*).unwrap(); - let debug = crate::macros::debug::Lite(&syntax_tree); - insta::assert_debug_snapshot_matches!(debug, @$snapshot); - syntax_tree - }}; - (($($expr:tt)*) , @$snapshot:literal) => {{ - let syntax_tree = $($expr)*; - let debug = crate::macros::debug::Lite(&syntax_tree); - insta::assert_debug_snapshot_matches!(debug, @$snapshot); - syntax_tree - }}; - (($($expr:tt)*) $next:tt $($rest:tt)*) => { - snapshot_impl!(($($expr)* $next) $($rest)*) - }; -} - -pub trait Tokens { - fn parse<T: Parse>(self) -> Result<T>; -} - -impl<'a> Tokens for &'a str { - fn parse<T: Parse>(self) -> Result<T> { - syn::parse_str(self) - } -} - -impl Tokens for proc_macro2::TokenStream { - fn parse<T: Parse>(self) -> Result<T> { - syn::parse2(self) - } -} diff --git a/0.15.42/tests/repo/mod.rs b/0.15.42/tests/repo/mod.rs deleted file mode 100644 index 6247bdb3..00000000 --- a/0.15.42/tests/repo/mod.rs +++ /dev/null @@ -1,54 +0,0 @@ -extern crate walkdir; - -use std::process::Command; - -use self::walkdir::DirEntry; - -pub fn base_dir_filter(entry: &DirEntry) -> bool { - let path = entry.path(); - if path.is_dir() { - return true; // otherwise walkdir does not visit the files - } - if path.extension().map(|e| e != "rs").unwrap_or(true) { - return false; - } - let path_string = path.to_string_lossy(); - let path_string = if cfg!(windows) { - path_string.replace('\\', "/").into() - } else { - path_string - }; - // TODO assert that parsing fails on the parse-fail cases - if path_string.starts_with("tests/rust/src/test/parse-fail") - || path_string.starts_with("tests/rust/src/test/compile-fail") - || path_string.starts_with("tests/rust/src/test/rustfix") - { - return false; - } - - if path_string.starts_with("tests/rust/src/test/ui") { - let stderr_path = path.with_extension("stderr"); - if stderr_path.exists() { - // Expected to fail in some way - return false; - } - } - - match path_string.as_ref() { - // Deprecated placement syntax - "tests/rust/src/test/run-pass/new-box-syntax.rs" | - "tests/rust/src/test/ui/obsolete-in-place/bad.rs" | - // 2015-style dyn that libsyntax rejects - "tests/rust/src/test/ui/dyn-keyword/dyn-2015-no-warnings-without-lints.rs" | - // not actually test cases - "tests/rust/src/test/run-pass/macros/auxiliary/macro-comma-support.rs" | - "tests/rust/src/test/run-pass/macros/auxiliary/macro-include-items-expr.rs" | - "tests/rust/src/test/ui/issues/auxiliary/issue-21146-inc.rs" => false, - _ => true, - } -} - -pub fn clone_rust() { - let result = Command::new("tests/clone.sh").status().unwrap(); - assert!(result.success()); -} diff --git a/0.15.42/tests/test_asyncness.rs b/0.15.42/tests/test_asyncness.rs deleted file mode 100644 index 8289b3d1..00000000 --- a/0.15.42/tests/test_asyncness.rs +++ /dev/null @@ -1,41 +0,0 @@ -extern crate syn; - -mod features; - -#[macro_use] -mod macros; - -use syn::{Expr, Item}; - -#[test] -fn test_async_fn() { - let input = "async fn process() {}"; - - snapshot!(input as Item, @r###" - ⋮Item::Fn { - ⋮ vis: Inherited, - ⋮ asyncness: Some, - ⋮ ident: "process", - ⋮ decl: FnDecl { - ⋮ generics: Generics, - ⋮ output: Default, - ⋮ }, - ⋮ block: Block, - ⋮} - "###); -} - -#[test] -fn test_async_closure() { - let input = "async || {}"; - - snapshot!(input as Expr, @r###" - ⋮Expr::Closure { - ⋮ asyncness: Some, - ⋮ output: Default, - ⋮ body: Expr::Block { - ⋮ block: Block, - ⋮ }, - ⋮} - "###); -} diff --git a/0.15.42/tests/test_attribute.rs b/0.15.42/tests/test_attribute.rs deleted file mode 100644 index 2a7e106b..00000000 --- a/0.15.42/tests/test_attribute.rs +++ /dev/null @@ -1,279 +0,0 @@ -extern crate syn; - -mod features; - -#[macro_use] -mod macros; - -use syn::parse::Parser; -use syn::{Attribute, Meta}; - -#[test] -fn test_meta_item_word() { - let (interpret, parse) = test("#[foo]"); - - snapshot!(interpret, @r###"Word("foo")"###); - - snapshot!(parse, @r###"Word("foo")"###); -} - -#[test] -fn test_meta_item_name_value() { - let (interpret, parse) = test("#[foo = 5]"); - - snapshot!(interpret, @r###" - ⋮Meta::NameValue { - ⋮ ident: "foo", - ⋮ lit: 5, - ⋮} - "###); - - snapshot!(parse, @r###" - ⋮Meta::NameValue { - ⋮ ident: "foo", - ⋮ lit: 5, - ⋮} - "###); -} - -#[test] -fn test_meta_item_bool_value() { - let (interpret, parse) = test("#[foo = true]");; - - snapshot!(interpret, @r###" - ⋮Meta::NameValue { - ⋮ ident: "foo", - ⋮ lit: Lit::Bool { - ⋮ value: true, - ⋮ }, - ⋮} - "###); - - snapshot!(parse, @r###" - ⋮Meta::NameValue { - ⋮ ident: "foo", - ⋮ lit: Lit::Bool { - ⋮ value: true, - ⋮ }, - ⋮} - "###); - - let (interpret, parse) = test("#[foo = false]"); - - snapshot!(interpret, @r###" - ⋮Meta::NameValue { - ⋮ ident: "foo", - ⋮ lit: Lit::Bool { - ⋮ value: false, - ⋮ }, - ⋮} - "###); - - snapshot!(parse, @r###" - ⋮Meta::NameValue { - ⋮ ident: "foo", - ⋮ lit: Lit::Bool { - ⋮ value: false, - ⋮ }, - ⋮} - "###); -} - -#[test] -fn test_meta_item_list_lit() { - let (interpret, parse) = test("#[foo(5)]"); - - snapshot!(interpret, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Literal(5), - ⋮ ], - ⋮} - "###); - - snapshot!(parse, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Literal(5), - ⋮ ], - ⋮} - "###); -} - -#[test] -fn test_meta_item_list_word() { - let (interpret, parse) = test("#[foo(bar)]"); - - snapshot!(interpret, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Word("bar")), - ⋮ ], - ⋮} - "###); - - snapshot!(parse, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Word("bar")), - ⋮ ], - ⋮} - "###); -} - -#[test] -fn test_meta_item_list_name_value() { - let (interpret, parse) = test("#[foo(bar = 5)]"); - - snapshot!(interpret, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Meta::NameValue { - ⋮ ident: "bar", - ⋮ lit: 5, - ⋮ }), - ⋮ ], - ⋮} - "###); - - snapshot!(parse, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Meta::NameValue { - ⋮ ident: "bar", - ⋮ lit: 5, - ⋮ }), - ⋮ ], - ⋮} - "###); -} - -#[test] -fn test_meta_item_list_bool_value() { - let (interpret, parse) = test("#[foo(bar = true)]"); - - snapshot!(interpret, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Meta::NameValue { - ⋮ ident: "bar", - ⋮ lit: Lit::Bool { - ⋮ value: true, - ⋮ }, - ⋮ }), - ⋮ ], - ⋮} - "###); - - snapshot!(parse, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Meta::NameValue { - ⋮ ident: "bar", - ⋮ lit: Lit::Bool { - ⋮ value: true, - ⋮ }, - ⋮ }), - ⋮ ], - ⋮} - "###); -} - -#[test] -fn test_meta_item_multiple() { - let (interpret, parse) = test("#[foo(word, name = 5, list(name2 = 6), word2)]"); - - snapshot!(interpret, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Word("word")), - ⋮ Meta(Meta::NameValue { - ⋮ ident: "name", - ⋮ lit: 5, - ⋮ }), - ⋮ Meta(Meta::List { - ⋮ ident: "list", - ⋮ nested: [ - ⋮ Meta(Meta::NameValue { - ⋮ ident: "name2", - ⋮ lit: 6, - ⋮ }), - ⋮ ], - ⋮ }), - ⋮ Meta(Word("word2")), - ⋮ ], - ⋮} - "###); - - snapshot!(parse, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Word("word")), - ⋮ Meta(Meta::NameValue { - ⋮ ident: "name", - ⋮ lit: 5, - ⋮ }), - ⋮ Meta(Meta::List { - ⋮ ident: "list", - ⋮ nested: [ - ⋮ Meta(Meta::NameValue { - ⋮ ident: "name2", - ⋮ lit: 6, - ⋮ }), - ⋮ ], - ⋮ }), - ⋮ Meta(Word("word2")), - ⋮ ], - ⋮} - "###); -} - -#[test] -fn test_bool_lit() { - let (interpret, parse) = test("#[foo(true)]"); - - snapshot!(interpret, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Literal(Lit::Bool { - ⋮ value: true, - ⋮ }), - ⋮ ], - ⋮} - "###); - - snapshot!(parse, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Literal(Lit::Bool { - ⋮ value: true, - ⋮ }), - ⋮ ], - ⋮} - "###); -} - -fn test(input: &str) -> (Meta, Meta) { - let attrs = Attribute::parse_outer.parse_str(input).unwrap(); - - assert_eq!(attrs.len(), 1); - let attr = attrs.into_iter().next().unwrap(); - - let interpret = attr.interpret_meta().unwrap(); - let parse = attr.parse_meta().unwrap(); - assert_eq!(interpret, parse); - - (interpret, parse) -} diff --git a/0.15.42/tests/test_derive_input.rs b/0.15.42/tests/test_derive_input.rs deleted file mode 100644 index 112caee8..00000000 --- a/0.15.42/tests/test_derive_input.rs +++ /dev/null @@ -1,849 +0,0 @@ -extern crate quote; -extern crate syn; - -mod features; - -#[macro_use] -mod macros; - -use quote::quote; -use syn::{Data, DeriveInput}; - -#[test] -fn test_unit() { - let input = quote! { - struct Unit; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Inherited, - ⋮ ident: "Unit", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); -} - -#[test] -fn test_struct() { - let input = quote! { - #[derive(Debug, Clone)] - pub struct Item { - pub ident: Ident, - pub attrs: Vec<Attribute> - } - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ attrs: [ - ⋮ Attribute { - ⋮ style: Outer, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "derive", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ tts: `( Debug , Clone )`, - ⋮ }, - ⋮ ], - ⋮ vis: Visibility::Public, - ⋮ ident: "Item", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Fields::Named { - ⋮ named: [ - ⋮ Field { - ⋮ vis: Visibility::Public, - ⋮ ident: Some("ident"), - ⋮ colon_token: Some, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "Ident", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ Field { - ⋮ vis: Visibility::Public, - ⋮ ident: Some("attrs"), - ⋮ colon_token: Some, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "Vec", - ⋮ arguments: PathArguments::AngleBracketed { - ⋮ args: [ - ⋮ Type(Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "Attribute", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }), - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮} - "###); - - snapshot!(input.attrs[0].interpret_meta().unwrap(), @r###" - ⋮Meta::List { - ⋮ ident: "derive", - ⋮ nested: [ - ⋮ Meta(Word("Debug")), - ⋮ Meta(Word("Clone")), - ⋮ ], - ⋮} - "###); -} - -#[test] -fn test_union() { - let input = quote! { - union MaybeUninit<T> { - uninit: (), - value: T - } - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Inherited, - ⋮ ident: "MaybeUninit", - ⋮ generics: Generics { - ⋮ lt_token: Some, - ⋮ params: [ - ⋮ Type(TypeParam { - ⋮ ident: "T", - ⋮ }), - ⋮ ], - ⋮ gt_token: Some, - ⋮ }, - ⋮ data: Data::Union { - ⋮ fields: FieldsNamed { - ⋮ named: [ - ⋮ Field { - ⋮ vis: Inherited, - ⋮ ident: Some("uninit"), - ⋮ colon_token: Some, - ⋮ ty: Type::Tuple, - ⋮ }, - ⋮ Field { - ⋮ vis: Inherited, - ⋮ ident: Some("value"), - ⋮ colon_token: Some, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "T", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮} - "###); -} - -#[test] -#[cfg(feature = "full")] -fn test_enum() { - let input = quote! { - /// See the std::result module documentation for details. - #[must_use] - pub enum Result<T, E> { - Ok(T), - Err(E), - Surprise = 0isize, - - // Smuggling data into a proc_macro_derive, - // in the style of https://github.com/dtolnay/proc-macro-hack - ProcMacroHack = (0, "data").0 - } - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ attrs: [ - ⋮ Attribute { - ⋮ style: Outer, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "doc", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ tts: `= r" See the std::result module documentation for details."`, - ⋮ }, - ⋮ Attribute { - ⋮ style: Outer, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "must_use", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ tts: ``, - ⋮ }, - ⋮ ], - ⋮ vis: Visibility::Public, - ⋮ ident: "Result", - ⋮ generics: Generics { - ⋮ lt_token: Some, - ⋮ params: [ - ⋮ Type(TypeParam { - ⋮ ident: "T", - ⋮ }), - ⋮ Type(TypeParam { - ⋮ ident: "E", - ⋮ }), - ⋮ ], - ⋮ gt_token: Some, - ⋮ }, - ⋮ data: Data::Enum { - ⋮ variants: [ - ⋮ Variant { - ⋮ ident: "Ok", - ⋮ fields: Fields::Unnamed { - ⋮ unnamed: [ - ⋮ Field { - ⋮ vis: Inherited, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "T", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ Variant { - ⋮ ident: "Err", - ⋮ fields: Fields::Unnamed { - ⋮ unnamed: [ - ⋮ Field { - ⋮ vis: Inherited, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "E", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ Variant { - ⋮ ident: "Surprise", - ⋮ fields: Unit, - ⋮ discriminant: Some(Expr::Lit { - ⋮ lit: 0, - ⋮ }), - ⋮ }, - ⋮ Variant { - ⋮ ident: "ProcMacroHack", - ⋮ fields: Unit, - ⋮ discriminant: Some(Expr::Field { - ⋮ base: Expr::Tuple { - ⋮ elems: [ - ⋮ Expr::Lit { - ⋮ lit: 0, - ⋮ }, - ⋮ Expr::Lit { - ⋮ lit: "data", - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ member: Unnamed(Index { - ⋮ index: 0, - ⋮ }), - ⋮ }), - ⋮ }, - ⋮ ], - ⋮ }, - ⋮} - "###); - - let meta_items: Vec<_> = input - .attrs - .into_iter() - .map(|attr| attr.interpret_meta().unwrap()) - .collect(); - - snapshot!(meta_items, @r###" - ⋮[ - ⋮ Meta::NameValue { - ⋮ ident: "doc", - ⋮ lit: " See the std::result module documentation for details.", - ⋮ }, - ⋮ Word("must_use"), - ⋮] - "###); -} - -#[test] -fn test_attr_with_path() { - let input = quote! { - #[::attr_args::identity - fn main() { assert_eq!(foo(), "Hello, world!"); }] - struct Dummy; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ attrs: [ - ⋮ Attribute { - ⋮ style: Outer, - ⋮ path: Path { - ⋮ leading_colon: Some, - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "attr_args", - ⋮ arguments: None, - ⋮ }, - ⋮ PathSegment { - ⋮ ident: "identity", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ tts: `fn main ( ) { assert_eq ! ( foo ( ) , "Hello, world!" ) ; }`, - ⋮ }, - ⋮ ], - ⋮ vis: Inherited, - ⋮ ident: "Dummy", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); - - assert!(input.attrs[0].interpret_meta().is_none()); -} - -#[test] -fn test_attr_with_non_mod_style_path() { - let input = quote! { - #[inert <T>] - struct S; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ attrs: [ - ⋮ Attribute { - ⋮ style: Outer, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "inert", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ tts: `< T >`, - ⋮ }, - ⋮ ], - ⋮ vis: Inherited, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); - - assert!(input.attrs[0].interpret_meta().is_none()); -} - -#[test] -fn test_attr_with_mod_style_path_with_self() { - let input = quote! { - #[foo::self] - struct S; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ attrs: [ - ⋮ Attribute { - ⋮ style: Outer, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "foo", - ⋮ arguments: None, - ⋮ }, - ⋮ PathSegment { - ⋮ ident: "self", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ tts: ``, - ⋮ }, - ⋮ ], - ⋮ vis: Inherited, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); - - assert!(input.attrs[0].interpret_meta().is_none()); -} - -#[test] -fn test_pub_restricted() { - // Taken from tests/rust/src/test/ui/resolve/auxiliary/privacy-struct-ctor.rs - let input = quote! { - pub(in m) struct Z(pub(in m::n) u8); - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Visibility::Restricted { - ⋮ in_token: Some, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "m", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ ident: "Z", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Fields::Unnamed { - ⋮ unnamed: [ - ⋮ Field { - ⋮ vis: Visibility::Restricted { - ⋮ in_token: Some, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "m", - ⋮ arguments: None, - ⋮ }, - ⋮ PathSegment { - ⋮ ident: "n", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "u8", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); -} - -#[test] -fn test_vis_crate() { - let input = quote! { - crate struct S; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Visibility::Crate, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); -} - -#[test] -fn test_pub_restricted_crate() { - let input = quote! { - pub(crate) struct S; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Visibility::Restricted { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "crate", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); -} - -#[test] -fn test_pub_restricted_super() { - let input = quote! { - pub(super) struct S; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Visibility::Restricted { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "super", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); -} - -#[test] -fn test_pub_restricted_in_super() { - let input = quote! { - pub(in super) struct S; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Visibility::Restricted { - ⋮ in_token: Some, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "super", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); -} - -#[test] -fn test_fields_on_unit_struct() { - let input = quote! { - struct S; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Inherited, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); - - let data = match input.data { - Data::Struct(data) => data, - _ => panic!("expected a struct"), - }; - - assert_eq!(0, data.fields.iter().count()); -} - -#[test] -fn test_fields_on_named_struct() { - let input = quote! { - struct S { - foo: i32, - pub bar: String, - } - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Inherited, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Fields::Named { - ⋮ named: [ - ⋮ Field { - ⋮ vis: Inherited, - ⋮ ident: Some("foo"), - ⋮ colon_token: Some, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "i32", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ Field { - ⋮ vis: Visibility::Public, - ⋮ ident: Some("bar"), - ⋮ colon_token: Some, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "String", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮} - "###); - - let data = match input.data { - Data::Struct(data) => data, - _ => panic!("expected a struct"), - }; - - snapshot!(data.fields.into_iter().collect::<Vec<_>>(), @r###" - ⋮[ - ⋮ Field { - ⋮ vis: Inherited, - ⋮ ident: Some("foo"), - ⋮ colon_token: Some, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "i32", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ Field { - ⋮ vis: Visibility::Public, - ⋮ ident: Some("bar"), - ⋮ colon_token: Some, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "String", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮] - "###); -} - -#[test] -fn test_fields_on_tuple_struct() { - let input = quote! { - struct S(i32, pub String); - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Inherited, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Fields::Unnamed { - ⋮ unnamed: [ - ⋮ Field { - ⋮ vis: Inherited, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "i32", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ Field { - ⋮ vis: Visibility::Public, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "String", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); - - let data = match input.data { - Data::Struct(data) => data, - _ => panic!("expected a struct"), - }; - - snapshot!(data.fields.iter().collect::<Vec<_>>(), @r###" - ⋮[ - ⋮ Field { - ⋮ vis: Inherited, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "i32", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ Field { - ⋮ vis: Visibility::Public, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "String", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮] - "###); -} - -#[test] -fn test_ambiguous_crate() { - let input = quote! { - // The field type is `(crate::X)` not `crate (::X)`. - struct S(crate::X); - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Inherited, - ⋮ ident: "S", - ⋮ generics: Generics, - ⋮ data: Data::Struct { - ⋮ fields: Fields::Unnamed { - ⋮ unnamed: [ - ⋮ Field { - ⋮ vis: Inherited, - ⋮ ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "crate", - ⋮ arguments: None, - ⋮ }, - ⋮ PathSegment { - ⋮ ident: "X", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); -} diff --git a/0.15.42/tests/test_expr.rs b/0.15.42/tests/test_expr.rs deleted file mode 100644 index be285258..00000000 --- a/0.15.42/tests/test_expr.rs +++ /dev/null @@ -1,16 +0,0 @@ -extern crate proc_macro2; -extern crate syn; - -use std::str::FromStr; - -use proc_macro2::TokenStream; -use syn::{Expr, ExprRange}; - -#[test] -fn test_expr_parse() { - let code = "..100u32"; - let tt = TokenStream::from_str(code).unwrap(); - let expr: Expr = syn::parse2(tt.clone()).unwrap(); - let expr_range: ExprRange = syn::parse2(tt).unwrap(); - assert_eq!(expr, Expr::Range(expr_range)); -} diff --git a/0.15.42/tests/test_generics.rs b/0.15.42/tests/test_generics.rs deleted file mode 100644 index 27b204e9..00000000 --- a/0.15.42/tests/test_generics.rs +++ /dev/null @@ -1,288 +0,0 @@ -extern crate quote; -extern crate syn; - -mod features; - -#[macro_use] -mod macros; - -use quote::quote; -use syn::{DeriveInput, ItemFn, TypeParamBound, WhereClause, WherePredicate}; - -#[test] -fn test_split_for_impl() { - let input = quote! { - struct S<'a, 'b: 'a, #[may_dangle] T: 'a = ()> where T: Debug; - }; - - snapshot!(input as DeriveInput, @r###" - ⋮DeriveInput { - ⋮ vis: Inherited, - ⋮ ident: "S", - ⋮ generics: Generics { - ⋮ lt_token: Some, - ⋮ params: [ - ⋮ Lifetime(LifetimeDef { - ⋮ lifetime: Lifetime { - ⋮ ident: "a", - ⋮ }, - ⋮ }), - ⋮ Lifetime(LifetimeDef { - ⋮ lifetime: Lifetime { - ⋮ ident: "b", - ⋮ }, - ⋮ colon_token: Some, - ⋮ bounds: [ - ⋮ Lifetime { - ⋮ ident: "a", - ⋮ }, - ⋮ ], - ⋮ }), - ⋮ Type(TypeParam { - ⋮ attrs: [ - ⋮ Attribute { - ⋮ style: Outer, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "may_dangle", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ tts: ``, - ⋮ }, - ⋮ ], - ⋮ ident: "T", - ⋮ colon_token: Some, - ⋮ bounds: [ - ⋮ Lifetime(Lifetime { - ⋮ ident: "a", - ⋮ }), - ⋮ ], - ⋮ eq_token: Some, - ⋮ default: Some(Type::Tuple), - ⋮ }), - ⋮ ], - ⋮ gt_token: Some, - ⋮ where_clause: Some(WhereClause { - ⋮ predicates: [ - ⋮ Type(PredicateType { - ⋮ bounded_ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "T", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ bounds: [ - ⋮ Trait(TraitBound { - ⋮ modifier: None, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "Debug", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }), - ⋮ ], - ⋮ }), - ⋮ ], - ⋮ }), - ⋮ }, - ⋮ data: Data::Struct { - ⋮ fields: Unit, - ⋮ semi_token: Some, - ⋮ }, - ⋮} - "###); - - let generics = input.generics; - let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); - - let generated = quote! { - impl #impl_generics MyTrait for Test #ty_generics #where_clause {} - }; - let expected = quote! { - impl<'a, 'b: 'a, #[may_dangle] T: 'a> MyTrait - for Test<'a, 'b, T> - where - T: Debug - {} - }; - assert_eq!(generated.to_string(), expected.to_string()); - - let turbofish = ty_generics.as_turbofish(); - let generated = quote! { - Test #turbofish - }; - let expected = quote! { - Test::<'a, 'b, T> - }; - assert_eq!(generated.to_string(), expected.to_string()); -} - -#[test] -fn test_ty_param_bound() { - let tokens = quote!('a); - snapshot!(tokens as TypeParamBound, @r###" - ⋮Lifetime(Lifetime { - ⋮ ident: "a", - ⋮}) - "###); - - let tokens = quote!('_); - snapshot!(tokens as TypeParamBound, @r###" - ⋮Lifetime(Lifetime { - ⋮ ident: "_", - ⋮}) - "###); - - let tokens = quote!(Debug); - snapshot!(tokens as TypeParamBound, @r###" - ⋮Trait(TraitBound { - ⋮ modifier: None, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "Debug", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮}) - "###); - - let tokens = quote!(?Sized); - snapshot!(tokens as TypeParamBound, @r###" - ⋮Trait(TraitBound { - ⋮ modifier: Maybe, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "Sized", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮}) - "###); -} - -#[test] -fn test_fn_precedence_in_where_clause() { - // This should parse as two separate bounds, `FnOnce() -> i32` and `Send` - not - // `FnOnce() -> (i32 + Send)`. - let input = quote! { - fn f<G>() - where - G: FnOnce() -> i32 + Send, - { - } - }; - - snapshot!(input as ItemFn, @r###" - ⋮ItemFn { - ⋮ vis: Inherited, - ⋮ ident: "f", - ⋮ decl: FnDecl { - ⋮ generics: Generics { - ⋮ lt_token: Some, - ⋮ params: [ - ⋮ Type(TypeParam { - ⋮ ident: "G", - ⋮ }), - ⋮ ], - ⋮ gt_token: Some, - ⋮ where_clause: Some(WhereClause { - ⋮ predicates: [ - ⋮ Type(PredicateType { - ⋮ bounded_ty: Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "G", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ bounds: [ - ⋮ Trait(TraitBound { - ⋮ modifier: None, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "FnOnce", - ⋮ arguments: PathArguments::Parenthesized { - ⋮ output: Type( - ⋮ Type::Path { - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "i32", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }, - ⋮ ), - ⋮ }, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }), - ⋮ Trait(TraitBound { - ⋮ modifier: None, - ⋮ path: Path { - ⋮ segments: [ - ⋮ PathSegment { - ⋮ ident: "Send", - ⋮ arguments: None, - ⋮ }, - ⋮ ], - ⋮ }, - ⋮ }), - ⋮ ], - ⋮ }), - ⋮ ], - ⋮ }), - ⋮ }, - ⋮ output: Default, - ⋮ }, - ⋮ block: Block, - ⋮} - "###); - - let where_clause = input.decl.generics.where_clause.as_ref().unwrap(); - assert_eq!(where_clause.predicates.len(), 1); - - let predicate = match &where_clause.predicates[0] { - WherePredicate::Type(pred) => pred, - _ => panic!("wrong predicate kind"), - }; - - assert_eq!(predicate.bounds.len(), 2, "{:#?}", predicate.bounds); - - let first_bound = &predicate.bounds[0]; - assert_eq!(quote!(#first_bound).to_string(), "FnOnce ( ) -> i32"); - - let second_bound = &predicate.bounds[1]; - assert_eq!(quote!(#second_bound).to_string(), "Send"); -} - -#[test] -fn test_where_clause_at_end_of_input() { - let input = quote! { - where - }; - - snapshot!(input as WhereClause, @"WhereClause"); - - assert_eq!(input.predicates.len(), 0); -} diff --git a/0.15.42/tests/test_grouping.rs b/0.15.42/tests/test_grouping.rs deleted file mode 100644 index 6ca438d7..00000000 --- a/0.15.42/tests/test_grouping.rs +++ /dev/null @@ -1,58 +0,0 @@ -extern crate proc_macro2; -extern crate syn; - -mod features; - -#[macro_use] -mod macros; - -use proc_macro2::{Delimiter, Group, Literal, Punct, Spacing, TokenStream, TokenTree}; -use syn::Expr; - -use std::iter::FromIterator; - -#[test] -fn test_grouping() { - let tokens: TokenStream = TokenStream::from_iter(vec![ - TokenTree::Literal(Literal::i32_suffixed(1)), - TokenTree::Punct(Punct::new('+', Spacing::Alone)), - TokenTree::Group(Group::new( - Delimiter::None, - TokenStream::from_iter(vec![ - TokenTree::Literal(Literal::i32_suffixed(2)), - TokenTree::Punct(Punct::new('+', Spacing::Alone)), - TokenTree::Literal(Literal::i32_suffixed(3)), - ]), - )), - TokenTree::Punct(Punct::new('*', Spacing::Alone)), - TokenTree::Literal(Literal::i32_suffixed(4)), - ]); - - assert_eq!(tokens.to_string(), "1i32 + 2i32 + 3i32 * 4i32"); - - snapshot!(tokens as Expr, @r###" - ⋮Expr::Binary { - ⋮ left: Expr::Lit { - ⋮ lit: 1, - ⋮ }, - ⋮ op: Add, - ⋮ right: Expr::Binary { - ⋮ left: Expr::Group { - ⋮ expr: Expr::Binary { - ⋮ left: Expr::Lit { - ⋮ lit: 2, - ⋮ }, - ⋮ op: Add, - ⋮ right: Expr::Lit { - ⋮ lit: 3, - ⋮ }, - ⋮ }, - ⋮ }, - ⋮ op: Mul, - ⋮ right: Expr::Lit { - ⋮ lit: 4, - ⋮ }, - ⋮ }, - ⋮} - "###); -} diff --git a/0.15.42/tests/test_ident.rs b/0.15.42/tests/test_ident.rs deleted file mode 100644 index bec00a70..00000000 --- a/0.15.42/tests/test_ident.rs +++ /dev/null @@ -1,90 +0,0 @@ -extern crate proc_macro2; -extern crate syn; - -mod features; - -use proc_macro2::{Ident, Span, TokenStream}; -use std::str::FromStr; -use syn::Result; - -fn parse(s: &str) -> Result<Ident> { - syn::parse2(TokenStream::from_str(s).unwrap()) -} - -fn new(s: &str) -> Ident { - Ident::new(s, Span::call_site()) -} - -#[test] -fn ident_parse() { - parse("String").unwrap(); -} - -#[test] -fn ident_parse_keyword() { - parse("abstract").unwrap_err(); -} - -#[test] -fn ident_parse_empty() { - parse("").unwrap_err(); -} - -#[test] -fn ident_parse_lifetime() { - parse("'static").unwrap_err(); -} - -#[test] -fn ident_parse_underscore() { - parse("_").unwrap_err(); -} - -#[test] -fn ident_parse_number() { - parse("255").unwrap_err(); -} - -#[test] -fn ident_parse_invalid() { - parse("a#").unwrap_err(); -} - -#[test] -fn ident_new() { - new("String"); -} - -#[test] -fn ident_new_keyword() { - new("abstract"); -} - -#[test] -#[should_panic(expected = "use Option<Ident>")] -fn ident_new_empty() { - new(""); -} - -#[test] -#[should_panic(expected = "not a valid Ident")] -fn ident_new_lifetime() { - new("'static"); -} - -#[test] -fn ident_new_underscore() { - new("_"); -} - -#[test] -#[should_panic(expected = "use Literal instead")] -fn ident_new_number() { - new("255"); -} - -#[test] -#[should_panic(expected = "\"a#\" is not a valid Ident")] -fn ident_new_invalid() { - new("a#"); -} diff --git a/0.15.42/tests/test_lit.rs b/0.15.42/tests/test_lit.rs deleted file mode 100644 index 4425fcce..00000000 --- a/0.15.42/tests/test_lit.rs +++ /dev/null @@ -1,190 +0,0 @@ -extern crate proc_macro2; -extern crate quote; -extern crate syn; - -mod features; - -use proc_macro2::{TokenStream, TokenTree}; -use quote::ToTokens; -use std::str::FromStr; -use syn::{FloatSuffix, IntSuffix, Lit}; - -fn lit(s: &str) -> Lit { - match TokenStream::from_str(s) - .unwrap() - .into_iter() - .next() - .unwrap() - { - TokenTree::Literal(lit) => Lit::new(lit), - _ => panic!(), - } -} - -#[test] -fn strings() { - fn test_string(s: &str, value: &str) { - match lit(s) { - Lit::Str(lit) => { - assert_eq!(lit.value(), value); - let again = lit.into_token_stream().to_string(); - if again != s { - test_string(&again, value); - } - } - wrong => panic!("{:?}", wrong), - } - } - - test_string("\"a\"", "a"); - test_string("\"\\n\"", "\n"); - test_string("\"\\r\"", "\r"); - test_string("\"\\t\"", "\t"); - test_string("\"🐕\"", "🐕"); // NOTE: This is an emoji - test_string("\"\\\"\"", "\""); - test_string("\"'\"", "'"); - test_string("\"\"", ""); - test_string("\"\\u{1F415}\"", "\u{1F415}"); - test_string( - "\"contains\nnewlines\\\nescaped newlines\"", - "contains\nnewlinesescaped newlines", - ); - test_string("r\"raw\nstring\\\nhere\"", "raw\nstring\\\nhere"); -} - -#[test] -fn byte_strings() { - fn test_byte_string(s: &str, value: &[u8]) { - match lit(s) { - Lit::ByteStr(lit) => { - assert_eq!(lit.value(), value); - let again = lit.into_token_stream().to_string(); - if again != s { - test_byte_string(&again, value); - } - } - wrong => panic!("{:?}", wrong), - } - } - - test_byte_string("b\"a\"", b"a"); - test_byte_string("b\"\\n\"", b"\n"); - test_byte_string("b\"\\r\"", b"\r"); - test_byte_string("b\"\\t\"", b"\t"); - test_byte_string("b\"\\\"\"", b"\""); - test_byte_string("b\"'\"", b"'"); - test_byte_string("b\"\"", b""); - test_byte_string( - "b\"contains\nnewlines\\\nescaped newlines\"", - b"contains\nnewlinesescaped newlines", - ); - test_byte_string("br\"raw\nstring\\\nhere\"", b"raw\nstring\\\nhere"); -} - -#[test] -fn bytes() { - fn test_byte(s: &str, value: u8) { - match lit(s) { - Lit::Byte(lit) => { - assert_eq!(lit.value(), value); - let again = lit.into_token_stream().to_string(); - assert_eq!(again, s); - } - wrong => panic!("{:?}", wrong), - } - } - - test_byte("b'a'", b'a'); - test_byte("b'\\n'", b'\n'); - test_byte("b'\\r'", b'\r'); - test_byte("b'\\t'", b'\t'); - test_byte("b'\\''", b'\''); - test_byte("b'\"'", b'"'); -} - -#[test] -fn chars() { - fn test_char(s: &str, value: char) { - match lit(s) { - Lit::Char(lit) => { - assert_eq!(lit.value(), value); - let again = lit.into_token_stream().to_string(); - if again != s { - test_char(&again, value); - } - } - wrong => panic!("{:?}", wrong), - } - } - - test_char("'a'", 'a'); - test_char("'\\n'", '\n'); - test_char("'\\r'", '\r'); - test_char("'\\t'", '\t'); - test_char("'🐕'", '🐕'); // NOTE: This is an emoji - test_char("'\\''", '\''); - test_char("'\"'", '"'); - test_char("'\\u{1F415}'", '\u{1F415}'); -} - -#[test] -fn ints() { - fn test_int(s: &str, value: u64, suffix: IntSuffix) { - match lit(s) { - Lit::Int(lit) => { - assert_eq!(lit.value(), value); - assert_eq!(lit.suffix(), suffix); - let again = lit.into_token_stream().to_string(); - if again != s { - test_int(&again, value, suffix); - } - } - wrong => panic!("{:?}", wrong), - } - } - - use syn::IntSuffix::*; - test_int("5", 5, None); - test_int("5u32", 5, U32); - test_int("5_0", 50, None); - test_int("5_____0_____", 50, None); - test_int("0x7f", 127, None); - test_int("0x7F", 127, None); - test_int("0b1001", 9, None); - test_int("0o73", 59, None); - test_int("0x7Fu8", 127, U8); - test_int("0b1001i8", 9, I8); - test_int("0o73u32", 59, U32); - test_int("0x__7___f_", 127, None); - test_int("0x__7___F_", 127, None); - test_int("0b_1_0__01", 9, None); - test_int("0o_7__3", 59, None); - test_int("0x_7F__u8", 127, U8); - test_int("0b__10__0_1i8", 9, I8); - test_int("0o__7__________________3u32", 59, U32); -} - -#[test] -fn floats() { - #[cfg_attr(feature = "cargo-clippy", allow(float_cmp))] - fn test_float(s: &str, value: f64, suffix: FloatSuffix) { - match lit(s) { - Lit::Float(lit) => { - assert_eq!(lit.value(), value); - assert_eq!(lit.suffix(), suffix); - let again = lit.into_token_stream().to_string(); - if again != s { - test_float(&again, value, suffix); - } - } - wrong => panic!("{:?}", wrong), - } - } - - use syn::FloatSuffix::*; - test_float("5.5", 5.5, None); - test_float("5.5E12", 5.5e12, None); - test_float("5.5e12", 5.5e12, None); - test_float("1.0__3e-12", 1.03e-12, None); - test_float("1.03e+12", 1.03e12, None); -} diff --git a/0.15.42/tests/test_meta.rs b/0.15.42/tests/test_meta.rs deleted file mode 100644 index 97639cf3..00000000 --- a/0.15.42/tests/test_meta.rs +++ /dev/null @@ -1,180 +0,0 @@ -extern crate syn; - -mod features; - -#[macro_use] -mod macros; - -use syn::{Meta, MetaList, MetaNameValue, NestedMeta}; - -#[test] -fn test_parse_meta_item_word() { - let input = "hello"; - - snapshot!(input as Meta, @r###"Word("hello")"###); -} - -#[test] -fn test_parse_meta_name_value() { - let input = "foo = 5"; - let (inner, meta) = (input, input); - - snapshot!(inner as MetaNameValue, @r###" - ⋮MetaNameValue { - ⋮ ident: "foo", - ⋮ lit: 5, - ⋮} - "###); - - snapshot!(meta as Meta, @r###" - ⋮Meta::NameValue { - ⋮ ident: "foo", - ⋮ lit: 5, - ⋮} - "###); - - assert_eq!(meta, inner.into()); -} - -#[test] -fn test_parse_meta_name_value_with_keyword() { - let input = "static = 5"; - let (inner, meta) = (input, input); - - snapshot!(inner as MetaNameValue, @r###" - ⋮MetaNameValue { - ⋮ ident: "static", - ⋮ lit: 5, - ⋮} - "###); - - snapshot!(meta as Meta, @r###" - ⋮Meta::NameValue { - ⋮ ident: "static", - ⋮ lit: 5, - ⋮} - "###); - - assert_eq!(meta, inner.into()); -} - -#[test] -fn test_parse_meta_name_value_with_bool() { - let input = "true = 5"; - let (inner, meta) = (input, input); - - snapshot!(inner as MetaNameValue, @r###" - ⋮MetaNameValue { - ⋮ ident: "true", - ⋮ lit: 5, - ⋮} - "###); - - snapshot!(meta as Meta, @r###" - ⋮Meta::NameValue { - ⋮ ident: "true", - ⋮ lit: 5, - ⋮} - "###); - - assert_eq!(meta, inner.into()); -} - -#[test] -fn test_parse_meta_item_list_lit() { - let input = "foo(5)"; - let (inner, meta) = (input, input); - - snapshot!(inner as MetaList, @r###" - ⋮MetaList { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Literal(5), - ⋮ ], - ⋮} - "###); - - snapshot!(meta as Meta, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Literal(5), - ⋮ ], - ⋮} - "###); - - assert_eq!(meta, inner.into()); -} - -#[test] -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###" - ⋮MetaList { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Word("word")), - ⋮ Meta(Meta::NameValue { - ⋮ ident: "name", - ⋮ lit: 5, - ⋮ }), - ⋮ Meta(Meta::List { - ⋮ ident: "list", - ⋮ nested: [ - ⋮ Meta(Meta::NameValue { - ⋮ ident: "name2", - ⋮ lit: 6, - ⋮ }), - ⋮ ], - ⋮ }), - ⋮ Meta(Word("word2")), - ⋮ ], - ⋮} - "###); - - snapshot!(meta as Meta, @r###" - ⋮Meta::List { - ⋮ ident: "foo", - ⋮ nested: [ - ⋮ Meta(Word("word")), - ⋮ Meta(Meta::NameValue { - ⋮ ident: "name", - ⋮ lit: 5, - ⋮ }), - ⋮ Meta(Meta::List { - ⋮ ident: "list", - ⋮ nested: [ - ⋮ Meta(Meta::NameValue { - ⋮ ident: "name2", - ⋮ lit: 6, - ⋮ }), - ⋮ ], - ⋮ }), - ⋮ Meta(Word("word2")), - ⋮ ], - ⋮} - "###); - - assert_eq!(meta, inner.into()); -} - -#[test] -fn test_parse_nested_meta() { - let input = "5"; - snapshot!(input as NestedMeta, @"Literal(5)"); - - let input = "list(name2 = 6)"; - snapshot!(input as NestedMeta, @r###" - ⋮Meta(Meta::List { - ⋮ ident: "list", - ⋮ nested: [ - ⋮ Meta(Meta::NameValue { - ⋮ ident: "name2", - ⋮ lit: 6, - ⋮ }), - ⋮ ], - ⋮}) - "###); -} diff --git a/0.15.42/tests/test_pat.rs b/0.15.42/tests/test_pat.rs deleted file mode 100644 index 1343aa64..00000000 --- a/0.15.42/tests/test_pat.rs +++ /dev/null @@ -1,23 +0,0 @@ -extern crate quote; -extern crate syn; - -mod features; - -use quote::quote; -use syn::Pat; - -#[test] -fn test_pat_ident() { - match syn::parse2(quote!(self)).unwrap() { - Pat::Ident(_) => (), - value => panic!("expected PatIdent, got {:?}", value), - } -} - -#[test] -fn test_pat_path() { - match syn::parse2(quote!(self::CONST)).unwrap() { - Pat::Path(_) => (), - value => panic!("expected PatPath, got {:?}", value), - } -} diff --git a/0.15.42/tests/test_precedence.rs b/0.15.42/tests/test_precedence.rs deleted file mode 100644 index 4774c284..00000000 --- a/0.15.42/tests/test_precedence.rs +++ /dev/null @@ -1,387 +0,0 @@ -#![cfg(not(syn_disable_nightly_tests))] -#![recursion_limit = "1024"] -#![feature(rustc_private)] - -//! The tests in this module do the following: -//! -//! 1. Parse a given expression in both `syn` and `libsyntax`. -//! 2. Fold over the expression adding brackets around each subexpression (with -//! some complications - see the `syn_brackets` and `libsyntax_brackets` -//! methods). -//! 3. Serialize the `syn` expression back into a string, and re-parse it with -//! `libsyntax`. -//! 4. Respan all of the expressions, replacing the spans with the default -//! spans. -//! 5. Compare the expressions with one another, if they are not equal fail. - -extern crate quote; -extern crate rayon; -extern crate regex; -extern crate rustc_data_structures; -extern crate smallvec; -extern crate syn; -extern crate syntax; -extern crate syntax_pos; -extern crate walkdir; - -mod features; - -use quote::quote; -use rayon::iter::{IntoParallelIterator, ParallelIterator}; -use regex::Regex; -use smallvec::smallvec; -use syntax::ast; -use syntax::ptr::P; -use syntax_pos::edition::Edition; -use walkdir::{DirEntry, WalkDir}; - -use std::fs::File; -use std::io::Read; -use std::process; -use std::sync::atomic::{AtomicUsize, Ordering}; - -use common::eq::SpanlessEq; -use common::parse; - -#[macro_use] -mod macros; - -#[allow(dead_code)] -mod common; - -mod repo; - -/// Test some pre-set expressions chosen by us. -#[test] -fn test_simple_precedence() { - const EXPRS: &[&str] = &[ - "1 + 2 * 3 + 4", - "1 + 2 * ( 3 + 4 )", - "{ for i in r { } *some_ptr += 1; }", - "{ loop { break 5; } }", - "{ if true { () }.mthd() }", - "{ for i in unsafe { 20 } { } }", - ]; - - let mut failed = 0; - - for input in EXPRS { - let expr = if let Some(expr) = parse::syn_expr(input) { - expr - } else { - failed += 1; - continue; - }; - - let pf = match test_expressions(vec![expr]) { - (1, 0) => "passed", - (0, 1) => { - failed += 1; - "failed" - } - _ => unreachable!(), - }; - errorf!("=== {}: {}\n", input, pf); - } - - if failed > 0 { - panic!("Failed {} tests", failed); - } -} - -/// Test expressions from rustc, like in `test_round_trip`. -#[test] -#[cfg_attr(target_os = "windows", ignore = "requires nix .sh")] -fn test_rustc_precedence() { - repo::clone_rust(); - let abort_after = common::abort_after(); - if abort_after == 0 { - panic!("Skipping all precedence tests"); - } - - let passed = AtomicUsize::new(0); - let failed = AtomicUsize::new(0); - - // 2018 edition is hard - let edition_regex = Regex::new(r"\b(async|try)[!(]").unwrap(); - - WalkDir::new("tests/rust") - .sort_by(|a, b| a.file_name().cmp(b.file_name())) - .into_iter() - .filter_entry(repo::base_dir_filter) - .collect::<Result<Vec<DirEntry>, walkdir::Error>>() - .unwrap() - .into_par_iter() - .for_each(|entry| { - let path = entry.path(); - if path.is_dir() { - return; - } - - // Our version of `libsyntax` can't parse this tests - if path - .to_str() - .unwrap() - .ends_with("optional_comma_in_match_arm.rs") - { - return; - } - - let mut file = File::open(path).unwrap(); - let mut content = String::new(); - file.read_to_string(&mut content).unwrap(); - let content = edition_regex.replace_all(&content, "_$0"); - - let (l_passed, l_failed) = match syn::parse_file(&content) { - Ok(file) => { - let exprs = collect_exprs(file); - test_expressions(exprs) - } - Err(msg) => { - errorf!("syn failed to parse\n{:?}\n", msg); - (0, 1) - } - }; - - errorf!( - "=== {}: {} passed | {} failed\n", - path.display(), - l_passed, - l_failed - ); - - passed.fetch_add(l_passed, Ordering::SeqCst); - let prev_failed = failed.fetch_add(l_failed, Ordering::SeqCst); - - if prev_failed + l_failed >= abort_after { - process::exit(1); - } - }); - - let passed = passed.load(Ordering::SeqCst); - let failed = failed.load(Ordering::SeqCst); - - errorf!("\n===== Precedence Test Results =====\n"); - errorf!("{} passed | {} failed\n", passed, failed); - - if failed > 0 { - panic!("{} failures", failed); - } -} - -fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) { - let mut passed = 0; - let mut failed = 0; - - syntax::with_globals(Edition::Edition2018, || { - for expr in exprs { - let raw = quote!(#expr).to_string(); - - let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) { - e - } else { - failed += 1; - errorf!("\nFAIL - libsyntax failed to parse raw\n"); - continue; - }; - - let syn_expr = syn_brackets(expr); - let syn_ast = if let Some(e) = parse::libsyntax_expr("e!(#syn_expr).to_string()) { - e - } else { - failed += 1; - errorf!("\nFAIL - libsyntax failed to parse bracketed\n"); - continue; - }; - - if SpanlessEq::eq(&syn_ast, &libsyntax_ast) { - passed += 1; - } else { - failed += 1; - errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast); - } - } - }); - - (passed, failed) -} - -fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> { - parse::libsyntax_expr(input).and_then(libsyntax_brackets) -} - -/// Wrap every expression which is not already wrapped in parens with parens, to -/// reveal the precidence of the parsed expressions, and produce a stringified -/// form of the resulting expression. -/// -/// This method operates on libsyntax objects. -fn libsyntax_brackets(mut libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> { - use rustc_data_structures::thin_vec::ThinVec; - use smallvec::SmallVec; - use std::mem; - use syntax::ast::{AwaitOrigin, Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty}; - use syntax::mut_visit::{self, MutVisitor}; - use syntax_pos::DUMMY_SP; - - struct BracketsVisitor { - failed: bool, - }; - - impl BracketsVisitor { - fn recurse_expr(&mut self, e: &mut Expr) { - match e.node { - ExprKind::Await(AwaitOrigin::MacroLike, _) => { - // Syn sees await!() as macro and doesn't recurse inside, so - // skip it here too. - } - _ => mut_visit::noop_visit_expr(e, self), - } - } - } - - impl MutVisitor for BracketsVisitor { - fn visit_expr(&mut self, e: &mut P<Expr>) { - self.recurse_expr(e); - match e.node { - ExprKind::If(..) | ExprKind::Block(..) | ExprKind::Let(..) => {} - _ => { - let inner = mem::replace( - e, - P(Expr { - id: ast::DUMMY_NODE_ID, - node: ExprKind::Err, - span: DUMMY_SP, - attrs: ThinVec::new(), - }), - ); - e.node = ExprKind::Paren(inner); - } - } - } - - fn visit_field(&mut self, f: &mut Field) { - if f.is_shorthand { - self.recurse_expr(&mut f.expr); - } else { - self.visit_expr(&mut f.expr); - } - } - - // We don't want to look at expressions that might appear in patterns or - // types yet. We'll look into comparing those in the future. For now - // focus on expressions appearing in other places. - fn visit_pat(&mut self, pat: &mut P<Pat>) { - let _ = pat; - } - - fn visit_ty(&mut self, ty: &mut P<Ty>) { - let _ = ty; - } - - fn flat_map_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> { - let node = match stmt.node { - // Don't wrap toplevel expressions in statements. - StmtKind::Expr(mut e) => { - self.recurse_expr(&mut e); - StmtKind::Expr(e) - } - StmtKind::Semi(mut e) => { - self.recurse_expr(&mut e); - StmtKind::Semi(e) - } - s => s, - }; - - smallvec![Stmt { node, ..stmt }] - } - - fn visit_mac(&mut self, mac: &mut Mac) { - // By default when folding over macros, libsyntax panics. This is - // because it's usually not what you want, you want to run after - // macro expansion. We do want to do that (syn doesn't do macro - // expansion), so we implement visit_mac to just return the macro - // unchanged. - let _ = mac; - } - } - - let mut folder = BracketsVisitor { failed: false }; - folder.visit_expr(&mut libsyntax_expr); - if folder.failed { - None - } else { - Some(libsyntax_expr) - } -} - -/// Wrap every expression which is not already wrapped in parens with parens, to -/// reveal the precedence of the parsed expressions, and produce a stringified -/// form of the resulting expression. -fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr { - use syn::fold::*; - use syn::*; - - struct ParenthesizeEveryExpr; - impl Fold for ParenthesizeEveryExpr { - fn fold_expr(&mut self, expr: Expr) -> Expr { - match expr { - Expr::Group(_) => unreachable!(), - Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::Let(..) => { - fold_expr(self, expr) - } - node => Expr::Paren(ExprParen { - attrs: Vec::new(), - expr: Box::new(fold_expr(self, node)), - paren_token: token::Paren::default(), - }), - } - } - - fn fold_stmt(&mut self, stmt: Stmt) -> Stmt { - match stmt { - // Don't wrap toplevel expressions in statements. - Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)), - Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi), - s => s, - } - } - - // We don't want to look at expressions that might appear in patterns or - // types yet. We'll look into comparing those in the future. For now - // focus on expressions appearing in other places. - fn fold_pat(&mut self, pat: Pat) -> Pat { - pat - } - - fn fold_type(&mut self, ty: Type) -> Type { - ty - } - } - - let mut folder = ParenthesizeEveryExpr; - folder.fold_expr(syn_expr) -} - -/// Walk through a crate collecting all expressions we can find in it. -fn collect_exprs(file: syn::File) -> Vec<syn::Expr> { - use syn::fold::*; - use syn::punctuated::Punctuated; - use syn::*; - - struct CollectExprs(Vec<Expr>); - impl Fold for CollectExprs { - fn fold_expr(&mut self, expr: Expr) -> Expr { - self.0.push(expr); - - Expr::Tuple(ExprTuple { - attrs: vec![], - elems: Punctuated::new(), - paren_token: token::Paren::default(), - }) - } - } - - let mut folder = CollectExprs(vec![]); - folder.fold_file(file); - folder.0 -} diff --git a/0.15.42/tests/test_round_trip.rs b/0.15.42/tests/test_round_trip.rs deleted file mode 100644 index 2fc9cecd..00000000 --- a/0.15.42/tests/test_round_trip.rs +++ /dev/null @@ -1,153 +0,0 @@ -#![cfg(not(syn_disable_nightly_tests))] -#![recursion_limit = "1024"] -#![feature(rustc_private)] - -extern crate quote; -extern crate rayon; -extern crate syn; -extern crate syntax; -extern crate syntax_pos; -extern crate walkdir; - -mod features; - -use quote::quote; -use rayon::iter::{IntoParallelIterator, ParallelIterator}; -use syntax::ast; -use syntax::parse::{self, PResult, ParseSess}; -use syntax::source_map::FilePathMapping; -use syntax_pos::edition::Edition; -use syntax_pos::FileName; -use walkdir::{DirEntry, WalkDir}; - -use std::fs::File; -use std::io::Read; -use std::panic; -use std::process; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::Instant; - -#[macro_use] -mod macros; - -#[allow(dead_code)] -mod common; - -mod repo; - -use common::eq::SpanlessEq; - -#[test] -#[cfg_attr(target_os = "windows", ignore = "requires nix .sh")] -fn test_round_trip() { - repo::clone_rust(); - let abort_after = common::abort_after(); - if abort_after == 0 { - panic!("Skipping all round_trip tests"); - } - - let failed = AtomicUsize::new(0); - - WalkDir::new("tests/rust") - .sort_by(|a, b| a.file_name().cmp(b.file_name())) - .into_iter() - .filter_entry(repo::base_dir_filter) - .collect::<Result<Vec<DirEntry>, walkdir::Error>>() - .unwrap() - .into_par_iter() - .for_each(|entry| { - let path = entry.path(); - if path.is_dir() { - return; - } - - let mut file = File::open(path).unwrap(); - let mut content = String::new(); - file.read_to_string(&mut content).unwrap(); - - let start = Instant::now(); - let (krate, elapsed) = match syn::parse_file(&content) { - Ok(krate) => (krate, start.elapsed()), - Err(msg) => { - errorf!("=== {}: syn failed to parse\n{:?}\n", path.display(), msg); - let prev_failed = failed.fetch_add(1, Ordering::SeqCst); - if prev_failed + 1 >= abort_after { - process::exit(1); - } - return; - } - }; - let back = quote!(#krate).to_string(); - - let equal = panic::catch_unwind(|| { - syntax::with_globals(Edition::Edition2018, || { - let sess = ParseSess::new(FilePathMapping::empty()); - let before = match libsyntax_parse(content, &sess) { - Ok(before) => before, - Err(mut diagnostic) => { - diagnostic.cancel(); - if diagnostic - .message() - .starts_with("file not found for module") - { - errorf!("=== {}: ignore\n", path.display()); - } else { - errorf!( - "=== {}: ignore - libsyntax failed to parse original content: {}\n", - path.display(), - diagnostic.message() - ); - } - return true; - } - }; - let after = match libsyntax_parse(back, &sess) { - Ok(after) => after, - Err(mut diagnostic) => { - errorf!("=== {}: libsyntax failed to parse", path.display()); - diagnostic.emit(); - return false; - } - }; - - if SpanlessEq::eq(&before, &after) { - errorf!( - "=== {}: pass in {}ms\n", - path.display(), - elapsed.as_secs() * 1000 - + u64::from(elapsed.subsec_nanos()) / 1_000_000 - ); - true - } else { - errorf!( - "=== {}: FAIL\nbefore: {:#?}\nafter: {:#?}\n", - path.display(), - before, - after, - ); - false - } - }) - }); - match equal { - Err(_) => errorf!("=== {}: ignoring libsyntax panic\n", path.display()), - Ok(true) => {} - Ok(false) => { - let prev_failed = failed.fetch_add(1, Ordering::SeqCst); - if prev_failed + 1 >= abort_after { - process::exit(1); - } - } - } - }); - - let failed = failed.load(Ordering::SeqCst); - if failed > 0 { - panic!("{} failures", failed); - } -} - -fn libsyntax_parse(content: String, sess: &ParseSess) -> PResult<ast::Crate> { - let name = FileName::Custom("test_round_trip".to_string()); - parse::parse_crate_from_source_str(name, content, sess) -} diff --git a/0.15.42/tests/test_should_parse.rs b/0.15.42/tests/test_should_parse.rs deleted file mode 100644 index aadf42e3..00000000 --- a/0.15.42/tests/test_should_parse.rs +++ /dev/null @@ -1,49 +0,0 @@ -extern crate syn; - -mod features; - -macro_rules! should_parse { - ($name:ident, { $($in:tt)* }) => { - #[test] - fn $name() { - // Make sure we can parse the file! - syn::parse_file(stringify!($($in)*)).unwrap(); - } - } -} - -should_parse!(generic_associated_type, { - impl Foo { - type Item = &'a i32; - fn foo<'a>(&'a self) -> Self::Item<'a> {} - } -}); - -#[rustfmt::skip] -should_parse!(const_generics_use, { - type X = Foo<5>; - type Y = Foo<"foo">; - type Z = Foo<X>; - type W = Foo<{ X + 10 }>; -}); - -should_parse!(trailing_plus_type, { - type A = Box<Foo>; - type A = Box<Foo + 'a>; - type A = Box<'a + Foo>; -}); - -should_parse!(generic_associated_type_where, { - trait Foo { - type Item; - fn foo<T>(&self, t: T) -> Self::Item<T>; - } -}); - -should_parse!(match_with_block_expr, { - fn main() { - match false { - _ => {}.a(), - } - } -}); diff --git a/0.15.42/tests/test_token_trees.rs b/0.15.42/tests/test_token_trees.rs deleted file mode 100644 index 70a9a72a..00000000 --- a/0.15.42/tests/test_token_trees.rs +++ /dev/null @@ -1,32 +0,0 @@ -extern crate proc_macro2; -extern crate quote; -extern crate syn; - -mod features; - -#[macro_use] -mod macros; - -use proc_macro2::TokenStream; -use quote::quote; -use syn::Lit; - -#[test] -fn test_struct() { - let input = " - #[derive(Debug, Clone)] - pub struct Item { - pub ident: Ident, - pub attrs: Vec<Attribute>, - } - "; - - snapshot!(input as TokenStream, @"`# [ derive ( Debug , Clone ) ] pub struct Item { pub ident : Ident , pub attrs : Vec < Attribute >, }`"); -} - -#[test] -fn test_literal_mangling() { - let code = "0_4"; - let parsed: Lit = syn::parse_str(code).unwrap(); - assert_eq!(code, quote!(#parsed).to_string()); -} diff --git a/0.15.42/tests/zzz_stable.rs b/0.15.42/tests/zzz_stable.rs deleted file mode 100644 index a81b3df4..00000000 --- a/0.15.42/tests/zzz_stable.rs +++ /dev/null @@ -1,35 +0,0 @@ -#![cfg(syn_disable_nightly_tests)] - -extern crate termcolor; - -use std::io::{self, Write}; -use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; - -const MSG: &str = "\ -‖ -‖ WARNING: -‖ This is not a nightly compiler so not all tests were able to -‖ run. Syn includes tests that compare Syn's parser against the -‖ compiler's parser, which requires access to unstable libsyntax -‖ data structures and a nightly compiler. -‖ -"; - -#[test] -fn notice() -> io::Result<()> { - let header = "WARNING"; - let index_of_header = MSG.find(header).unwrap(); - let before = &MSG[..index_of_header]; - let after = &MSG[index_of_header + header.len()..]; - - let mut stderr = StandardStream::stderr(ColorChoice::Auto); - stderr.set_color(ColorSpec::new().set_fg(Some(Color::Yellow)))?; - write!(&mut stderr, "{}", before)?; - stderr.set_color(ColorSpec::new().set_bold(true).set_fg(Some(Color::Yellow)))?; - write!(&mut stderr, "{}", header)?; - stderr.set_color(ColorSpec::new().set_fg(Some(Color::Yellow)))?; - write!(&mut stderr, "{}", after)?; - stderr.reset()?; - - Ok(()) -} diff --git a/1.0.7/.cargo_vcs_info.json b/1.0.7/.cargo_vcs_info.json deleted file mode 100644 index c053ad6a..00000000 --- a/1.0.7/.cargo_vcs_info.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "git": { - "sha1": "b06fef4bd130b74cf47b44a68e76522a45bec18d" - } -} diff --git a/1.0.7/Android.bp b/1.0.7/Android.bp deleted file mode 100644 index 55198eb8..00000000 --- a/1.0.7/Android.bp +++ /dev/null @@ -1,29 +0,0 @@ -// This file is generated by cargo2android.py. - -rust_library_host_rlib { - name: "libsyn-1.0.7", - crate_name: "syn", - srcs: ["src/lib.rs"], - edition: "2018", - features: [ - "clone-impls", - "default", - "derive", - "extra-traits", - "full", - "parsing", - "printing", - "proc-macro", - "quote", - "visit", - "visit-mut", - ], - flags: [ - "--cfg syn_disable_nightly_tests", - ], - rlibs: [ - "libproc_macro2", - "libquote", - "libunicode_xid", - ], -} diff --git a/1.0.7/LICENSE-APACHE b/1.0.7/LICENSE-APACHE deleted file mode 100644 index 16fe87b0..00000000 --- a/1.0.7/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/1.0.7/LICENSE-MIT b/1.0.7/LICENSE-MIT deleted file mode 100644 index 31aa7938..00000000 --- a/1.0.7/LICENSE-MIT +++ /dev/null @@ -1,23 +0,0 @@ -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/1.0.7/benches/rust.rs b/1.0.7/benches/rust.rs deleted file mode 100644 index e3d9cd29..00000000 --- a/1.0.7/benches/rust.rs +++ /dev/null @@ -1,147 +0,0 @@ -// $ cargo bench --features full --bench rust -// -// Syn only, useful for profiling: -// $ RUSTFLAGS='--cfg syn_only' cargo build --release --features full --bench rust - -#![cfg_attr(not(syn_only), feature(rustc_private))] - -#[path = "../tests/repo/mod.rs"] -mod repo; - -use std::fs; -use std::time::{Duration, Instant}; - -#[cfg(not(syn_only))] -mod tokenstream_parse { - use proc_macro2::TokenStream; - use std::str::FromStr; - - pub fn bench(content: &str) -> Result<(), ()> { - TokenStream::from_str(content).map(drop).map_err(drop) - } -} - -mod syn_parse { - pub fn bench(content: &str) -> Result<(), ()> { - syn::parse_file(content).map(drop).map_err(drop) - } -} - -#[cfg(not(syn_only))] -mod libsyntax_parse { - extern crate rustc_data_structures; - extern crate syntax; - extern crate syntax_pos; - - use rustc_data_structures::sync::Lrc; - use syntax::edition::Edition; - use syntax::errors::{emitter::Emitter, DiagnosticBuilder, Handler}; - use syntax::parse::ParseSess; - use syntax::source_map::{FilePathMapping, SourceMap}; - use syntax_pos::FileName; - - pub fn bench(content: &str) -> Result<(), ()> { - struct SilentEmitter; - - impl Emitter for SilentEmitter { - fn emit_diagnostic(&mut self, _db: &DiagnosticBuilder) {} - } - - syntax::with_globals(Edition::Edition2018, || { - let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let emitter = Box::new(SilentEmitter); - let handler = Handler::with_emitter(false, None, emitter); - let sess = ParseSess::with_span_handler(handler, cm); - if let Err(mut diagnostic) = syntax::parse::parse_crate_from_source_str( - FileName::Custom("bench".to_owned()), - content.to_owned(), - &sess, - ) { - diagnostic.cancel(); - return Err(()); - }; - Ok(()) - }) - } -} - -#[cfg(not(syn_only))] -mod read_from_disk { - pub fn bench(content: &str) -> Result<(), ()> { - let _ = content; - Ok(()) - } -} - -fn exec(mut codepath: impl FnMut(&str) -> Result<(), ()>) -> Duration { - let begin = Instant::now(); - let mut success = 0; - let mut total = 0; - - walkdir::WalkDir::new("tests/rust/src") - .into_iter() - .filter_entry(repo::base_dir_filter) - .for_each(|entry| { - let entry = entry.unwrap(); - let path = entry.path(); - if path.is_dir() { - return; - } - let content = fs::read_to_string(path).unwrap(); - let ok = codepath(&content).is_ok(); - success += ok as usize; - total += 1; - if !ok { - eprintln!("FAIL {}", path.display()); - } - }); - - assert_eq!(success, total); - begin.elapsed() -} - -fn main() { - repo::clone_rust(); - - macro_rules! testcases { - ($($(#[$cfg:meta])* $name:path,)*) => { - vec![ - $( - $(#[$cfg])* - (stringify!($name), $name as fn(&str) -> Result<(), ()>), - )* - ] - }; - } - - #[cfg(not(syn_only))] - { - let mut lines = 0; - let mut files = 0; - exec(|content| { - lines += content.lines().count(); - files += 1; - Ok(()) - }); - eprintln!("\n{} lines in {} files", lines, files); - } - - for (name, f) in testcases!( - #[cfg(not(syn_only))] - read_from_disk::bench, - #[cfg(not(syn_only))] - tokenstream_parse::bench, - syn_parse::bench, - #[cfg(not(syn_only))] - libsyntax_parse::bench, - ) { - eprint!("{:20}", format!("{}:", name)); - let elapsed = exec(f); - eprintln!( - "elapsed={}.{:03}s", - elapsed.as_secs(), - elapsed.subsec_millis(), - ); - } - eprintln!(); -} diff --git a/1.0.7/src/keyword.rs b/1.0.7/src/keyword.rs deleted file mode 100644 index e69de29b..00000000 --- a/1.0.7/src/keyword.rs +++ /dev/null diff --git a/1.0.7/src/sealed.rs b/1.0.7/src/sealed.rs deleted file mode 100644 index 0b11bc99..00000000 --- a/1.0.7/src/sealed.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[cfg(feature = "parsing")] -pub mod lookahead { - pub trait Sealed: Copy {} -} diff --git a/1.0.7/src/span.rs b/1.0.7/src/span.rs deleted file mode 100644 index 27a7fe84..00000000 --- a/1.0.7/src/span.rs +++ /dev/null @@ -1,67 +0,0 @@ -use proc_macro2::Span; - -pub trait IntoSpans<S> { - fn into_spans(self) -> S; -} - -impl IntoSpans<[Span; 1]> for Span { - fn into_spans(self) -> [Span; 1] { - [self] - } -} - -impl IntoSpans<[Span; 2]> for Span { - fn into_spans(self) -> [Span; 2] { - [self, self] - } -} - -impl IntoSpans<[Span; 3]> for Span { - fn into_spans(self) -> [Span; 3] { - [self, self, self] - } -} - -impl IntoSpans<[Span; 1]> for [Span; 1] { - fn into_spans(self) -> [Span; 1] { - self - } -} - -impl IntoSpans<[Span; 2]> for [Span; 2] { - fn into_spans(self) -> [Span; 2] { - self - } -} - -impl IntoSpans<[Span; 3]> for [Span; 3] { - fn into_spans(self) -> [Span; 3] { - self - } -} - -#[cfg(feature = "parsing")] -pub trait FromSpans: Sized { - fn from_spans(spans: &[Span]) -> Self; -} - -#[cfg(feature = "parsing")] -impl FromSpans for [Span; 1] { - fn from_spans(spans: &[Span]) -> Self { - [spans[0]] - } -} - -#[cfg(feature = "parsing")] -impl FromSpans for [Span; 2] { - fn from_spans(spans: &[Span]) -> Self { - [spans[0], spans[1]] - } -} - -#[cfg(feature = "parsing")] -impl FromSpans for [Span; 3] { - fn from_spans(spans: &[Span]) -> Self { - [spans[0], spans[1], spans[2]] - } -} diff --git a/1.0.7/tests/clone.sh b/1.0.7/tests/clone.sh deleted file mode 100755 index 03d0c224..00000000 --- a/1.0.7/tests/clone.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -REV=7979016aff545f7b41cc517031026020b340989d - -set -euo pipefail -cd "$(dirname "${BASH_SOURCE[0]}")" -mkdir -p rust -touch rust/COMMIT - -if [ "$(cat rust/COMMIT)" != "$REV" ]; then - rm -rf rust - mkdir rust - curl -L "https://github.com/rust-lang/rust/archive/${REV}.tar.gz" \ - | tar xz --directory rust --strip-components 1 - echo "$REV" > rust/COMMIT -fi diff --git a/1.0.7/tests/common/eq.rs b/1.0.7/tests/common/eq.rs deleted file mode 100644 index 199e0fe6..00000000 --- a/1.0.7/tests/common/eq.rs +++ /dev/null @@ -1,458 +0,0 @@ -extern crate rustc_data_structures; -extern crate rustc_target; -extern crate syntax; -extern crate syntax_pos; - -use std::mem; - -use rustc_data_structures::sync::Lrc; -use rustc_data_structures::thin_vec::ThinVec; -use rustc_target::abi::FloatTy; -use rustc_target::spec::abi::Abi; -use syntax::ast::{ - AngleBracketedArgs, AnonConst, Arm, AsmDialect, AssocTyConstraint, AssocTyConstraintKind, - AttrId, AttrItem, AttrStyle, Attribute, BareFnTy, BinOpKind, BindingMode, Block, - BlockCheckMode, CaptureBy, Constness, Crate, CrateSugar, Defaultness, EnumDef, Expr, ExprKind, - Field, FieldPat, FnDecl, FnHeader, ForeignItem, ForeignItemKind, ForeignMod, FunctionRetTy, - GenericArg, GenericArgs, GenericBound, GenericParam, GenericParamKind, Generics, GlobalAsm, - Ident, ImplItem, ImplItemKind, ImplPolarity, InlineAsm, InlineAsmOutput, IntTy, IsAsync, - IsAuto, Item, ItemKind, Label, Lifetime, Lit, LitIntType, LitKind, Local, Mac, MacDelimiter, - MacStmtStyle, MacroDef, MethodSig, Mod, Movability, MutTy, Mutability, NodeId, Param, - ParenthesizedArgs, Pat, PatKind, Path, PathSegment, PolyTraitRef, QSelf, RangeEnd, RangeLimits, - RangeSyntax, Stmt, StmtKind, StrStyle, StructField, TraitBoundModifier, TraitItem, - TraitItemKind, TraitObjectSyntax, TraitRef, Ty, TyKind, UintTy, UnOp, UnsafeSource, Unsafety, - UseTree, UseTreeKind, Variant, VariantData, VisibilityKind, WhereBoundPredicate, WhereClause, - WhereEqPredicate, WherePredicate, WhereRegionPredicate, -}; -use syntax::parse::lexer::comments; -use syntax::parse::token::{self, DelimToken, Token, TokenKind}; -use syntax::ptr::P; -use syntax::source_map::Spanned; -use syntax::symbol::{sym, Symbol}; -use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree}; -use syntax_pos::{Span, SyntaxContext, DUMMY_SP}; - -pub trait SpanlessEq { - fn eq(&self, other: &Self) -> bool; -} - -impl<T: SpanlessEq> SpanlessEq for P<T> { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&**self, &**other) - } -} - -impl<T: SpanlessEq> SpanlessEq for Lrc<T> { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&**self, &**other) - } -} - -impl<T: SpanlessEq> SpanlessEq for Option<T> { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (None, None) => true, - (Some(this), Some(other)) => SpanlessEq::eq(this, other), - _ => false, - } - } -} - -impl<T: SpanlessEq> SpanlessEq for Vec<T> { - fn eq(&self, other: &Self) -> bool { - self.len() == other.len() && self.iter().zip(other).all(|(a, b)| SpanlessEq::eq(a, b)) - } -} - -impl<T: SpanlessEq> SpanlessEq for ThinVec<T> { - fn eq(&self, other: &Self) -> bool { - self.len() == other.len() - && self - .iter() - .zip(other.iter()) - .all(|(a, b)| SpanlessEq::eq(a, b)) - } -} - -impl<T: SpanlessEq> SpanlessEq for Spanned<T> { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&self.node, &other.node) - } -} - -impl<A: SpanlessEq, B: SpanlessEq> SpanlessEq for (A, B) { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&self.0, &other.0) && SpanlessEq::eq(&self.1, &other.1) - } -} - -impl<A: SpanlessEq, B: SpanlessEq, C: SpanlessEq> SpanlessEq for (A, B, C) { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&self.0, &other.0) - && SpanlessEq::eq(&self.1, &other.1) - && SpanlessEq::eq(&self.2, &other.2) - } -} - -macro_rules! spanless_eq_true { - ($name:ident) => { - impl SpanlessEq for $name { - fn eq(&self, _other: &Self) -> bool { - true - } - } - }; -} - -spanless_eq_true!(Span); -spanless_eq_true!(DelimSpan); -spanless_eq_true!(AttrId); -spanless_eq_true!(NodeId); -spanless_eq_true!(SyntaxContext); - -macro_rules! spanless_eq_partial_eq { - ($name:ident) => { - impl SpanlessEq for $name { - fn eq(&self, other: &Self) -> bool { - PartialEq::eq(self, other) - } - } - }; -} - -spanless_eq_partial_eq!(bool); -spanless_eq_partial_eq!(u8); -spanless_eq_partial_eq!(u16); -spanless_eq_partial_eq!(u128); -spanless_eq_partial_eq!(usize); -spanless_eq_partial_eq!(char); -spanless_eq_partial_eq!(Symbol); -spanless_eq_partial_eq!(Abi); -spanless_eq_partial_eq!(DelimToken); - -macro_rules! spanless_eq_struct { - { - $name:ident; - $([$field:ident $other:ident])* - $(![$ignore:ident])* - } => { - impl SpanlessEq for $name { - fn eq(&self, other: &Self) -> bool { - let $name { $($field,)* $($ignore: _,)* } = self; - let $name { $($field: $other,)* $($ignore: _,)* } = other; - $(SpanlessEq::eq($field, $other))&&* - } - } - }; - - { - $name:ident; - $([$field:ident $other:ident])* - $next:ident - $($rest:ident)* - $(!$ignore:ident)* - } => { - spanless_eq_struct! { - $name; - $([$field $other])* - [$next other] - $($rest)* - $(!$ignore)* - } - }; - - { - $name:ident; - $([$field:ident $other:ident])* - $(![$ignore:ident])* - !$next:ident - $(!$rest:ident)* - } => { - spanless_eq_struct! { - $name; - $([$field $other])* - $(![$ignore])* - ![$next] - $(!$rest)* - } - }; -} - -macro_rules! spanless_eq_enum { - { - $name:ident; - $([$variant:ident $([$field:tt $this:ident $other:ident])*])* - } => { - impl SpanlessEq for $name { - fn eq(&self, other: &Self) -> bool { - match self { - $( - $name::$variant { .. } => {} - )* - } - #[allow(unreachable_patterns)] - match (self, other) { - $( - ( - $name::$variant { $($field: $this),* }, - $name::$variant { $($field: $other),* }, - ) => { - true $(&& SpanlessEq::eq($this, $other))* - } - )* - _ => false, - } - } - } - }; - - { - $name:ident; - $([$variant:ident $($fields:tt)*])* - $next:ident [$($named:tt)*] ( $i:tt $($field:tt)* ) - $($rest:tt)* - } => { - spanless_eq_enum! { - $name; - $([$variant $($fields)*])* - $next [$($named)* [$i this other]] ( $($field)* ) - $($rest)* - } - }; - - { - $name:ident; - $([$variant:ident $($fields:tt)*])* - $next:ident [$($named:tt)*] () - $($rest:tt)* - } => { - spanless_eq_enum! { - $name; - $([$variant $($fields)*])* - [$next $($named)*] - $($rest)* - } - }; - - { - $name:ident; - $([$variant:ident $($fields:tt)*])* - $next:ident ( $($field:tt)* ) - $($rest:tt)* - } => { - spanless_eq_enum! { - $name; - $([$variant $($fields)*])* - $next [] ( $($field)* ) - $($rest)* - } - }; - - { - $name:ident; - $([$variant:ident $($fields:tt)*])* - $next:ident - $($rest:tt)* - } => { - spanless_eq_enum! { - $name; - $([$variant $($fields)*])* - [$next] - $($rest)* - } - }; -} - -spanless_eq_struct!(AngleBracketedArgs; span args constraints); -spanless_eq_struct!(AnonConst; id value); -spanless_eq_struct!(Arm; attrs pat guard body span id is_placeholder); -spanless_eq_struct!(AssocTyConstraint; id ident kind span); -spanless_eq_struct!(AttrItem; path tokens); -spanless_eq_struct!(Attribute; item id style span !is_sugared_doc); -spanless_eq_struct!(BareFnTy; unsafety abi generic_params decl); -spanless_eq_struct!(Block; stmts id rules span); -spanless_eq_struct!(Crate; module attrs span); -spanless_eq_struct!(EnumDef; variants); -spanless_eq_struct!(Expr; id kind span attrs); -spanless_eq_struct!(Field; ident expr span is_shorthand attrs id is_placeholder); -spanless_eq_struct!(FieldPat; ident pat is_shorthand attrs id span is_placeholder); -spanless_eq_struct!(FnDecl; inputs output); -spanless_eq_struct!(FnHeader; constness asyncness unsafety abi); -spanless_eq_struct!(ForeignItem; ident attrs kind id span vis); -spanless_eq_struct!(ForeignMod; abi items); -spanless_eq_struct!(GenericParam; id ident attrs bounds is_placeholder kind); -spanless_eq_struct!(Generics; params where_clause span); -spanless_eq_struct!(GlobalAsm; asm); -spanless_eq_struct!(ImplItem; id ident vis defaultness attrs generics kind span !tokens); -spanless_eq_struct!(InlineAsm; asm asm_str_style outputs inputs clobbers volatile alignstack dialect); -spanless_eq_struct!(InlineAsmOutput; constraint expr is_rw is_indirect); -spanless_eq_struct!(Item; ident attrs id kind vis span !tokens); -spanless_eq_struct!(Label; ident); -spanless_eq_struct!(Lifetime; id ident); -spanless_eq_struct!(Lit; token kind span); -spanless_eq_struct!(Local; pat ty init id span attrs); -spanless_eq_struct!(Mac; path delim tts span prior_type_ascription); -spanless_eq_struct!(MacroDef; tokens legacy); -spanless_eq_struct!(MethodSig; header decl); -spanless_eq_struct!(Mod; inner items inline); -spanless_eq_struct!(MutTy; ty mutbl); -spanless_eq_struct!(Param; attrs ty pat id span is_placeholder); -spanless_eq_struct!(ParenthesizedArgs; span inputs output); -spanless_eq_struct!(Pat; id kind span); -spanless_eq_struct!(Path; span segments); -spanless_eq_struct!(PathSegment; ident id args); -spanless_eq_struct!(PolyTraitRef; bound_generic_params trait_ref span); -spanless_eq_struct!(QSelf; ty path_span position); -spanless_eq_struct!(Stmt; id kind span); -spanless_eq_struct!(StructField; span ident vis id ty attrs is_placeholder); -spanless_eq_struct!(Token; kind span); -spanless_eq_struct!(TraitItem; id ident attrs generics kind span !tokens); -spanless_eq_struct!(TraitRef; path ref_id); -spanless_eq_struct!(Ty; id kind span); -spanless_eq_struct!(UseTree; prefix kind span); -spanless_eq_struct!(Variant; ident attrs id data disr_expr span is_placeholder); -spanless_eq_struct!(WhereBoundPredicate; span bound_generic_params bounded_ty bounds); -spanless_eq_struct!(WhereClause; predicates span); -spanless_eq_struct!(WhereEqPredicate; id span lhs_ty rhs_ty); -spanless_eq_struct!(WhereRegionPredicate; span lifetime bounds); -spanless_eq_enum!(AsmDialect; Att Intel); -spanless_eq_enum!(AssocTyConstraintKind; Equality(ty) Bound(bounds)); -spanless_eq_enum!(AttrStyle; Outer Inner); -spanless_eq_enum!(BinOpKind; Add Sub Mul Div Rem And Or BitXor BitAnd BitOr Shl Shr Eq Lt Le Ne Ge Gt); -spanless_eq_enum!(BindingMode; ByRef(0) ByValue(0)); -spanless_eq_enum!(BlockCheckMode; Default Unsafe(0)); -spanless_eq_enum!(CaptureBy; Value Ref); -spanless_eq_enum!(Constness; Const NotConst); -spanless_eq_enum!(CrateSugar; PubCrate JustCrate); -spanless_eq_enum!(Defaultness; Default Final); -spanless_eq_enum!(FloatTy; F32 F64); -spanless_eq_enum!(ForeignItemKind; Fn(0 1) Static(0 1) Ty Macro(0)); -spanless_eq_enum!(FunctionRetTy; Default(0) Ty(0)); -spanless_eq_enum!(GenericArg; Lifetime(0) Type(0) Const(0)); -spanless_eq_enum!(GenericArgs; AngleBracketed(0) Parenthesized(0)); -spanless_eq_enum!(GenericBound; Trait(0 1) Outlives(0)); -spanless_eq_enum!(GenericParamKind; Lifetime Type(default) Const(ty)); -spanless_eq_enum!(ImplItemKind; Const(0 1) Method(0 1) TyAlias(0) OpaqueTy(0) Macro(0)); -spanless_eq_enum!(ImplPolarity; Positive Negative); -spanless_eq_enum!(IntTy; Isize I8 I16 I32 I64 I128); -spanless_eq_enum!(IsAsync; Async(closure_id return_impl_trait_id) NotAsync); -spanless_eq_enum!(IsAuto; Yes No); -spanless_eq_enum!(LitIntType; Signed(0) Unsigned(0) Unsuffixed); -spanless_eq_enum!(MacDelimiter; Parenthesis Bracket Brace); -spanless_eq_enum!(MacStmtStyle; Semicolon Braces NoBraces); -spanless_eq_enum!(Movability; Static Movable); -spanless_eq_enum!(Mutability; Mutable Immutable); -spanless_eq_enum!(RangeEnd; Included(0) Excluded); -spanless_eq_enum!(RangeLimits; HalfOpen Closed); -spanless_eq_enum!(StmtKind; Local(0) Item(0) Expr(0) Semi(0) Mac(0)); -spanless_eq_enum!(StrStyle; Cooked Raw(0)); -spanless_eq_enum!(TokenTree; Token(0) Delimited(0 1 2)); -spanless_eq_enum!(TraitBoundModifier; None Maybe); -spanless_eq_enum!(TraitItemKind; Const(0 1) Method(0 1) Type(0 1) Macro(0)); -spanless_eq_enum!(TraitObjectSyntax; Dyn None); -spanless_eq_enum!(UintTy; Usize U8 U16 U32 U64 U128); -spanless_eq_enum!(UnOp; Deref Not Neg); -spanless_eq_enum!(UnsafeSource; CompilerGenerated UserProvided); -spanless_eq_enum!(Unsafety; Unsafe Normal); -spanless_eq_enum!(UseTreeKind; Simple(0 1 2) Nested(0) Glob); -spanless_eq_enum!(VariantData; Struct(0 1) Tuple(0 1) Unit(0)); -spanless_eq_enum!(VisibilityKind; Public Crate(0) Restricted(path id) Inherited); -spanless_eq_enum!(WherePredicate; BoundPredicate(0) RegionPredicate(0) EqPredicate(0)); -spanless_eq_enum!(ExprKind; Box(0) Array(0) Call(0 1) MethodCall(0 1) Tup(0) - Binary(0 1 2) Unary(0 1) Lit(0) Cast(0 1) Type(0 1) Let(0 1) If(0 1 2) - While(0 1 2) ForLoop(0 1 2 3) Loop(0 1) Match(0 1) Closure(0 1 2 3 4 5) - Block(0 1) Async(0 1 2) Await(0) TryBlock(0) Assign(0 1) AssignOp(0 1 2) - Field(0 1) Index(0 1) Range(0 1 2) Path(0 1) AddrOf(0 1) Break(0 1) - Continue(0) Ret(0) InlineAsm(0) Mac(0) Struct(0 1 2) Repeat(0 1) Paren(0) - Try(0) Yield(0) Err); -spanless_eq_enum!(ItemKind; ExternCrate(0) Use(0) Static(0 1 2) Const(0 1) - Fn(0 1 2 3) Mod(0) ForeignMod(0) GlobalAsm(0) TyAlias(0 1) OpaqueTy(0 1) - Enum(0 1) Struct(0 1) Union(0 1) Trait(0 1 2 3 4) TraitAlias(0 1) - Impl(0 1 2 3 4 5 6) Mac(0) MacroDef(0)); -spanless_eq_enum!(LitKind; Str(0 1) ByteStr(0) Byte(0) Char(0) Int(0 1) - Float(0 1) FloatUnsuffixed(0) Bool(0) Err(0)); -spanless_eq_enum!(PatKind; Wild Ident(0 1 2) Struct(0 1 2) TupleStruct(0 1) - Or(0) Path(0 1) Tuple(0) Box(0) Ref(0 1) Lit(0) Range(0 1 2) Slice(0) Rest - Paren(0) Mac(0)); -spanless_eq_enum!(TyKind; Slice(0) Array(0 1) Ptr(0) Rptr(0 1) BareFn(0) Never - Tup(0) Path(0 1) TraitObject(0 1) ImplTrait(0 1) Paren(0) Typeof(0) Infer - ImplicitSelf Mac(0) Err CVarArgs); - -impl SpanlessEq for Ident { - fn eq(&self, other: &Self) -> bool { - self.as_str() == other.as_str() - } -} - -// Give up on comparing literals inside of macros because there are so many -// equivalent representations of the same literal; they are tested elsewhere -impl SpanlessEq for token::Lit { - fn eq(&self, other: &Self) -> bool { - mem::discriminant(self) == mem::discriminant(other) - } -} - -impl SpanlessEq for RangeSyntax { - fn eq(&self, _other: &Self) -> bool { - match self { - RangeSyntax::DotDotDot | RangeSyntax::DotDotEq => true, - } - } -} - -impl SpanlessEq for TokenKind { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (TokenKind::Literal(this), TokenKind::Literal(other)) => SpanlessEq::eq(this, other), - (TokenKind::DotDotEq, _) | (TokenKind::DotDotDot, _) => match other { - TokenKind::DotDotEq | TokenKind::DotDotDot => true, - _ => false, - }, - _ => self == other, - } - } -} - -impl SpanlessEq for TokenStream { - fn eq(&self, other: &Self) -> bool { - SpanlessEq::eq(&expand_tts(self), &expand_tts(other)) - } -} - -fn expand_tts(tts: &TokenStream) -> Vec<TokenTree> { - let mut tokens = Vec::new(); - for tt in tts.clone().into_trees() { - let c = match tt { - TokenTree::Token(Token { - kind: TokenKind::DocComment(c), - .. - }) => c, - _ => { - tokens.push(tt); - continue; - } - }; - let contents = comments::strip_doc_comment_decoration(&c.as_str()); - let style = comments::doc_comment_style(&c.as_str()); - tokens.push(TokenTree::token(TokenKind::Pound, DUMMY_SP)); - if style == AttrStyle::Inner { - tokens.push(TokenTree::token(TokenKind::Not, DUMMY_SP)); - } - let lit = token::Lit { - kind: token::LitKind::Str, - symbol: Symbol::intern(&contents), - suffix: None, - }; - let tts = vec![ - TokenTree::token(TokenKind::Ident(sym::doc, false), DUMMY_SP), - TokenTree::token(TokenKind::Eq, DUMMY_SP), - TokenTree::token(TokenKind::Literal(lit), DUMMY_SP), - ]; - tokens.push(TokenTree::Delimited( - DelimSpan::dummy(), - DelimToken::Bracket, - tts.into_iter().collect::<TokenStream>().into(), - )); - } - tokens -} diff --git a/1.0.7/tests/common/mod.rs b/1.0.7/tests/common/mod.rs deleted file mode 100644 index 8b784bee..00000000 --- a/1.0.7/tests/common/mod.rs +++ /dev/null @@ -1,14 +0,0 @@ -#![allow(dead_code)] - -use std::env; - -pub mod eq; -pub mod parse; - -/// Read the `ABORT_AFTER_FAILURE` environment variable, and parse it. -pub fn abort_after() -> usize { - match env::var("ABORT_AFTER_FAILURE") { - Ok(s) => s.parse().expect("failed to parse ABORT_AFTER_FAILURE"), - Err(_) => usize::max_value(), - } -} diff --git a/1.0.7/tests/features/error.rs b/1.0.7/tests/features/error.rs deleted file mode 100644 index 10ac8896..00000000 --- a/1.0.7/tests/features/error.rs +++ /dev/null @@ -1 +0,0 @@ -"Hello! You want: cargo test --release --all-features" diff --git a/1.0.7/tests/features/mod.rs b/1.0.7/tests/features/mod.rs deleted file mode 100644 index 83fbe13e..00000000 --- a/1.0.7/tests/features/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -#[allow(unused_macros)] -macro_rules! hide_from_rustfmt { - ($mod:item) => { - $mod - }; -} - -#[cfg(not(all( - feature = "derive", - feature = "full", - feature = "parsing", - feature = "printing", - feature = "visit", - feature = "visit-mut", - feature = "fold", - feature = "clone-impls", - feature = "extra-traits", - feature = "proc-macro", -)))] -hide_from_rustfmt! { - mod error; -} diff --git a/1.0.7/tests/repo/mod.rs b/1.0.7/tests/repo/mod.rs deleted file mode 100644 index 02b4e321..00000000 --- a/1.0.7/tests/repo/mod.rs +++ /dev/null @@ -1,60 +0,0 @@ -use std::process::Command; - -use walkdir::DirEntry; - -pub fn base_dir_filter(entry: &DirEntry) -> bool { - let path = entry.path(); - if path.is_dir() { - return true; // otherwise walkdir does not visit the files - } - if path.extension().map(|e| e != "rs").unwrap_or(true) { - return false; - } - let path_string = path.to_string_lossy(); - let path_string = if cfg!(windows) { - path_string.replace('\\', "/").into() - } else { - path_string - }; - // TODO assert that parsing fails on the parse-fail cases - if path_string.starts_with("tests/rust/src/test/parse-fail") - || path_string.starts_with("tests/rust/src/test/compile-fail") - || path_string.starts_with("tests/rust/src/test/rustfix") - { - return false; - } - - if path_string.starts_with("tests/rust/src/test/ui") { - let stderr_path = path.with_extension("stderr"); - if stderr_path.exists() { - // Expected to fail in some way - return false; - } - } - - match path_string.as_ref() { - // Deprecated placement syntax - "tests/rust/src/test/ui/obsolete-in-place/bad.rs" | - // Deprecated anonymous parameter syntax in traits - "tests/rust/src/test/ui/error-codes/e0119/auxiliary/issue-23563-a.rs" | - "tests/rust/src/test/ui/issues/issue-13105.rs" | - "tests/rust/src/test/ui/issues/issue-13775.rs" | - "tests/rust/src/test/ui/issues/issue-34074.rs" | - // Deprecated await macro syntax - "tests/rust/src/test/ui/async-await/await-macro.rs" | - // 2015-style dyn that libsyntax rejects - "tests/rust/src/test/ui/dyn-keyword/dyn-2015-no-warnings-without-lints.rs" | - // not actually test cases - "tests/rust/src/test/ui/include-single-expr-helper.rs" | - "tests/rust/src/test/ui/include-single-expr-helper-1.rs" | - "tests/rust/src/test/ui/issues/auxiliary/issue-21146-inc.rs" | - "tests/rust/src/test/ui/macros/auxiliary/macro-comma-support.rs" | - "tests/rust/src/test/ui/macros/auxiliary/macro-include-items-expr.rs" => false, - _ => true, - } -} - -pub fn clone_rust() { - let result = Command::new("tests/clone.sh").status().unwrap(); - assert!(result.success()); -} diff --git a/1.0.7/tests/test_expr.rs b/1.0.7/tests/test_expr.rs deleted file mode 100644 index 0edf6cee..00000000 --- a/1.0.7/tests/test_expr.rs +++ /dev/null @@ -1,37 +0,0 @@ -#[macro_use] -mod macros; - -use std::str::FromStr; - -use proc_macro2::TokenStream; -use syn::{Expr, ExprRange}; - -#[test] -fn test_expr_parse() { - let code = "..100u32"; - let tt = TokenStream::from_str(code).unwrap(); - let expr: Expr = syn::parse2(tt.clone()).unwrap(); - let expr_range: ExprRange = syn::parse2(tt).unwrap(); - assert_eq!(expr, Expr::Range(expr_range)); -} - -#[test] -fn test_await() { - // Must not parse as Expr::Field. - let expr = syn::parse_str::<Expr>("fut.await").unwrap(); - - snapshot!(expr, @r###" - Expr::Await { - base: Expr::Path { - path: Path { - segments: [ - PathSegment { - ident: "fut", - arguments: None, - }, - ], - }, - }, - } - "###); -} diff --git a/1.0.7/tests/test_parse_buffer.rs b/1.0.7/tests/test_parse_buffer.rs deleted file mode 100644 index d3f10c07..00000000 --- a/1.0.7/tests/test_parse_buffer.rs +++ /dev/null @@ -1,53 +0,0 @@ -use syn::parenthesized; -use syn::parse::{discouraged::Speculative, Parse, ParseStream, Parser, Result}; - -#[test] -#[should_panic(expected = "Fork was not derived from the advancing parse stream")] -fn smuggled_speculative_cursor_between_sources() { - struct BreakRules; - impl Parse for BreakRules { - fn parse(input1: ParseStream) -> Result<Self> { - let nested = |input2: ParseStream| { - input1.advance_to(&input2); - Ok(Self) - }; - nested.parse_str("") - } - } - - syn::parse_str::<BreakRules>("").unwrap(); -} - -#[test] -#[should_panic(expected = "Fork was not derived from the advancing parse stream")] -fn smuggled_speculative_cursor_between_brackets() { - struct BreakRules; - impl Parse for BreakRules { - fn parse(input: ParseStream) -> Result<Self> { - let a; - let b; - parenthesized!(a in input); - parenthesized!(b in input); - a.advance_to(&b); - Ok(Self) - } - } - - syn::parse_str::<BreakRules>("()()").unwrap(); -} - -#[test] -#[should_panic(expected = "Fork was not derived from the advancing parse stream")] -fn smuggled_speculative_cursor_into_brackets() { - struct BreakRules; - impl Parse for BreakRules { - fn parse(input: ParseStream) -> Result<Self> { - let a; - parenthesized!(a in input); - input.advance_to(&a); - Ok(Self) - } - } - - syn::parse_str::<BreakRules>("()").unwrap(); -} diff --git a/1.0.7/tests/test_pat.rs b/1.0.7/tests/test_pat.rs deleted file mode 100644 index cce4b809..00000000 --- a/1.0.7/tests/test_pat.rs +++ /dev/null @@ -1,20 +0,0 @@ -mod features; - -use quote::quote; -use syn::Pat; - -#[test] -fn test_pat_ident() { - match syn::parse2(quote!(self)).unwrap() { - Pat::Ident(_) => (), - value => panic!("expected PatIdent, got {:?}", value), - } -} - -#[test] -fn test_pat_path() { - match syn::parse2(quote!(self::CONST)).unwrap() { - Pat::Path(_) => (), - value => panic!("expected PatPath, got {:?}", value), - } -} diff --git a/1.0.7/tests/test_round_trip.rs b/1.0.7/tests/test_round_trip.rs deleted file mode 100644 index b6e8ee16..00000000 --- a/1.0.7/tests/test_round_trip.rs +++ /dev/null @@ -1,150 +0,0 @@ -#![cfg(not(syn_disable_nightly_tests))] -#![recursion_limit = "1024"] -#![feature(rustc_private)] - -extern crate syntax; -extern crate syntax_pos; - -mod features; - -use quote::quote; -use rayon::iter::{IntoParallelIterator, ParallelIterator}; -use syntax::ast; -use syntax::parse::{self, PResult}; -use syntax::sess::ParseSess; -use syntax::source_map::FilePathMapping; -use syntax_pos::edition::Edition; -use syntax_pos::FileName; -use walkdir::{DirEntry, WalkDir}; - -use std::fs::File; -use std::io::Read; -use std::panic; -use std::process; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::Instant; - -#[macro_use] -mod macros; - -#[allow(dead_code)] -mod common; - -mod repo; - -use common::eq::SpanlessEq; - -#[test] -#[cfg_attr(target_os = "windows", ignore = "requires nix .sh")] -fn test_round_trip() { - repo::clone_rust(); - let abort_after = common::abort_after(); - if abort_after == 0 { - panic!("Skipping all round_trip tests"); - } - - let failed = AtomicUsize::new(0); - - WalkDir::new("tests/rust") - .sort_by(|a, b| a.file_name().cmp(b.file_name())) - .into_iter() - .filter_entry(repo::base_dir_filter) - .collect::<Result<Vec<DirEntry>, walkdir::Error>>() - .unwrap() - .into_par_iter() - .for_each(|entry| { - let path = entry.path(); - if path.is_dir() { - return; - } - - let mut file = File::open(path).unwrap(); - let mut content = String::new(); - file.read_to_string(&mut content).unwrap(); - - let start = Instant::now(); - let (krate, elapsed) = match syn::parse_file(&content) { - Ok(krate) => (krate, start.elapsed()), - Err(msg) => { - errorf!("=== {}: syn failed to parse\n{:?}\n", path.display(), msg); - let prev_failed = failed.fetch_add(1, Ordering::SeqCst); - if prev_failed + 1 >= abort_after { - process::exit(1); - } - return; - } - }; - let back = quote!(#krate).to_string(); - - let equal = panic::catch_unwind(|| { - syntax::with_globals(Edition::Edition2018, || { - let sess = ParseSess::new(FilePathMapping::empty()); - let before = match libsyntax_parse(content, &sess) { - Ok(before) => before, - Err(mut diagnostic) => { - diagnostic.cancel(); - if diagnostic - .message() - .starts_with("file not found for module") - { - errorf!("=== {}: ignore\n", path.display()); - } else { - errorf!( - "=== {}: ignore - libsyntax failed to parse original content: {}\n", - path.display(), - diagnostic.message() - ); - } - return true; - } - }; - let after = match libsyntax_parse(back, &sess) { - Ok(after) => after, - Err(mut diagnostic) => { - errorf!("=== {}: libsyntax failed to parse", path.display()); - diagnostic.emit(); - return false; - } - }; - - if SpanlessEq::eq(&before, &after) { - errorf!( - "=== {}: pass in {}ms\n", - path.display(), - elapsed.as_secs() * 1000 - + u64::from(elapsed.subsec_nanos()) / 1_000_000 - ); - true - } else { - errorf!( - "=== {}: FAIL\nbefore: {:#?}\nafter: {:#?}\n", - path.display(), - before, - after, - ); - false - } - }) - }); - match equal { - Err(_) => errorf!("=== {}: ignoring libsyntax panic\n", path.display()), - Ok(true) => {} - Ok(false) => { - let prev_failed = failed.fetch_add(1, Ordering::SeqCst); - if prev_failed + 1 >= abort_after { - process::exit(1); - } - } - } - }); - - let failed = failed.load(Ordering::SeqCst); - if failed > 0 { - panic!("{} failures", failed); - } -} - -fn libsyntax_parse(content: String, sess: &ParseSess) -> PResult<ast::Crate> { - let name = FileName::Custom("test_round_trip".to_string()); - parse::parse_crate_from_source_str(name, content, sess) -} diff --git a/Android.bp b/Android.bp new file mode 100644 index 00000000..7445c4c0 --- /dev/null +++ b/Android.bp @@ -0,0 +1,72 @@ +// This file is generated by cargo2android.py --run --dependencies --features=full,visit,visit-mut,extra-traits --features=default,full,visit,visit-mut,extra-traits --host-first-multilib. +// Do not modify this file as changes will be overridden on upgrade. + +package { + default_applicable_licenses: ["external_rust_crates_syn_license"], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// +// large-scale-change included anything that looked like it might be a license +// text as a license_text. e.g. LICENSE, NOTICE, COPYING etc. +// +// Please consider removing redundant or irrelevant files from 'license_text:'. +// See: http://go/android-license-faq +license { + name: "external_rust_crates_syn_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-MIT", + ], + license_text: [ + "LICENSE-APACHE", + "LICENSE-MIT", + ], +} + +rust_library_host { + name: "libsyn", + crate_name: "syn", + srcs: ["src/lib.rs"], + edition: "2018", + features: [ + "clone-impls", + "default", + "derive", + "extra-traits", + "full", + "parsing", + "printing", + "proc-macro", + "quote", + "visit", + "visit-mut", + ], + flags: [ + "--cfg syn_disable_nightly_tests", + ], + rustlibs: [ + "libproc_macro2", + "libquote", + "libunicode_xid", + ], + compile_multilib: "first", +} + +// dependent_library ["feature_list"] +// proc-macro2-1.0.26 "default,proc-macro" +// quote-1.0.9 "default,proc-macro" +// unicode-xid-0.2.1 "default" diff --git a/1.0.7/Cargo.toml b/Cargo.toml index 82f815bc..b2dbe617 100644 --- a/1.0.7/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ [package] edition = "2018" name = "syn" -version = "1.0.7" +version = "1.0.69" authors = ["David Tolnay <dtolnay@gmail.com>"] include = ["/benches/**", "/build.rs", "/Cargo.toml", "/LICENSE-APACHE", "/LICENSE-MIT", "/README.md", "/src/**", "/tests/**"] description = "Parser for Rust source code" @@ -24,9 +24,11 @@ license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/syn" [package.metadata.docs.rs] all-features = true +rustdoc-args = ["--cfg", "doc_cfg"] +targets = ["x86_64-unknown-linux-gnu"] [package.metadata.playground] -all-features = true +features = ["full", "visit", "visit-mut", "fold", "extra-traits"] [[bench]] name = "rust" @@ -37,7 +39,7 @@ required-features = ["full", "parsing"] name = "file" required-features = ["full", "parsing"] [dependencies.proc-macro2] -version = "1.0" +version = "1.0.26" default-features = false [dependencies.quote] @@ -47,18 +49,34 @@ default-features = false [dependencies.unicode-xid] version = "0.2" +[dev-dependencies.anyhow] +version = "1.0" + +[dev-dependencies.flate2] +version = "1.0" + [dev-dependencies.insta] -version = "0.11" +version = "1.0" [dev-dependencies.rayon] version = "1.0" [dev-dependencies.ref-cast] -version = "0.2" +version = "1.0" [dev-dependencies.regex] version = "1.0" +[dev-dependencies.reqwest] +version = "0.10" +features = ["blocking"] + +[dev-dependencies.syn-test-suite] +version = "0" + +[dev-dependencies.tar] +version = "0.4.16" + [dev-dependencies.termcolor] version = "1.0" @@ -75,7 +93,6 @@ full = [] parsing = [] printing = ["quote"] proc-macro = ["proc-macro2/proc-macro", "quote/proc-macro"] +test = ["syn-test-suite/all-features"] visit = [] visit-mut = [] -[badges.travis-ci] -repository = "dtolnay/syn" diff --git a/1.0.7/Cargo.toml.orig b/Cargo.toml.orig index f050fac9..d29b93db 100644 --- a/1.0.7/Cargo.toml.orig +++ b/Cargo.toml.orig @@ -1,6 +1,6 @@ [package] name = "syn" -version = "1.0.7" # don't forget to update html_root_url and syn.json +version = "1.0.69" # don't forget to update html_root_url and syn.json authors = ["David Tolnay <dtolnay@gmail.com>"] license = "MIT OR Apache-2.0" description = "Parser for Rust source code" @@ -32,17 +32,23 @@ fold = [] clone-impls = [] extra-traits = [] proc-macro = ["proc-macro2/proc-macro", "quote/proc-macro"] +test = ["syn-test-suite/all-features"] [dependencies] -proc-macro2 = { version = "1.0", default-features = false } +proc-macro2 = { version = "1.0.26", default-features = false } quote = { version = "1.0", optional = true, default-features = false } unicode-xid = "0.2" [dev-dependencies] -insta = "0.11" +anyhow = "1.0" +flate2 = "1.0" +insta = "1.0" rayon = "1.0" -ref-cast = "0.2" +ref-cast = "1.0" regex = "1.0" +reqwest = { version = "0.10", features = ["blocking"] } +syn-test-suite = { version = "0", path = "tests/features" } +tar = "0.4.16" termcolor = "1.0" walkdir = "2.1" @@ -57,12 +63,11 @@ required-features = ["full", "parsing"] [package.metadata.docs.rs] all-features = true +targets = ["x86_64-unknown-linux-gnu"] +rustdoc-args = ["--cfg", "doc_cfg"] [package.metadata.playground] -all-features = true - -[badges] -travis-ci = { repository = "dtolnay/syn" } +features = ["full", "visit", "visit-mut", "fold", "extra-traits"] [workspace] -members = ["dev", "json"] +members = ["dev", "json", "tests/features"] diff --git a/LICENSE b/LICENSE new file mode 120000 index 00000000..6b579aae --- /dev/null +++ b/LICENSE @@ -0,0 +1 @@ +LICENSE-APACHE
\ No newline at end of file diff --git a/0.15.42/LICENSE-APACHE b/LICENSE-APACHE index 16fe87b0..16fe87b0 100644 --- a/0.15.42/LICENSE-APACHE +++ b/LICENSE-APACHE diff --git a/0.15.42/LICENSE-MIT b/LICENSE-MIT index 31aa7938..31aa7938 100644 --- a/0.15.42/LICENSE-MIT +++ b/LICENSE-MIT diff --git a/METADATA b/METADATA new file mode 100644 index 00000000..366fd603 --- /dev/null +++ b/METADATA @@ -0,0 +1,19 @@ +name: "syn" +description: "Parser for Rust source code" +third_party { + url { + type: HOMEPAGE + value: "https://crates.io/crates/syn" + } + url { + type: ARCHIVE + value: "https://static.crates.io/crates/syn/syn-1.0.69.crate" + } + version: "1.0.69" + license_type: NOTICE + last_upgrade_date { + year: 2021 + month: 4 + day: 13 + } +} diff --git a/0.15.42/src/keyword.rs b/MODULE_LICENSE_APACHE2 index e69de29b..e69de29b 100644 --- a/0.15.42/src/keyword.rs +++ b/MODULE_LICENSE_APACHE2 @@ -0,0 +1 @@ +include platform/prebuilts/rust:/OWNERS diff --git a/1.0.7/README.md b/README.md index 29a7f32a..12b5f45b 100644 --- a/1.0.7/README.md +++ b/README.md @@ -1,10 +1,10 @@ Parser for Rust source code =========================== -[![Build Status](https://api.travis-ci.org/dtolnay/syn.svg?branch=master)](https://travis-ci.org/dtolnay/syn) -[![Latest Version](https://img.shields.io/crates/v/syn.svg)](https://crates.io/crates/syn) -[![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/syn/1.0/syn/) -[![Rustc Version 1.31+](https://img.shields.io/badge/rustc-1.31+-lightgray.svg)](https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html) +[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/syn-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/syn) +[<img alt="crates.io" src="https://img.shields.io/crates/v/syn.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/syn) +[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-syn-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/syn) +[<img alt="build status" src="https://img.shields.io/github/workflow/status/dtolnay/syn/CI/master?style=for-the-badge" height="20">](https://github.com/dtolnay/syn/actions?query=branch%3Amaster) Syn is a parsing library for parsing a stream of Rust tokens into a syntax tree of Rust source code. @@ -46,10 +46,6 @@ contains some APIs that may be useful more generally. [`syn::DeriveInput`]: https://docs.rs/syn/1.0/syn/struct.DeriveInput.html [parser functions]: https://docs.rs/syn/1.0/syn/parse/index.html -If you get stuck with anything involving procedural macros in Rust I am happy to -provide help even if the issue is not related to Syn. Please file a ticket in -this repo. - *Version requirement: Syn supports rustc 1.31 and up.* [*Release notes*](https://github.com/dtolnay/syn/releases) @@ -88,8 +84,6 @@ proc-macro = true ``` ```rust -extern crate proc_macro; - use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, DeriveInput}; @@ -271,7 +265,7 @@ points, which are required by the language to use `proc_macro::TokenStream`. The proc-macro2 crate will automatically detect and use the compiler's data structures when a procedural macro is active. -[proc-macro2]: https://docs.rs/proc-macro2/1.0.0/proc_macro2/ +[proc-macro2]: https://docs.rs/proc-macro2/1.0/proc_macro2/ <br> diff --git a/TEST_MAPPING b/TEST_MAPPING new file mode 100644 index 00000000..ff7187ba --- /dev/null +++ b/TEST_MAPPING @@ -0,0 +1,221 @@ +// Generated by update_crate_tests.py for tests that depend on this crate. +{ + "presubmit": [ + { + "name": "ZipFuseTest" + }, + { + "name": "anyhow_device_test_src_lib" + }, + { + "name": "anyhow_device_test_tests_test_autotrait" + }, + { + "name": "anyhow_device_test_tests_test_boxed" + }, + { + "name": "anyhow_device_test_tests_test_chain" + }, + { + "name": "anyhow_device_test_tests_test_context" + }, + { + "name": "anyhow_device_test_tests_test_convert" + }, + { + "name": "anyhow_device_test_tests_test_downcast" + }, + { + "name": "anyhow_device_test_tests_test_ffi" + }, + { + "name": "anyhow_device_test_tests_test_fmt" + }, + { + "name": "anyhow_device_test_tests_test_macros" + }, + { + "name": "anyhow_device_test_tests_test_repr" + }, + { + "name": "anyhow_device_test_tests_test_source" + }, + { + "name": "authfs_device_test_src_lib" + }, + { + "name": "doh_unit_test" + }, + { + "name": "either_device_test_src_lib" + }, + { + "name": "futures-util_device_test_src_lib" + }, + { + "name": "keystore2_crypto_test_rust" + }, + { + "name": "keystore2_selinux_test" + }, + { + "name": "keystore2_test" + }, + { + "name": "libm_device_test_src_lib" + }, + { + "name": "serde_cbor_device_test_src_lib" + }, + { + "name": "serde_cbor_device_test_tests_bennofs" + }, + { + "name": "serde_cbor_device_test_tests_canonical" + }, + { + "name": "serde_cbor_device_test_tests_de" + }, + { + "name": "serde_cbor_device_test_tests_enum" + }, + { + "name": "serde_cbor_device_test_tests_ser" + }, + { + "name": "serde_cbor_device_test_tests_std_types" + }, + { + "name": "serde_cbor_device_test_tests_tags" + }, + { + "name": "serde_cbor_device_test_tests_value" + }, + { + "name": "serde_test_device_test_src_lib" + }, + { + "name": "tokio-test_device_test_src_lib" + }, + { + "name": "tokio-test_device_test_tests_block_on" + }, + { + "name": "tokio-test_device_test_tests_io" + }, + { + "name": "tokio-test_device_test_tests_macros" + }, + { + "name": "tokio_device_test_tests_buffered" + }, + { + "name": "tokio_device_test_tests_io_async_read" + }, + { + "name": "tokio_device_test_tests_io_copy_bidirectional" + }, + { + "name": "tokio_device_test_tests_io_lines" + }, + { + "name": "tokio_device_test_tests_io_mem_stream" + }, + { + "name": "tokio_device_test_tests_io_read" + }, + { + "name": "tokio_device_test_tests_io_read_buf" + }, + { + "name": "tokio_device_test_tests_io_read_to_end" + }, + { + "name": "tokio_device_test_tests_io_take" + }, + { + "name": "tokio_device_test_tests_io_write" + }, + { + "name": "tokio_device_test_tests_io_write_all" + }, + { + "name": "tokio_device_test_tests_io_write_buf" + }, + { + "name": "tokio_device_test_tests_io_write_int" + }, + { + "name": "tokio_device_test_tests_macros_join" + }, + { + "name": "tokio_device_test_tests_no_rt" + }, + { + "name": "tokio_device_test_tests_rt_basic" + }, + { + "name": "tokio_device_test_tests_rt_threaded" + }, + { + "name": "tokio_device_test_tests_sync_barrier" + }, + { + "name": "tokio_device_test_tests_sync_broadcast" + }, + { + "name": "tokio_device_test_tests_sync_errors" + }, + { + "name": "tokio_device_test_tests_sync_mpsc" + }, + { + "name": "tokio_device_test_tests_sync_mutex_owned" + }, + { + "name": "tokio_device_test_tests_sync_rwlock" + }, + { + "name": "tokio_device_test_tests_sync_watch" + }, + { + "name": "tokio_device_test_tests_task_local" + }, + { + "name": "tokio_device_test_tests_task_local_set" + }, + { + "name": "tokio_device_test_tests_tcp_accept" + }, + { + "name": "tokio_device_test_tests_tcp_echo" + }, + { + "name": "tokio_device_test_tests_tcp_into_std" + }, + { + "name": "tokio_device_test_tests_tcp_shutdown" + }, + { + "name": "tokio_device_test_tests_time_rt" + }, + { + "name": "tokio_device_test_tests_uds_split" + }, + { + "name": "unicode-bidi_device_test_src_lib" + }, + { + "name": "url_device_test_src_lib" + }, + { + "name": "url_device_test_tests_data" + }, + { + "name": "url_device_test_tests_unit" + }, + { + "name": "vpnprofilestore_test" + } + ] +} diff --git a/1.0.7/benches/file.rs b/benches/file.rs index 08ecd909..58ab8df2 100644 --- a/1.0.7/benches/file.rs +++ b/benches/file.rs @@ -1,9 +1,16 @@ // $ cargo bench --features full --bench file #![feature(rustc_private, test)] +#![recursion_limit = "1024"] extern crate test; +#[macro_use] +#[path = "../tests/macros/mod.rs"] +mod macros; + +#[path = "../tests/common/mod.rs"] +mod common; #[path = "../tests/repo/mod.rs"] pub mod repo; diff --git a/0.15.42/benches/rust.rs b/benches/rust.rs index e3d9cd29..50e1a7f6 100644 --- a/0.15.42/benches/rust.rs +++ b/benches/rust.rs @@ -4,7 +4,14 @@ // $ RUSTFLAGS='--cfg syn_only' cargo build --release --features full --bench rust #![cfg_attr(not(syn_only), feature(rustc_private))] +#![recursion_limit = "1024"] +#[macro_use] +#[path = "../tests/macros/mod.rs"] +mod macros; + +#[path = "../tests/common/mod.rs"] +mod common; #[path = "../tests/repo/mod.rs"] mod repo; @@ -28,31 +35,35 @@ mod syn_parse { } #[cfg(not(syn_only))] -mod libsyntax_parse { +mod librustc_parse { extern crate rustc_data_structures; - extern crate syntax; - extern crate syntax_pos; + extern crate rustc_errors; + extern crate rustc_parse; + extern crate rustc_session; + extern crate rustc_span; use rustc_data_structures::sync::Lrc; - use syntax::edition::Edition; - use syntax::errors::{emitter::Emitter, DiagnosticBuilder, Handler}; - use syntax::parse::ParseSess; - use syntax::source_map::{FilePathMapping, SourceMap}; - use syntax_pos::FileName; + use rustc_errors::{emitter::Emitter, Diagnostic, Handler}; + use rustc_session::parse::ParseSess; + use rustc_span::source_map::{FilePathMapping, SourceMap}; + use rustc_span::{edition::Edition, FileName}; pub fn bench(content: &str) -> Result<(), ()> { struct SilentEmitter; impl Emitter for SilentEmitter { - fn emit_diagnostic(&mut self, _db: &DiagnosticBuilder) {} + fn emit_diagnostic(&mut self, _diag: &Diagnostic) {} + fn source_map(&self) -> Option<&Lrc<SourceMap>> { + None + } } - syntax::with_globals(Edition::Edition2018, || { + rustc_span::with_session_globals(Edition::Edition2018, || { let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let emitter = Box::new(SilentEmitter); let handler = Handler::with_emitter(false, None, emitter); let sess = ParseSess::with_span_handler(handler, cm); - if let Err(mut diagnostic) = syntax::parse::parse_crate_from_source_str( + if let Err(mut diagnostic) = rustc_parse::parse_crate_from_source_str( FileName::Custom("bench".to_owned()), content.to_owned(), &sess, @@ -104,11 +115,11 @@ fn main() { repo::clone_rust(); macro_rules! testcases { - ($($(#[$cfg:meta])* $name:path,)*) => { + ($($(#[$cfg:meta])* $name:ident,)*) => { vec![ $( $(#[$cfg])* - (stringify!($name), $name as fn(&str) -> Result<(), ()>), + (stringify!($name), $name::bench as fn(&str) -> Result<(), ()>), )* ] }; @@ -128,12 +139,12 @@ fn main() { for (name, f) in testcases!( #[cfg(not(syn_only))] - read_from_disk::bench, + read_from_disk, #[cfg(not(syn_only))] - tokenstream_parse::bench, - syn_parse::bench, + tokenstream_parse, + syn_parse, #[cfg(not(syn_only))] - libsyntax_parse::bench, + librustc_parse, ) { eprint!("{:20}", format!("{}:", name)); let elapsed = exec(f); diff --git a/1.0.7/build.rs b/build.rs index c0f9ed34..25190f4c 100644 --- a/1.0.7/build.rs +++ b/build.rs @@ -1,6 +1,6 @@ use std::env; use std::process::Command; -use std::str::{self, FromStr}; +use std::str; // 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 @@ -15,6 +15,10 @@ fn main() { println!("cargo:rustc-cfg=syn_omit_await_from_token_macro"); } + if compiler.minor < 39 { + println!("cargo:rustc-cfg=syn_no_const_vec_new"); + } + if !compiler.nightly { println!("cargo:rustc-cfg=syn_disable_nightly_tests"); } @@ -26,38 +30,14 @@ struct Compiler { } fn rustc_version() -> Option<Compiler> { - 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, - }; - - let minor = match u32::from_str(next) { - Ok(minor) => minor, - Err(_) => return None, - }; - - Some(Compiler { - minor: minor, - nightly: version.contains("nightly"), - }) + let minor = pieces.next()?.parse().ok()?; + let nightly = version.contains("nightly"); + Some(Compiler { minor, nightly }) } diff --git a/1.0.7/src/attr.rs b/src/attr.rs index 34009dea..794a3104 100644 --- a/1.0.7/src/attr.rs +++ b/src/attr.rs @@ -1,23 +1,17 @@ use super::*; use crate::punctuated::Punctuated; - -use std::iter; - use proc_macro2::TokenStream; +use std::iter; #[cfg(feature = "parsing")] use crate::parse::{Parse, ParseBuffer, ParseStream, Parser, Result}; #[cfg(feature = "parsing")] use crate::punctuated::Pair; -#[cfg(feature = "extra-traits")] -use crate::tt::TokenStreamHelper; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; ast_struct! { /// An attribute like `#[repr(transparent)]`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* /// /// <br> @@ -111,7 +105,47 @@ ast_struct! { /// /// [`parse_meta()`]: Attribute::parse_meta /// [`parse_args()`]: Attribute::parse_args - pub struct Attribute #manual_extra_traits { + /// + /// <p><br></p> + /// + /// # Doc comments + /// + /// The compiler transforms doc comments, such as `/// comment` and `/*! + /// comment */`, into attributes before macros are expanded. Each comment is + /// expanded into an attribute of the form `#[doc = r"comment"]`. + /// + /// As an example, the following `mod` items are expanded identically: + /// + /// ``` + /// # use syn::{ItemMod, parse_quote}; + /// let doc: ItemMod = parse_quote! { + /// /// Single line doc comments + /// /// We write so many! + /// /** + /// * Multi-line comments... + /// * May span many lines + /// */ + /// mod example { + /// //! Of course, they can be inner too + /// /*! And fit in a single line */ + /// } + /// }; + /// let attr: ItemMod = parse_quote! { + /// #[doc = r" Single line doc comments"] + /// #[doc = r" We write so many!"] + /// #[doc = r" + /// * Multi-line comments... + /// * May span many lines + /// "] + /// mod example { + /// #![doc = r" Of course, they can be inner too"] + /// #![doc = r" And fit in a single line "] + /// } + /// }; + /// assert_eq!(doc, attr); + /// ``` + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct Attribute { pub pound_token: Token![#], pub style: AttrStyle, pub bracket_token: token::Bracket, @@ -120,41 +154,14 @@ ast_struct! { } } -#[cfg(feature = "extra-traits")] -impl Eq for Attribute {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Attribute { - fn eq(&self, other: &Self) -> bool { - self.style == other.style - && self.pound_token == other.pound_token - && self.bracket_token == other.bracket_token - && self.path == other.path - && TokenStreamHelper(&self.tokens) == TokenStreamHelper(&other.tokens) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Attribute { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - self.style.hash(state); - self.pound_token.hash(state); - self.bracket_token.hash(state); - self.path.hash(state); - TokenStreamHelper(&self.tokens).hash(state); - } -} - impl Attribute { /// Parses the content of the attribute, consisting of the path and tokens, /// as a [`Meta`] if possible. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_meta(&self) -> Result<Meta> { fn clone_ident_segment(segment: &PathSegment) -> PathSegment { PathSegment { @@ -199,18 +206,20 @@ impl Attribute { /// ^^^^^^^^^ what gets parsed /// ``` /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_args<T: Parse>(&self) -> Result<T> { self.parse_args_with(T::parse) } /// Parse the arguments to the attribute using the given parser. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_args_with<F: Parser>(&self, parser: F) -> Result<F::Output> { let parser = |input: ParseStream| { let args = enter_args(self, input)?; @@ -221,9 +230,10 @@ impl Attribute { /// Parses zero or more outer attributes from the stream. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_outer(input: ParseStream) -> Result<Vec<Self>> { let mut attrs = Vec::new(); while input.peek(Token![#]) { @@ -234,9 +244,10 @@ impl Attribute { /// Parses zero or more inner attributes from the stream. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_inner(input: ParseStream) -> Result<Vec<Self>> { let mut attrs = Vec::new(); while input.peek(Token![#]) && input.peek2(Token![!]) { @@ -247,7 +258,7 @@ impl Attribute { } #[cfg(feature = "parsing")] -fn error_expected_args(attr: &Attribute) -> Error { +fn expected_parentheses(attr: &Attribute) -> String { let style = match attr.style { AttrStyle::Outer => "#", AttrStyle::Inner(_) => "#!", @@ -261,19 +272,23 @@ fn error_expected_args(attr: &Attribute) -> Error { path += &segment.ident.to_string(); } - let msg = format!("expected attribute arguments: {}[{}(...)]", style, path); - - #[cfg(feature = "printing")] - return Error::new_spanned(attr, msg); - - #[cfg(not(feature = "printing"))] - return Error::new(attr.bracket_token.span, msg); + format!("{}[{}(...)]", style, path) } #[cfg(feature = "parsing")] fn enter_args<'a>(attr: &Attribute, input: ParseStream<'a>) -> Result<ParseBuffer<'a>> { if input.is_empty() { - return Err(error_expected_args(attr)); + let expected = expected_parentheses(attr); + let msg = format!("expected attribute arguments in parentheses: {}", expected); + return Err(crate::error::new2( + attr.pound_token.span, + attr.bracket_token.span, + msg, + )); + } else if input.peek(Token![=]) { + let expected = expected_parentheses(attr); + let msg = format!("expected parentheses: {}", expected); + return Err(input.error(msg)); }; let content; @@ -298,7 +313,7 @@ ast_enum! { /// Distinguishes between attributes that decorate an item and attributes /// that are contained within an item. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* /// /// # Outer attributes @@ -312,7 +327,7 @@ ast_enum! { /// - `#![feature(proc_macro)]` /// - `//! # Example` /// - `/*! Please file an issue */` - #[cfg_attr(feature = "clone-impls", derive(Copy))] + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum AttrStyle { Outer, Inner(Token![!]), @@ -322,7 +337,7 @@ ast_enum! { ast_enum_of_structs! { /// Content of a compile-time structured attribute. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* /// /// ## Path @@ -342,10 +357,8 @@ ast_enum_of_structs! { /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum Meta { Path(Path), @@ -360,8 +373,9 @@ ast_enum_of_structs! { ast_struct! { /// A structured list within an attribute, like `derive(Copy, Clone)`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct MetaList { pub path: Path, pub paren_token: token::Paren, @@ -372,8 +386,9 @@ ast_struct! { ast_struct! { /// A name-value pair within an attribute, like `feature = "nightly"`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct MetaNameValue { pub path: Path, pub eq_token: Token![=], @@ -398,8 +413,9 @@ impl Meta { ast_enum_of_structs! { /// Element of a compile-time attribute list. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum NestedMeta { /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which /// would be a nested `Meta::Path`. @@ -429,8 +445,8 @@ ast_enum_of_structs! { /// as type `AttributeArgs`. /// /// ``` -/// extern crate proc_macro; -/// +/// # extern crate proc_macro; +/// # /// use proc_macro::TokenStream; /// use syn::{parse_macro_input, AttributeArgs, ItemFn}; /// @@ -445,6 +461,7 @@ ast_enum_of_structs! { /// # "".parse().unwrap() /// } /// ``` +#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub type AttributeArgs = Vec<NestedMeta>; pub trait FilterAttrs<'a> { @@ -464,7 +481,7 @@ where fn is_outer(attr: &&Attribute) -> bool { match attr.style { AttrStyle::Outer => true, - _ => false, + AttrStyle::Inner(_) => false, } } self.into_iter().filter(is_outer) @@ -474,7 +491,7 @@ where fn is_inner(attr: &&Attribute) -> bool { match attr.style { AttrStyle::Inner(_) => true, - _ => false, + AttrStyle::Outer => false, } } self.into_iter().filter(is_inner) @@ -484,7 +501,6 @@ where #[cfg(feature = "parsing")] pub mod parsing { use super::*; - use crate::ext::IdentExt; use crate::parse::{Parse, ParseStream, Result}; #[cfg(feature = "full")] @@ -514,7 +530,7 @@ pub mod parsing { #[cfg(feature = "full")] impl private { - pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> { + pub(crate) fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> { let mut attrs = outer; attrs.extend(inner); attrs @@ -546,6 +562,7 @@ pub mod parsing { }) } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Meta { fn parse(input: ParseStream) -> Result<Self> { let path = input.call(parse_meta_path)?; @@ -553,6 +570,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for MetaList { fn parse(input: ParseStream) -> Result<Self> { let path = input.call(parse_meta_path)?; @@ -560,6 +578,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for MetaNameValue { fn parse(input: ParseStream) -> Result<Self> { let path = input.call(parse_meta_path)?; @@ -567,11 +586,14 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for NestedMeta { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Lit) && !(input.peek(LitBool) && input.peek2(Token![=])) { input.parse().map(NestedMeta::Lit) - } else if input.peek(Ident::peek_any) { + } else if input.peek(Ident::peek_any) + || input.peek(Token![::]) && input.peek3(Ident::peek_any) + { input.parse().map(NestedMeta::Meta) } else { Err(input.error("expected identifier or literal")) @@ -613,6 +635,7 @@ mod printing { use proc_macro2::TokenStream; use quote::ToTokens; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Attribute { fn to_tokens(&self, tokens: &mut TokenStream) { self.pound_token.to_tokens(tokens); @@ -626,6 +649,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for MetaList { fn to_tokens(&self, tokens: &mut TokenStream) { self.path.to_tokens(tokens); @@ -635,6 +659,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for MetaNameValue { fn to_tokens(&self, tokens: &mut TokenStream) { self.path.to_tokens(tokens); diff --git a/1.0.7/src/await.rs b/src/await.rs index a8e24fd4..038c6a5d 100644 --- a/1.0.7/src/await.rs +++ b/src/await.rs @@ -1,2 +1,2 @@ // See include!("await.rs") in token.rs. -export_token_macro![(await)]; +export_token_macro! {[await]} diff --git a/1.0.7/src/bigint.rs b/src/bigint.rs index 5397d6be..5397d6be 100644 --- a/1.0.7/src/bigint.rs +++ b/src/bigint.rs diff --git a/1.0.7/src/buffer.rs b/src/buffer.rs index 551a5ac8..ec172259 100644 --- a/1.0.7/src/buffer.rs +++ b/src/buffer.rs @@ -1,7 +1,7 @@ //! A stably addressed token buffer supporting efficient traversal based on a //! cheaply copyable cursor. //! -//! *This module is available if Syn is built with the `"parsing"` feature.* +//! *This module is available only if Syn is built with the `"parsing"` feature.* // This module is heavily commented as it contains most of the unsafe code in // Syn, and caution should be used when editing it. The public-facing interface @@ -12,13 +12,11 @@ feature = "proc-macro" ))] use crate::proc_macro as pm; +use crate::Lifetime; use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; - use std::marker::PhantomData; use std::ptr; -use crate::Lifetime; - /// Internal type which is used instead of `TokenTree` to represent a token tree /// within a `TokenBuffer`. enum Entry { @@ -36,7 +34,7 @@ enum Entry { /// `TokenStream` which requires a deep copy in order to traverse more than /// once. /// -/// *This type is available if Syn is built with the `"parsing"` feature.* +/// *This type is available only if Syn is built with the `"parsing"` feature.* pub struct TokenBuffer { // NOTE: Do not derive clone on this - there are raw pointers inside which // will be messed up. Moving the `TokenBuffer` itself is safe as the actual @@ -98,7 +96,7 @@ impl TokenBuffer { /// Creates a `TokenBuffer` containing all the tokens from the input /// `TokenStream`. /// - /// *This method is available if Syn is built with both the `"parsing"` and + /// *This method is available only if Syn is built with both the `"parsing"` and /// `"proc-macro"` features.* #[cfg(all( not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), @@ -133,8 +131,7 @@ impl TokenBuffer { /// Two cursors are equal if they have the same location in the same input /// stream, and have the same scope. /// -/// *This type is available if Syn is built with the `"parsing"` feature.* -#[derive(Copy, Clone, Eq, PartialEq)] +/// *This type is available only if Syn is built with the `"parsing"` feature.* pub struct Cursor<'a> { // The current entry which the `Cursor` is pointing at. ptr: *const Entry, @@ -201,13 +198,13 @@ impl<'a> Cursor<'a> { Cursor::create(self.ptr.offset(1), self.scope) } - /// If the cursor is looking at a `None`-delimited group, move it to look at - /// the first token inside instead. If the group is empty, this will move + /// While the cursor is looking at a `None`-delimited group, move it to look + /// at the first token inside instead. If the group is empty, this will move /// the cursor past the `None`-delimited group. /// /// WARNING: This mutates its argument. fn ignore_none(&mut self) { - if let Entry::Group(group, buf) = self.entry() { + while let Entry::Group(group, buf) = self.entry() { if group.delimiter() == Delimiter::None { // NOTE: We call `Cursor::create` here to make sure that // situations where we should immediately exit the span after @@ -215,13 +212,14 @@ impl<'a> Cursor<'a> { unsafe { *self = Cursor::create(&buf.data[0], self.scope); } + } else { + break; } } } /// Checks whether the cursor is currently pointing at the end of its valid /// scope. - #[inline] pub fn eof(self) -> bool { // We're at eof if we're at the end of our scope. self.ptr == self.scope @@ -342,6 +340,44 @@ impl<'a> Cursor<'a> { Entry::End(..) => Span::call_site(), } } + + /// Skip over the next token without cloning it. Returns `None` if this + /// cursor points to eof. + /// + /// This method treats `'lifetimes` as a single token. + pub(crate) fn skip(self) -> Option<Cursor<'a>> { + match self.entry() { + Entry::End(..) => None, + + // Treat lifetimes as a single tt for the purposes of 'skip'. + Entry::Punct(op) if op.as_char() == '\'' && op.spacing() == Spacing::Joint => { + let next = unsafe { self.bump() }; + match next.entry() { + Entry::Ident(_) => Some(unsafe { next.bump() }), + _ => Some(next), + } + } + _ => Some(unsafe { self.bump() }), + } + } +} + +impl<'a> Copy for Cursor<'a> {} + +impl<'a> Clone for Cursor<'a> { + fn clone(&self) -> Self { + *self + } +} + +impl<'a> Eq for Cursor<'a> {} + +impl<'a> PartialEq for Cursor<'a> { + fn eq(&self, other: &Self) -> bool { + let Cursor { ptr, scope, marker } = self; + let _ = marker; + *ptr == other.ptr && *scope == other.scope + } } pub(crate) fn same_scope(a: Cursor, b: Cursor) -> bool { diff --git a/1.0.7/src/custom_keyword.rs b/src/custom_keyword.rs index 200e8478..69d787e5 100644 --- a/1.0.7/src/custom_keyword.rs +++ b/src/custom_keyword.rs @@ -26,8 +26,8 @@ /// /// - Field access to its span — `let sp = whatever_token.span` /// -/// [Peeking]: parse::ParseBuffer::peek -/// [Parsing]: parse::ParseBuffer::parse +/// [Peeking]: crate::parse::ParseBuffer::peek +/// [Parsing]: crate::parse::ParseBuffer::parse /// [Printing]: quote::ToTokens /// [`Span`]: proc_macro2::Span /// @@ -86,36 +86,36 @@ /// } /// } /// ``` -#[macro_export(local_inner_macros)] +#[macro_export] macro_rules! custom_keyword { ($ident:ident) => { #[allow(non_camel_case_types)] pub struct $ident { - pub span: $crate::export::Span, + pub span: $crate::__private::Span, } #[doc(hidden)] - #[allow(non_snake_case)] - pub fn $ident<__S: $crate::export::IntoSpans<[$crate::export::Span; 1]>>( + #[allow(dead_code, non_snake_case)] + pub fn $ident<__S: $crate::__private::IntoSpans<[$crate::__private::Span; 1]>>( span: __S, ) -> $ident { $ident { - span: $crate::export::IntoSpans::into_spans(span)[0], + span: $crate::__private::IntoSpans::into_spans(span)[0], } } - impl $crate::export::Default for $ident { + impl $crate::__private::Default for $ident { fn default() -> Self { $ident { - span: $crate::export::Span::call_site(), + span: $crate::__private::Span::call_site(), } } } - impl_parse_for_custom_keyword!($ident); - impl_to_tokens_for_custom_keyword!($ident); - impl_clone_for_custom_keyword!($ident); - impl_extra_traits_for_custom_keyword!($ident); + $crate::impl_parse_for_custom_keyword!($ident); + $crate::impl_to_tokens_for_custom_keyword!($ident); + $crate::impl_clone_for_custom_keyword!($ident); + $crate::impl_extra_traits_for_custom_keyword!($ident); }; } @@ -127,7 +127,7 @@ macro_rules! impl_parse_for_custom_keyword { ($ident:ident) => { // For peek. impl $crate::token::CustomToken for $ident { - fn peek(cursor: $crate::buffer::Cursor) -> $crate::export::bool { + fn peek(cursor: $crate::buffer::Cursor) -> $crate::__private::bool { if let Some((ident, _rest)) = cursor.ident() { ident == stringify!($ident) } else { @@ -135,7 +135,7 @@ macro_rules! impl_parse_for_custom_keyword { } } - fn display() -> &'static $crate::export::str { + fn display() -> &'static $crate::__private::str { concat!("`", stringify!($ident), "`") } } @@ -143,12 +143,12 @@ macro_rules! impl_parse_for_custom_keyword { impl $crate::parse::Parse for $ident { fn parse(input: $crate::parse::ParseStream) -> $crate::parse::Result<$ident> { input.step(|cursor| { - if let $crate::export::Some((ident, rest)) = cursor.ident() { + if let $crate::__private::Some((ident, rest)) = cursor.ident() { if ident == stringify!($ident) { - return $crate::export::Ok(($ident { span: ident.span() }, rest)); + return $crate::__private::Ok(($ident { span: ident.span() }, rest)); } } - $crate::export::Err(cursor.error(concat!( + $crate::__private::Err(cursor.error(concat!( "expected `", stringify!($ident), "`" @@ -173,10 +173,10 @@ macro_rules! impl_parse_for_custom_keyword { #[macro_export] macro_rules! impl_to_tokens_for_custom_keyword { ($ident:ident) => { - impl $crate::export::ToTokens for $ident { - fn to_tokens(&self, tokens: &mut $crate::export::TokenStream2) { + impl $crate::__private::ToTokens for $ident { + fn to_tokens(&self, tokens: &mut $crate::__private::TokenStream2) { let ident = $crate::Ident::new(stringify!($ident), self.span); - $crate::export::TokenStreamExt::append(tokens, ident); + $crate::__private::TokenStreamExt::append(tokens, ident); } } }; @@ -196,9 +196,10 @@ macro_rules! impl_to_tokens_for_custom_keyword { #[macro_export] macro_rules! impl_clone_for_custom_keyword { ($ident:ident) => { - impl $crate::export::Copy for $ident {} + impl $crate::__private::Copy for $ident {} - impl $crate::export::Clone for $ident { + #[allow(clippy::expl_impl_clone_on_copy)] + impl $crate::__private::Clone for $ident { fn clone(&self) -> Self { *self } @@ -220,25 +221,25 @@ macro_rules! impl_clone_for_custom_keyword { #[macro_export] macro_rules! impl_extra_traits_for_custom_keyword { ($ident:ident) => { - impl $crate::export::Debug for $ident { - fn fmt(&self, f: &mut $crate::export::Formatter) -> $crate::export::fmt::Result { - $crate::export::Formatter::write_str( + impl $crate::__private::Debug for $ident { + fn fmt(&self, f: &mut $crate::__private::Formatter) -> $crate::__private::fmt::Result { + $crate::__private::Formatter::write_str( f, concat!("Keyword [", stringify!($ident), "]"), ) } } - impl $crate::export::Eq for $ident {} + impl $crate::__private::Eq for $ident {} - impl $crate::export::PartialEq for $ident { - fn eq(&self, _other: &Self) -> $crate::export::bool { + impl $crate::__private::PartialEq for $ident { + fn eq(&self, _other: &Self) -> $crate::__private::bool { true } } - impl $crate::export::Hash for $ident { - fn hash<__H: $crate::export::Hasher>(&self, _state: &mut __H) {} + impl $crate::__private::Hash for $ident { + fn hash<__H: $crate::__private::Hasher>(&self, _state: &mut __H) {} } }; } diff --git a/1.0.7/src/custom_punctuation.rs b/src/custom_punctuation.rs index 29fa448b..118a8453 100644 --- a/1.0.7/src/custom_punctuation.rs +++ b/src/custom_punctuation.rs @@ -22,8 +22,8 @@ /// /// - Field access to its spans — `let spans = lrarrow.spans` /// -/// [Peeking]: parse::ParseBuffer::peek -/// [Parsing]: parse::ParseBuffer::parse +/// [Peeking]: crate::parse::ParseBuffer::peek +/// [Parsing]: crate::parse::ParseBuffer::parse /// [Printing]: quote::ToTokens /// [`Span`]: proc_macro2::Span /// @@ -74,57 +74,57 @@ /// let _: PathSegments = syn::parse_str(input).unwrap(); /// } /// ``` -#[macro_export(local_inner_macros)] +#[macro_export] macro_rules! custom_punctuation { ($ident:ident, $($tt:tt)+) => { pub struct $ident { - pub spans: custom_punctuation_repr!($($tt)+), + pub spans: $crate::custom_punctuation_repr!($($tt)+), } #[doc(hidden)] - #[allow(non_snake_case)] - pub fn $ident<__S: $crate::export::IntoSpans<custom_punctuation_repr!($($tt)+)>>( + #[allow(dead_code, non_snake_case)] + pub fn $ident<__S: $crate::__private::IntoSpans<$crate::custom_punctuation_repr!($($tt)+)>>( spans: __S, ) -> $ident { - let _validate_len = 0 $(+ custom_punctuation_len!(strict, $tt))*; + let _validate_len = 0 $(+ $crate::custom_punctuation_len!(strict, $tt))*; $ident { - spans: $crate::export::IntoSpans::into_spans(spans) + spans: $crate::__private::IntoSpans::into_spans(spans) } } - impl $crate::export::Default for $ident { + impl $crate::__private::Default for $ident { fn default() -> Self { - $ident($crate::export::Span::call_site()) + $ident($crate::__private::Span::call_site()) } } - impl_parse_for_custom_punctuation!($ident, $($tt)+); - impl_to_tokens_for_custom_punctuation!($ident, $($tt)+); - impl_clone_for_custom_punctuation!($ident, $($tt)+); - impl_extra_traits_for_custom_punctuation!($ident, $($tt)+); + $crate::impl_parse_for_custom_punctuation!($ident, $($tt)+); + $crate::impl_to_tokens_for_custom_punctuation!($ident, $($tt)+); + $crate::impl_clone_for_custom_punctuation!($ident, $($tt)+); + $crate::impl_extra_traits_for_custom_punctuation!($ident, $($tt)+); }; } // Not public API. #[cfg(feature = "parsing")] #[doc(hidden)] -#[macro_export(local_inner_macros)] +#[macro_export] macro_rules! impl_parse_for_custom_punctuation { ($ident:ident, $($tt:tt)+) => { impl $crate::token::CustomToken for $ident { fn peek(cursor: $crate::buffer::Cursor) -> bool { - $crate::token::parsing::peek_punct(cursor, stringify_punct!($($tt)+)) + $crate::token::parsing::peek_punct(cursor, $crate::stringify_punct!($($tt)+)) } - fn display() -> &'static $crate::export::str { - custom_punctuation_concat!("`", stringify_punct!($($tt)+), "`") + fn display() -> &'static $crate::__private::str { + concat!("`", $crate::stringify_punct!($($tt)+), "`") } } impl $crate::parse::Parse for $ident { fn parse(input: $crate::parse::ParseStream) -> $crate::parse::Result<$ident> { - let spans: custom_punctuation_repr!($($tt)+) = - $crate::token::parsing::punct(input, stringify_punct!($($tt)+))?; + let spans: $crate::custom_punctuation_repr!($($tt)+) = + $crate::token::parsing::punct(input, $crate::stringify_punct!($($tt)+))?; Ok($ident(spans)) } } @@ -142,12 +142,12 @@ macro_rules! impl_parse_for_custom_punctuation { // Not public API. #[cfg(feature = "printing")] #[doc(hidden)] -#[macro_export(local_inner_macros)] +#[macro_export] macro_rules! impl_to_tokens_for_custom_punctuation { ($ident:ident, $($tt:tt)+) => { - impl $crate::export::ToTokens for $ident { - fn to_tokens(&self, tokens: &mut $crate::export::TokenStream2) { - $crate::token::printing::punct(stringify_punct!($($tt)+), &self.spans, tokens) + impl $crate::__private::ToTokens for $ident { + fn to_tokens(&self, tokens: &mut $crate::__private::TokenStream2) { + $crate::token::printing::punct($crate::stringify_punct!($($tt)+), &self.spans, tokens) } } }; @@ -167,9 +167,10 @@ macro_rules! impl_to_tokens_for_custom_punctuation { #[macro_export] macro_rules! impl_clone_for_custom_punctuation { ($ident:ident, $($tt:tt)+) => { - impl $crate::export::Copy for $ident {} + impl $crate::__private::Copy for $ident {} - impl $crate::export::Clone for $ident { + #[allow(clippy::expl_impl_clone_on_copy)] + impl $crate::__private::Clone for $ident { fn clone(&self) -> Self { *self } @@ -191,22 +192,22 @@ macro_rules! impl_clone_for_custom_punctuation { #[macro_export] macro_rules! impl_extra_traits_for_custom_punctuation { ($ident:ident, $($tt:tt)+) => { - impl $crate::export::Debug for $ident { - fn fmt(&self, f: &mut $crate::export::Formatter) -> $crate::export::fmt::Result { - $crate::export::Formatter::write_str(f, stringify!($ident)) + impl $crate::__private::Debug for $ident { + fn fmt(&self, f: &mut $crate::__private::Formatter) -> $crate::__private::fmt::Result { + $crate::__private::Formatter::write_str(f, stringify!($ident)) } } - impl $crate::export::Eq for $ident {} + impl $crate::__private::Eq for $ident {} - impl $crate::export::PartialEq for $ident { - fn eq(&self, _other: &Self) -> $crate::export::bool { + impl $crate::__private::PartialEq for $ident { + fn eq(&self, _other: &Self) -> $crate::__private::bool { true } } - impl $crate::export::Hash for $ident { - fn hash<__H: $crate::export::Hasher>(&self, _state: &mut __H) {} + impl $crate::__private::Hash for $ident { + fn hash<__H: $crate::__private::Hasher>(&self, _state: &mut __H) {} } }; } @@ -221,16 +222,16 @@ macro_rules! impl_extra_traits_for_custom_punctuation { // Not public API. #[doc(hidden)] -#[macro_export(local_inner_macros)] +#[macro_export] macro_rules! custom_punctuation_repr { ($($tt:tt)+) => { - [$crate::export::Span; 0 $(+ custom_punctuation_len!(lenient, $tt))+] + [$crate::__private::Span; 0 $(+ $crate::custom_punctuation_len!(lenient, $tt))+] }; } // Not public API. #[doc(hidden)] -#[macro_export(local_inner_macros)] +#[macro_export] #[rustfmt::skip] macro_rules! custom_punctuation_len { ($mode:ident, +) => { 1 }; @@ -279,7 +280,7 @@ macro_rules! custom_punctuation_len { ($mode:ident, -=) => { 2 }; ($mode:ident, ~) => { 1 }; (lenient, $tt:tt) => { 0 }; - (strict, $tt:tt) => {{ custom_punctuation_unexpected!($tt); 0 }}; + (strict, $tt:tt) => {{ $crate::custom_punctuation_unexpected!($tt); 0 }}; } // Not public API. @@ -297,13 +298,3 @@ macro_rules! stringify_punct { concat!($(stringify!($tt)),+) }; } - -// Not public API. -// Without this, local_inner_macros breaks when looking for concat! -#[doc(hidden)] -#[macro_export] -macro_rules! custom_punctuation_concat { - ($($tt:tt)*) => { - concat!($($tt)*) - }; -} diff --git a/1.0.7/src/data.rs b/src/data.rs index 2554506c..731f5a0a 100644 --- a/1.0.7/src/data.rs +++ b/src/data.rs @@ -4,8 +4,9 @@ use crate::punctuated::Punctuated; ast_struct! { /// An enum variant. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct Variant { /// Attributes tagged on the variant. pub attrs: Vec<Attribute>, @@ -24,17 +25,15 @@ ast_struct! { ast_enum_of_structs! { /// Data stored within an enum variant or struct. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum Fields { /// Named fields of a struct or struct variant such as `Point { x: f64, /// y: f64 }`. @@ -52,8 +51,9 @@ ast_struct! { /// Named fields of a struct or struct variant such as `Point { x: f64, /// y: f64 }`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct FieldsNamed { pub brace_token: token::Brace, pub named: Punctuated<Field, Token![,]>, @@ -63,8 +63,9 @@ ast_struct! { ast_struct! { /// Unnamed fields of a tuple struct or tuple variant such as `Some(T)`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct FieldsUnnamed { pub paren_token: token::Paren, pub unnamed: Punctuated<Field, Token![,]>, @@ -147,8 +148,9 @@ impl<'a> IntoIterator for &'a mut Fields { ast_struct! { /// A field of a struct or enum variant. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct Field { /// Attributes tagged on the field. pub attrs: Vec<Attribute>, @@ -172,17 +174,15 @@ ast_enum_of_structs! { /// The visibility level of an item: inherited or `pub` or /// `pub(restricted)`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum Visibility { /// A public visibility level: `pub`. Public(VisPublic), @@ -202,8 +202,9 @@ ast_enum_of_structs! { ast_struct! { /// A public visibility level: `pub`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct VisPublic { pub pub_token: Token![pub], } @@ -212,8 +213,9 @@ ast_struct! { ast_struct! { /// A crate-level visibility: `crate`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct VisCrate { pub crate_token: Token![crate], } @@ -223,8 +225,9 @@ ast_struct! { /// A visibility level restricted to some path: `pub(self)` or /// `pub(super)` or `pub(crate)` or `pub(in some::module)`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct VisRestricted { pub pub_token: Token![pub], pub paren_token: token::Paren, @@ -236,14 +239,17 @@ ast_struct! { #[cfg(feature = "parsing")] pub mod parsing { use super::*; - use crate::ext::IdentExt; + use crate::parse::discouraged::Speculative; use crate::parse::{Parse, ParseStream, Result}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Variant { fn parse(input: ParseStream) -> Result<Self> { + let attrs = input.call(Attribute::parse_outer)?; + let _visibility: Visibility = input.parse()?; Ok(Variant { - attrs: input.call(Attribute::parse_outer)?, + attrs, ident: input.parse()?, fields: { if input.peek(token::Brace) { @@ -267,6 +273,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for FieldsNamed { fn parse(input: ParseStream) -> Result<Self> { let content; @@ -277,6 +284,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for FieldsUnnamed { fn parse(input: ParseStream) -> Result<Self> { let content; @@ -289,6 +297,7 @@ pub mod parsing { impl Field { /// Parses a named (braced struct) field. + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_named(input: ParseStream) -> Result<Self> { Ok(Field { attrs: input.call(Attribute::parse_outer)?, @@ -300,6 +309,7 @@ pub mod parsing { } /// Parses an unnamed (tuple struct) field. + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_unnamed(input: ParseStream) -> Result<Self> { Ok(Field { attrs: input.call(Attribute::parse_outer)?, @@ -311,8 +321,20 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Visibility { fn parse(input: ParseStream) -> Result<Self> { + // Recognize an empty None-delimited group, as produced by a $:vis + // matcher that matched no tokens. + if input.peek(token::Group) { + let ahead = input.fork(); + let group = crate::group::parse_group(&ahead)?; + if group.content.is_empty() { + input.advance_to(&ahead); + return Ok(Visibility::Inherited); + } + } + if input.peek(Token![pub]) { Self::parse_pub(input) } else if input.peek(Token![crate]) { @@ -328,27 +350,39 @@ pub mod parsing { let pub_token = input.parse::<Token![pub]>()?; if input.peek(token::Paren) { - // TODO: optimize using advance_to let ahead = input.fork(); - let mut content; - parenthesized!(content in ahead); + let content; + let paren_token = parenthesized!(content in ahead); if content.peek(Token![crate]) || content.peek(Token![self]) || content.peek(Token![super]) { - return Ok(Visibility::Restricted(VisRestricted { - pub_token, - paren_token: parenthesized!(content in input), - in_token: None, - path: Box::new(Path::from(content.call(Ident::parse_any)?)), - })); + let path = content.call(Ident::parse_any)?; + + // Ensure there are no additional tokens within `content`. + // Without explicitly checking, we may misinterpret a tuple + // field as a restricted visibility, causing a parse error. + // e.g. `pub (crate::A, crate::B)` (Issue #720). + if content.is_empty() { + input.advance_to(&ahead); + return Ok(Visibility::Restricted(VisRestricted { + pub_token, + paren_token, + in_token: None, + path: Box::new(Path::from(path)), + })); + } } else if content.peek(Token![in]) { + let in_token: Token![in] = content.parse()?; + let path = content.call(Path::parse_mod_style)?; + + input.advance_to(&ahead); return Ok(Visibility::Restricted(VisRestricted { pub_token, - paren_token: parenthesized!(content in input), - in_token: Some(content.parse()?), - path: Box::new(content.call(Path::parse_mod_style)?), + paren_token, + in_token: Some(in_token), + path: Box::new(path), })); } } @@ -365,18 +399,25 @@ pub mod parsing { })) } } + + #[cfg(feature = "full")] + pub(crate) fn is_some(&self) -> bool { + match self { + Visibility::Inherited => false, + _ => true, + } + } } } #[cfg(feature = "printing")] mod printing { use super::*; - + use crate::print::TokensOrDefault; use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; - use crate::print::TokensOrDefault; - + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Variant { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(&self.attrs); @@ -389,6 +430,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for FieldsNamed { fn to_tokens(&self, tokens: &mut TokenStream) { self.brace_token.surround(tokens, |tokens| { @@ -397,6 +439,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for FieldsUnnamed { fn to_tokens(&self, tokens: &mut TokenStream) { self.paren_token.surround(tokens, |tokens| { @@ -405,6 +448,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Field { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(&self.attrs); @@ -417,18 +461,21 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for VisPublic { fn to_tokens(&self, tokens: &mut TokenStream) { self.pub_token.to_tokens(tokens) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for VisCrate { fn to_tokens(&self, tokens: &mut TokenStream) { self.crate_token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for VisRestricted { fn to_tokens(&self, tokens: &mut TokenStream) { self.pub_token.to_tokens(tokens); diff --git a/1.0.7/src/derive.rs b/src/derive.rs index 8cb9cf7b..af9bb91b 100644 --- a/1.0.7/src/derive.rs +++ b/src/derive.rs @@ -4,7 +4,8 @@ use crate::punctuated::Punctuated; ast_struct! { /// Data structure sent to a `proc_macro_derive` macro. /// - /// *This type is available if Syn is built with the `"derive"` feature.* + /// *This type is available only if Syn is built with the `"derive"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] pub struct DeriveInput { /// Attributes tagged on the whole struct or enum. pub attrs: Vec<Attribute>, @@ -26,16 +27,14 @@ ast_struct! { ast_enum_of_structs! { /// The storage of a struct, enum or union data structure. /// - /// *This type is available if Syn is built with the `"derive"` feature.* + /// *This type is available only if Syn is built with the `"derive"` feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] pub enum Data { /// A struct input to a `proc_macro_derive` macro. Struct(DataStruct), @@ -53,8 +52,9 @@ ast_enum_of_structs! { ast_struct! { /// A struct input to a `proc_macro_derive` macro. /// - /// *This type is available if Syn is built with the `"derive"` + /// *This type is available only if Syn is built with the `"derive"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] pub struct DataStruct { pub struct_token: Token![struct], pub fields: Fields, @@ -65,8 +65,9 @@ ast_struct! { ast_struct! { /// An enum input to a `proc_macro_derive` macro. /// - /// *This type is available if Syn is built with the `"derive"` + /// *This type is available only if Syn is built with the `"derive"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] pub struct DataEnum { pub enum_token: Token![enum], pub brace_token: token::Brace, @@ -77,8 +78,9 @@ ast_struct! { ast_struct! { /// An untagged union input to a `proc_macro_derive` macro. /// - /// *This type is available if Syn is built with the `"derive"` + /// *This type is available only if Syn is built with the `"derive"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] pub struct DataUnion { pub union_token: Token![union], pub fields: FieldsNamed, @@ -88,9 +90,9 @@ ast_struct! { #[cfg(feature = "parsing")] pub mod parsing { use super::*; - use crate::parse::{Parse, ParseStream, Result}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for DeriveInput { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -221,13 +223,12 @@ pub mod parsing { #[cfg(feature = "printing")] mod printing { use super::*; - - use proc_macro2::TokenStream; - use quote::ToTokens; - use crate::attr::FilterAttrs; use crate::print::TokensOrDefault; + use proc_macro2::TokenStream; + use quote::ToTokens; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for DeriveInput { fn to_tokens(&self, tokens: &mut TokenStream) { for attr in self.attrs.outer() { diff --git a/1.0.7/src/discouraged.rs b/src/discouraged.rs index 4d9ff937..76c9fce6 100644 --- a/1.0.7/src/discouraged.rs +++ b/src/discouraged.rs @@ -16,7 +16,7 @@ pub trait Speculative { /// syntax of the form `A* B*` for arbitrary syntax `A` and `B`. The problem /// is that when the fork fails to parse an `A`, it's impossible to tell /// whether that was because of a syntax error and the user meant to provide - /// an `A`, or that the `A`s are finished and its time to start parsing + /// an `A`, or that the `A`s are finished and it's time to start parsing /// `B`s. Use with care. /// /// Also note that if `A` is a subset of `B`, `A* B*` can be parsed by @@ -72,7 +72,6 @@ pub trait Speculative { /// || input.peek(Token![self]) /// || input.peek(Token![Self]) /// || input.peek(Token![crate]) - /// || input.peek(Token![extern]) /// { /// let ident = input.call(Ident::parse_any)?; /// return Ok(PathSegment::from(ident)); @@ -164,6 +163,30 @@ impl<'a> Speculative for ParseBuffer<'a> { panic!("Fork was not derived from the advancing parse stream"); } + let (self_unexp, self_sp) = inner_unexpected(self); + let (fork_unexp, fork_sp) = inner_unexpected(fork); + if !Rc::ptr_eq(&self_unexp, &fork_unexp) { + match (fork_sp, self_sp) { + // Unexpected set on the fork, but not on `self`, copy it over. + (Some(span), None) => { + self_unexp.set(Unexpected::Some(span)); + } + // Unexpected unset. Use chain to propagate errors from fork. + (None, None) => { + fork_unexp.set(Unexpected::Chain(self_unexp)); + + // Ensure toplevel 'unexpected' tokens from the fork don't + // bubble up the chain by replacing the root `unexpected` + // pointer, only 'unexpected' tokens from existing group + // parsers should bubble. + fork.unexpected + .set(Some(Rc::new(Cell::new(Unexpected::None)))); + } + // Unexpected has been set on `self`. No changes needed. + (_, Some(_)) => {} + } + } + // See comment on `cell` in the struct definition. self.cell .set(unsafe { mem::transmute::<Cursor, Cursor<'static>>(fork.cursor()) }) diff --git a/1.0.7/src/error.rs b/src/error.rs index 146d6522..780731c8 100644 --- a/1.0.7/src/error.rs +++ b/src/error.rs @@ -1,18 +1,15 @@ -use std; -use std::fmt::{self, Debug, Display}; -use std::iter::FromIterator; -use std::slice; -use std::vec; - +#[cfg(feature = "parsing")] +use crate::buffer::Cursor; +use crate::thread::ThreadBound; use proc_macro2::{ Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree, }; #[cfg(feature = "printing")] use quote::ToTokens; - -#[cfg(feature = "parsing")] -use crate::buffer::Cursor; -use crate::thread::ThreadBound; +use std::fmt::{self, Debug, Display}; +use std::iter::FromIterator; +use std::slice; +use std::vec; /// The result of a Syn parser. pub type Result<T> = std::result::Result<T, Error>; @@ -26,14 +23,14 @@ pub type Result<T> = std::result::Result<T, Error>; /// [`compile_error!`] in the generated code. This produces a better diagnostic /// message than simply panicking the macro. /// -/// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html +/// [`compile_error!`]: std::compile_error! /// /// When parsing macro input, the [`parse_macro_input!`] macro handles the /// conversion to `compile_error!` automatically. /// /// ``` -/// extern crate proc_macro; -/// +/// # extern crate proc_macro; +/// # /// use proc_macro::TokenStream; /// use syn::{parse_macro_input, AttributeArgs, ItemFn}; /// @@ -82,7 +79,6 @@ pub type Result<T> = std::result::Result<T, Error>; /// # } /// # } /// ``` -#[derive(Clone)] pub struct Error { messages: Vec<ErrorMessage>, } @@ -193,7 +189,7 @@ impl Error { /// The [`parse_macro_input!`] macro provides a convenient way to invoke /// this method correctly in a procedural macro. /// - /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html + /// [`compile_error!`]: std::compile_error! pub fn to_compile_error(&self) -> TokenStream { self.messages .iter() @@ -201,6 +197,42 @@ impl Error { .collect() } + /// Render the error as an invocation of [`compile_error!`]. + /// + /// [`compile_error!`]: std::compile_error! + /// + /// # Example + /// + /// ``` + /// # extern crate proc_macro; + /// # + /// use proc_macro::TokenStream; + /// use syn::{parse_macro_input, DeriveInput, Error}; + /// + /// # const _: &str = stringify! { + /// #[proc_macro_derive(MyTrait)] + /// # }; + /// pub fn derive_my_trait(input: TokenStream) -> TokenStream { + /// let input = parse_macro_input!(input as DeriveInput); + /// my_trait::expand(input) + /// .unwrap_or_else(Error::into_compile_error) + /// .into() + /// } + /// + /// mod my_trait { + /// use proc_macro2::TokenStream; + /// use syn::{DeriveInput, Result}; + /// + /// pub(crate) fn expand(input: DeriveInput) -> Result<TokenStream> { + /// /* ... */ + /// # unimplemented!() + /// } + /// } + /// ``` + pub fn into_compile_error(self) -> TokenStream { + self.to_compile_error() + } + /// Add another error message to self such that when `to_compile_error()` is /// called, both errors will be emitted together. pub fn combine(&mut self, another: Error) { @@ -250,6 +282,17 @@ pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error { } } +#[cfg(all(feature = "parsing", any(feature = "full", feature = "derive")))] +pub fn new2<T: Display>(start: Span, end: Span, message: T) -> Error { + Error { + messages: vec![ErrorMessage { + start_span: ThreadBound::new(start), + end_span: ThreadBound::new(end), + message: message.to_string(), + }], + } +} + impl Debug for Error { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if self.messages.len() == 1 { @@ -278,6 +321,14 @@ impl Display for Error { } } +impl Clone for Error { + fn clone(&self) -> Self { + Error { + messages: self.messages.clone(), + } + } +} + impl Clone for ErrorMessage { fn clone(&self) -> Self { let start = self @@ -294,15 +345,11 @@ impl Clone for ErrorMessage { } } -impl std::error::Error for Error { - fn description(&self) -> &str { - "parse error" - } -} +impl std::error::Error for Error {} impl From<LexError> for Error { fn from(err: LexError) -> Self { - Error::new(Span::call_site(), format!("{:?}", err)) + Error::new(err.span(), "lex error") } } @@ -355,3 +402,11 @@ impl<'a> Iterator for Iter<'a> { }) } } + +impl Extend<Error> for Error { + fn extend<T: IntoIterator<Item = Error>>(&mut self, iter: T) { + for err in iter { + self.combine(err); + } + } +} diff --git a/1.0.7/src/export.rs b/src/export.rs index 37dc467a..601a214b 100644 --- a/1.0.7/src/export.rs +++ b/src/export.rs @@ -33,3 +33,5 @@ mod help { pub type Bool = bool; pub type Str = str; } + +pub struct private(pub(crate) ()); diff --git a/1.0.7/src/expr.rs b/src/expr.rs index 2874a463..a35532d4 100644 --- a/1.0.7/src/expr.rs +++ b/src/expr.rs @@ -1,18 +1,21 @@ use super::*; use crate::punctuated::Punctuated; -#[cfg(feature = "extra-traits")] -use crate::tt::TokenStreamHelper; +#[cfg(feature = "full")] +use crate::reserved::Reserved; use proc_macro2::{Span, TokenStream}; -#[cfg(feature = "extra-traits")] +#[cfg(feature = "printing")] +use quote::IdentFragment; +#[cfg(feature = "printing")] +use std::fmt::{self, Display}; use std::hash::{Hash, Hasher}; -#[cfg(all(feature = "parsing", feature = "full"))] +#[cfg(feature = "parsing")] use std::mem; ast_enum_of_structs! { /// A Rust expression. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature, but most of the variants are not available unless "full" is enabled.* /// /// # Syntax tree enums /// @@ -83,7 +86,8 @@ ast_enum_of_structs! { /// A sign that you may not be choosing the right variable names is if you /// see names getting repeated in your code, like accessing /// `receiver.receiver` or `pat.pat` or `cond.cond`. - pub enum Expr #manual_extra_traits { + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub enum Expr { /// A slice literal expression: `[a, b, c, d]`. Array(ExprArray), @@ -220,15 +224,39 @@ ast_enum_of_structs! { /// A yield expression: `yield expr`. Yield(ExprYield), + // The following is the only supported idiom for exhaustive matching of + // this enum. + // + // match expr { + // Expr::Array(e) => {...} + // Expr::Assign(e) => {...} + // ... + // Expr::Yield(e) => {...} + // + // #[cfg(test)] + // Expr::__TestExhaustive(_) => unimplemented!(), + // #[cfg(not(test))] + // _ => { /* some sane fallback */ } + // } + // + // This way we fail your tests but don't break your library when adding + // a variant. You will be notified by a test failure when a variant is + // added, so that you can add code to handle it, but your library will + // continue to compile and work for downstream users in the interim. + // + // Once `deny(reachable)` is available in rustc, Expr will be + // reimplemented as a non_exhaustive enum. + // https://github.com/rust-lang/rust/issues/44109#issuecomment-521781237 #[doc(hidden)] - __Nonexhaustive, + __TestExhaustive(crate::private), } } ast_struct! { /// A slice literal expression: `[a, b, c, d]`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprArray #full { pub attrs: Vec<Attribute>, pub bracket_token: token::Bracket, @@ -239,7 +267,8 @@ ast_struct! { ast_struct! { /// An assignment expression: `a = compute()`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprAssign #full { pub attrs: Vec<Attribute>, pub left: Box<Expr>, @@ -251,7 +280,8 @@ ast_struct! { ast_struct! { /// A compound assignment expression: `counter += 1`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprAssignOp #full { pub attrs: Vec<Attribute>, pub left: Box<Expr>, @@ -263,7 +293,8 @@ ast_struct! { ast_struct! { /// An async block: `async { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprAsync #full { pub attrs: Vec<Attribute>, pub async_token: Token![async], @@ -275,7 +306,8 @@ ast_struct! { ast_struct! { /// An await expression: `fut.await`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprAwait #full { pub attrs: Vec<Attribute>, pub base: Box<Expr>, @@ -287,8 +319,9 @@ ast_struct! { ast_struct! { /// A binary operation: `a + b`, `a * b`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ExprBinary { pub attrs: Vec<Attribute>, pub left: Box<Expr>, @@ -300,7 +333,8 @@ ast_struct! { ast_struct! { /// A blocked scope: `{ ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprBlock #full { pub attrs: Vec<Attribute>, pub label: Option<Label>, @@ -311,7 +345,8 @@ ast_struct! { ast_struct! { /// A box expression: `box f`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprBox #full { pub attrs: Vec<Attribute>, pub box_token: Token![box], @@ -323,7 +358,8 @@ ast_struct! { /// A `break`, with an optional label to break and an optional /// expression. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprBreak #full { pub attrs: Vec<Attribute>, pub break_token: Token![break], @@ -335,8 +371,9 @@ ast_struct! { ast_struct! { /// A function call expression: `invoke(a, b)`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ExprCall { pub attrs: Vec<Attribute>, pub func: Box<Expr>, @@ -348,8 +385,9 @@ ast_struct! { ast_struct! { /// A cast expression: `foo as f64`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ExprCast { pub attrs: Vec<Attribute>, pub expr: Box<Expr>, @@ -361,7 +399,8 @@ ast_struct! { ast_struct! { /// A closure expression: `|a, b| a + b`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprClosure #full { pub attrs: Vec<Attribute>, pub asyncness: Option<Token![async]>, @@ -378,7 +417,8 @@ ast_struct! { ast_struct! { /// A `continue`, with an optional label. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprContinue #full { pub attrs: Vec<Attribute>, pub continue_token: Token![continue], @@ -390,7 +430,8 @@ ast_struct! { /// Access of a named struct field (`obj.k`) or unnamed tuple struct /// field (`obj.0`). /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ExprField { pub attrs: Vec<Attribute>, pub base: Box<Expr>, @@ -402,7 +443,8 @@ ast_struct! { ast_struct! { /// A for loop: `for pat in expr { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprForLoop #full { pub attrs: Vec<Attribute>, pub label: Option<Label>, @@ -421,7 +463,8 @@ ast_struct! { /// of expressions and is related to `None`-delimited spans in a /// `TokenStream`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprGroup #full { pub attrs: Vec<Attribute>, pub group_token: token::Group, @@ -436,7 +479,8 @@ ast_struct! { /// The `else` branch expression may only be an `If` or `Block` /// expression, not any of the other types of expression. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprIf #full { pub attrs: Vec<Attribute>, pub if_token: Token![if], @@ -449,8 +493,9 @@ ast_struct! { ast_struct! { /// A square bracketed indexing expression: `vector[2]`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ExprIndex { pub attrs: Vec<Attribute>, pub expr: Box<Expr>, @@ -462,7 +507,8 @@ ast_struct! { ast_struct! { /// A `let` guard: `let Some(x) = opt`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprLet #full { pub attrs: Vec<Attribute>, pub let_token: Token![let], @@ -475,8 +521,9 @@ ast_struct! { ast_struct! { /// A literal in place of an expression: `1`, `"foo"`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ExprLit { pub attrs: Vec<Attribute>, pub lit: Lit, @@ -486,7 +533,8 @@ ast_struct! { ast_struct! { /// Conditionless loop: `loop { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprLoop #full { pub attrs: Vec<Attribute>, pub label: Option<Label>, @@ -498,7 +546,8 @@ ast_struct! { ast_struct! { /// A macro invocation expression: `format!("{}", q)`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprMacro #full { pub attrs: Vec<Attribute>, pub mac: Macro, @@ -508,7 +557,8 @@ ast_struct! { ast_struct! { /// A `match` expression: `match n { Some(n) => {}, None => {} }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprMatch #full { pub attrs: Vec<Attribute>, pub match_token: Token![match], @@ -521,7 +571,8 @@ ast_struct! { ast_struct! { /// A method call expression: `x.foo::<T>(a, b)`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprMethodCall #full { pub attrs: Vec<Attribute>, pub receiver: Box<Expr>, @@ -536,7 +587,8 @@ ast_struct! { ast_struct! { /// A parenthesized expression: `(a + b)`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ExprParen { pub attrs: Vec<Attribute>, pub paren_token: token::Paren, @@ -550,8 +602,9 @@ ast_struct! { /// /// A plain identifier like `x` is a path of length 1. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ExprPath { pub attrs: Vec<Attribute>, pub qself: Option<QSelf>, @@ -562,7 +615,8 @@ ast_struct! { ast_struct! { /// A range expression: `1..2`, `1..`, `..2`, `1..=2`, `..=2`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprRange #full { pub attrs: Vec<Attribute>, pub from: Option<Box<Expr>>, @@ -574,7 +628,8 @@ ast_struct! { ast_struct! { /// A referencing operation: `&a` or `&mut a`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprReference #full { pub attrs: Vec<Attribute>, pub and_token: Token![&], @@ -587,7 +642,8 @@ ast_struct! { ast_struct! { /// An array literal constructed from one repeated element: `[0u8; N]`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprRepeat #full { pub attrs: Vec<Attribute>, pub bracket_token: token::Bracket, @@ -600,7 +656,8 @@ ast_struct! { ast_struct! { /// A `return`, with an optional value to be returned. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprReturn #full { pub attrs: Vec<Attribute>, pub return_token: Token![return], @@ -614,7 +671,8 @@ ast_struct! { /// The `rest` provides the value of the remaining fields as in `S { a: /// 1, b: 1, ..rest }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprStruct #full { pub attrs: Vec<Attribute>, pub path: Path, @@ -628,7 +686,8 @@ ast_struct! { ast_struct! { /// A try-expression: `expr?`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprTry #full { pub attrs: Vec<Attribute>, pub expr: Box<Expr>, @@ -639,7 +698,8 @@ ast_struct! { ast_struct! { /// A try block: `try { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprTryBlock #full { pub attrs: Vec<Attribute>, pub try_token: Token![try], @@ -650,7 +710,8 @@ ast_struct! { ast_struct! { /// A tuple expression: `(a, b, c, d)`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprTuple #full { pub attrs: Vec<Attribute>, pub paren_token: token::Paren, @@ -661,7 +722,8 @@ ast_struct! { ast_struct! { /// A type ascription expression: `foo: f64`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprType #full { pub attrs: Vec<Attribute>, pub expr: Box<Expr>, @@ -673,8 +735,9 @@ ast_struct! { ast_struct! { /// A unary operation: `!x`, `*x`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ExprUnary { pub attrs: Vec<Attribute>, pub op: UnOp, @@ -685,7 +748,8 @@ ast_struct! { ast_struct! { /// An unsafe block: `unsafe { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprUnsafe #full { pub attrs: Vec<Attribute>, pub unsafe_token: Token![unsafe], @@ -696,7 +760,8 @@ ast_struct! { ast_struct! { /// A while loop: `while expr { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprWhile #full { pub attrs: Vec<Attribute>, pub label: Option<Label>, @@ -709,7 +774,8 @@ ast_struct! { ast_struct! { /// A yield expression: `yield expr`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ExprYield #full { pub attrs: Vec<Attribute>, pub yield_token: Token![yield], @@ -717,232 +783,6 @@ ast_struct! { } } -#[cfg(feature = "extra-traits")] -impl Eq for Expr {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Expr { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Expr::Array(this), Expr::Array(other)) => this == other, - (Expr::Assign(this), Expr::Assign(other)) => this == other, - (Expr::AssignOp(this), Expr::AssignOp(other)) => this == other, - (Expr::Async(this), Expr::Async(other)) => this == other, - (Expr::Await(this), Expr::Await(other)) => this == other, - (Expr::Binary(this), Expr::Binary(other)) => this == other, - (Expr::Block(this), Expr::Block(other)) => this == other, - (Expr::Box(this), Expr::Box(other)) => this == other, - (Expr::Break(this), Expr::Break(other)) => this == other, - (Expr::Call(this), Expr::Call(other)) => this == other, - (Expr::Cast(this), Expr::Cast(other)) => this == other, - (Expr::Closure(this), Expr::Closure(other)) => this == other, - (Expr::Continue(this), Expr::Continue(other)) => this == other, - (Expr::Field(this), Expr::Field(other)) => this == other, - (Expr::ForLoop(this), Expr::ForLoop(other)) => this == other, - (Expr::Group(this), Expr::Group(other)) => this == other, - (Expr::If(this), Expr::If(other)) => this == other, - (Expr::Index(this), Expr::Index(other)) => this == other, - (Expr::Let(this), Expr::Let(other)) => this == other, - (Expr::Lit(this), Expr::Lit(other)) => this == other, - (Expr::Loop(this), Expr::Loop(other)) => this == other, - (Expr::Macro(this), Expr::Macro(other)) => this == other, - (Expr::Match(this), Expr::Match(other)) => this == other, - (Expr::MethodCall(this), Expr::MethodCall(other)) => this == other, - (Expr::Paren(this), Expr::Paren(other)) => this == other, - (Expr::Path(this), Expr::Path(other)) => this == other, - (Expr::Range(this), Expr::Range(other)) => this == other, - (Expr::Reference(this), Expr::Reference(other)) => this == other, - (Expr::Repeat(this), Expr::Repeat(other)) => this == other, - (Expr::Return(this), Expr::Return(other)) => this == other, - (Expr::Struct(this), Expr::Struct(other)) => this == other, - (Expr::Try(this), Expr::Try(other)) => this == other, - (Expr::TryBlock(this), Expr::TryBlock(other)) => this == other, - (Expr::Tuple(this), Expr::Tuple(other)) => this == other, - (Expr::Type(this), Expr::Type(other)) => this == other, - (Expr::Unary(this), Expr::Unary(other)) => this == other, - (Expr::Unsafe(this), Expr::Unsafe(other)) => this == other, - (Expr::Verbatim(this), Expr::Verbatim(other)) => { - TokenStreamHelper(this) == TokenStreamHelper(other) - } - (Expr::While(this), Expr::While(other)) => this == other, - (Expr::Yield(this), Expr::Yield(other)) => this == other, - _ => false, - } - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Expr { - fn hash<H>(&self, hash: &mut H) - where - H: Hasher, - { - match self { - Expr::Array(expr) => { - hash.write_u8(0); - expr.hash(hash); - } - Expr::Assign(expr) => { - hash.write_u8(1); - expr.hash(hash); - } - Expr::AssignOp(expr) => { - hash.write_u8(2); - expr.hash(hash); - } - Expr::Async(expr) => { - hash.write_u8(3); - expr.hash(hash); - } - Expr::Await(expr) => { - hash.write_u8(4); - expr.hash(hash); - } - Expr::Binary(expr) => { - hash.write_u8(5); - expr.hash(hash); - } - Expr::Block(expr) => { - hash.write_u8(6); - expr.hash(hash); - } - Expr::Box(expr) => { - hash.write_u8(7); - expr.hash(hash); - } - Expr::Break(expr) => { - hash.write_u8(8); - expr.hash(hash); - } - Expr::Call(expr) => { - hash.write_u8(9); - expr.hash(hash); - } - Expr::Cast(expr) => { - hash.write_u8(10); - expr.hash(hash); - } - Expr::Closure(expr) => { - hash.write_u8(11); - expr.hash(hash); - } - Expr::Continue(expr) => { - hash.write_u8(12); - expr.hash(hash); - } - Expr::Field(expr) => { - hash.write_u8(13); - expr.hash(hash); - } - Expr::ForLoop(expr) => { - hash.write_u8(14); - expr.hash(hash); - } - Expr::Group(expr) => { - hash.write_u8(15); - expr.hash(hash); - } - Expr::If(expr) => { - hash.write_u8(16); - expr.hash(hash); - } - Expr::Index(expr) => { - hash.write_u8(17); - expr.hash(hash); - } - Expr::Let(expr) => { - hash.write_u8(18); - expr.hash(hash); - } - Expr::Lit(expr) => { - hash.write_u8(19); - expr.hash(hash); - } - Expr::Loop(expr) => { - hash.write_u8(20); - expr.hash(hash); - } - Expr::Macro(expr) => { - hash.write_u8(21); - expr.hash(hash); - } - Expr::Match(expr) => { - hash.write_u8(22); - expr.hash(hash); - } - Expr::MethodCall(expr) => { - hash.write_u8(23); - expr.hash(hash); - } - Expr::Paren(expr) => { - hash.write_u8(24); - expr.hash(hash); - } - Expr::Path(expr) => { - hash.write_u8(25); - expr.hash(hash); - } - Expr::Range(expr) => { - hash.write_u8(26); - expr.hash(hash); - } - Expr::Reference(expr) => { - hash.write_u8(27); - expr.hash(hash); - } - Expr::Repeat(expr) => { - hash.write_u8(28); - expr.hash(hash); - } - Expr::Return(expr) => { - hash.write_u8(29); - expr.hash(hash); - } - Expr::Struct(expr) => { - hash.write_u8(30); - expr.hash(hash); - } - Expr::Try(expr) => { - hash.write_u8(31); - expr.hash(hash); - } - Expr::TryBlock(expr) => { - hash.write_u8(32); - expr.hash(hash); - } - Expr::Tuple(expr) => { - hash.write_u8(33); - expr.hash(hash); - } - Expr::Type(expr) => { - hash.write_u8(34); - expr.hash(hash); - } - Expr::Unary(expr) => { - hash.write_u8(35); - expr.hash(hash); - } - Expr::Unsafe(expr) => { - hash.write_u8(36); - expr.hash(hash); - } - Expr::Verbatim(expr) => { - hash.write_u8(37); - TokenStreamHelper(expr).hash(hash); - } - Expr::While(expr) => { - hash.write_u8(38); - expr.hash(hash); - } - Expr::Yield(expr) => { - hash.write_u8(39); - expr.hash(hash); - } - Expr::__Nonexhaustive => unreachable!(), - } - } -} - impl Expr { #[cfg(all(feature = "parsing", feature = "full"))] pub(crate) fn replace_attrs(&mut self, new: Vec<Attribute>) -> Vec<Attribute> { @@ -987,7 +827,11 @@ impl Expr { | Expr::TryBlock(ExprTryBlock { attrs, .. }) | Expr::Yield(ExprYield { attrs, .. }) => mem::replace(attrs, new), Expr::Verbatim(_) => Vec::new(), - Expr::__Nonexhaustive => unreachable!(), + + #[cfg(test)] + Expr::__TestExhaustive(_) => unimplemented!(), + #[cfg(not(test))] + _ => unreachable!(), } } } @@ -996,8 +840,9 @@ ast_enum! { /// A struct or tuple struct field accessed in a struct literal or field /// expression. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum Member { /// A named field like `self.x`. Named(Ident), @@ -1006,12 +851,51 @@ ast_enum! { } } +impl Eq for Member {} + +impl PartialEq for Member { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Member::Named(this), Member::Named(other)) => this == other, + (Member::Unnamed(this), Member::Unnamed(other)) => this == other, + _ => false, + } + } +} + +impl Hash for Member { + fn hash<H: Hasher>(&self, state: &mut H) { + match self { + Member::Named(m) => m.hash(state), + Member::Unnamed(m) => m.hash(state), + } + } +} + +#[cfg(feature = "printing")] +impl IdentFragment for Member { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Member::Named(m) => Display::fmt(m, formatter), + Member::Unnamed(m) => Display::fmt(&m.index, formatter), + } + } + + fn span(&self) -> Option<Span> { + match self { + Member::Named(m) => Some(m.span()), + Member::Unnamed(m) => Some(m.span), + } + } +} + ast_struct! { /// The index of an unnamed tuple struct field. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* - pub struct Index #manual_extra_traits { + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct Index { pub index: u32, pub span: Span, } @@ -1027,28 +911,28 @@ impl From<usize> for Index { } } -#[cfg(feature = "extra-traits")] impl Eq for Index {} -#[cfg(feature = "extra-traits")] impl PartialEq for Index { fn eq(&self, other: &Self) -> bool { self.index == other.index } } -#[cfg(feature = "extra-traits")] impl Hash for Index { fn hash<H: Hasher>(&self, state: &mut H) { self.index.hash(state); } } -#[cfg(feature = "full")] -ast_struct! { - #[derive(Default)] - pub struct Reserved { - private: (), +#[cfg(feature = "printing")] +impl IdentFragment for Index { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.index, formatter) + } + + fn span(&self) -> Option<Span> { + Some(self.span) } } @@ -1057,7 +941,8 @@ ast_struct! { /// The `::<>` explicit type parameters passed to a method call: /// `parse::<u64>()`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct MethodTurbofish { pub colon2_token: Token![::], pub lt_token: Token![<], @@ -1070,7 +955,8 @@ ast_struct! { ast_enum! { /// An individual generic argument to a method, like `T`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub enum GenericMethodArgument { /// A type argument. Type(Type), @@ -1086,7 +972,8 @@ ast_enum! { ast_struct! { /// A field-value pair in a struct literal. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct FieldValue { /// Attributes tagged on the field. pub attrs: Vec<Attribute>, @@ -1107,7 +994,8 @@ ast_struct! { ast_struct! { /// A lifetime labeling a `for`, `while`, or `loop`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct Label { pub name: Lifetime, pub colon_token: Token![:], @@ -1134,7 +1022,8 @@ ast_struct! { /// # } /// ``` /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct Arm { pub attrs: Vec<Attribute>, pub pat: Pat, @@ -1149,8 +1038,8 @@ ast_struct! { ast_enum! { /// Limit types of a range, inclusive or exclusive. /// - /// *This type is available if Syn is built with the `"full"` feature.* - #[cfg_attr(feature = "clone-impls", derive(Copy))] + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub enum RangeLimits { /// Inclusive at the beginning, exclusive at the end. HalfOpen(Token![..]), @@ -1162,7 +1051,7 @@ ast_enum! { #[cfg(any(feature = "parsing", feature = "printing"))] #[cfg(feature = "full")] pub(crate) fn requires_terminator(expr: &Expr) -> bool { - // see https://github.com/rust-lang/rust/blob/eb8f2586e/src/libsyntax/parse/classify.rs#L17-L37 + // see https://github.com/rust-lang/rust/blob/2679c38fc/src/librustc_ast/util/classify.rs#L7-L25 match *expr { Expr::Unsafe(..) | Expr::Block(..) @@ -1180,19 +1069,21 @@ pub(crate) fn requires_terminator(expr: &Expr) -> bool { #[cfg(feature = "parsing")] pub(crate) mod parsing { use super::*; - use crate::parse::{Parse, ParseStream, Result}; use crate::path; + #[cfg(feature = "full")] + use proc_macro2::TokenTree; + use std::cmp::Ordering; + + 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. // // Struct literals are ambiguous in certain positions // https://github.com/rust-lang/rfcs/pull/92 - #[derive(Copy, Clone)] pub struct AllowStruct(bool); - #[derive(Copy, Clone, PartialEq, PartialOrd)] enum Precedence { Any, Assign, @@ -1240,15 +1131,129 @@ pub(crate) mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Expr { fn parse(input: ParseStream) -> Result<Self> { ambiguous_expr(input, AllowStruct(true)) } } - #[cfg(feature = "full")] - fn expr_no_struct(input: ParseStream) -> Result<Expr> { - ambiguous_expr(input, AllowStruct(false)) + impl Expr { + /// An alternative to the primary `Expr::parse` parser (from the + /// [`Parse`] trait) for ambiguous syntactic positions in which a + /// trailing brace should not be taken as part of the expression. + /// + /// Rust grammar has an ambiguity where braces sometimes turn a path + /// expression into a struct initialization and sometimes do not. In the + /// following code, the expression `S {}` is one expression. Presumably + /// there is an empty struct `struct S {}` defined somewhere which it is + /// instantiating. + /// + /// ``` + /// # struct S; + /// # impl std::ops::Deref for S { + /// # type Target = bool; + /// # fn deref(&self) -> &Self::Target { + /// # &true + /// # } + /// # } + /// let _ = *S {}; + /// + /// // parsed by rustc as: `*(S {})` + /// ``` + /// + /// We would want to parse the above using `Expr::parse` after the `=` + /// token. + /// + /// But in the following, `S {}` is *not* a struct init expression. + /// + /// ``` + /// # const S: &bool = &true; + /// if *S {} {} + /// + /// // parsed by rustc as: + /// // + /// // if (*S) { + /// // /* empty block */ + /// // } + /// // { + /// // /* another empty block */ + /// // } + /// ``` + /// + /// For that reason we would want to parse if-conditions using + /// `Expr::parse_without_eager_brace` after the `if` token. Same for + /// similar syntactic positions such as the condition expr after a + /// `while` token or the expr at the top of a `match`. + /// + /// The Rust grammar's choices around which way this ambiguity is + /// resolved at various syntactic positions is fairly arbitrary. Really + /// either parse behavior could work in most positions, and language + /// designers just decide each case based on which is more likely to be + /// what the programmer had in mind most of the time. + /// + /// ``` + /// # struct S; + /// # fn doc() -> S { + /// if return S {} {} + /// # unreachable!() + /// # } + /// + /// // parsed by rustc as: + /// // + /// // if (return (S {})) { + /// // } + /// // + /// // but could equally well have been this other arbitrary choice: + /// // + /// // if (return S) { + /// // } + /// // {} + /// ``` + /// + /// Note the grammar ambiguity on trailing braces is distinct from + /// precedence and is not captured by assigning a precedence level to + /// the braced struct init expr in relation to other operators. This can + /// be illustrated by `return 0..S {}` vs `match 0..S {}`. The former + /// parses as `return (0..(S {}))` implying tighter precedence for + /// struct init than `..`, while the latter parses as `match (0..S) {}` + /// implying tighter precedence for `..` than struct init, a + /// contradiction. + #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(all(feature = "full", feature = "parsing"))))] + pub fn parse_without_eager_brace(input: ParseStream) -> Result<Expr> { + ambiguous_expr(input, AllowStruct(false)) + } + } + + impl Copy for AllowStruct {} + + impl Clone for AllowStruct { + fn clone(&self) -> Self { + *self + } + } + + impl Copy for Precedence {} + + impl Clone for Precedence { + fn clone(&self) -> Self { + *self + } + } + + impl PartialEq for Precedence { + fn eq(&self, other: &Self) -> bool { + *self as u8 == *other as u8 + } + } + + impl PartialOrd for Precedence { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + let this = *self as u8; + let other = *other as u8; + Some(this.cmp(&other)) + } } #[cfg(feature = "full")] @@ -1417,7 +1422,9 @@ pub(crate) mod parsing { Precedence::Assign } else if input.peek(Token![..]) { Precedence::Range - } else if input.peek(Token![as]) || input.peek(Token![:]) && !input.peek(Token![::]) { + } else if input.peek(Token![as]) + || cfg!(feature = "full") && input.peek(Token![:]) && !input.peek(Token![::]) + { Precedence::Cast } else { Precedence::Any @@ -1430,56 +1437,76 @@ pub(crate) mod parsing { parse_expr(input, lhs, allow_struct, Precedence::Any) } + #[cfg(feature = "full")] + fn expr_attrs(input: ParseStream) -> Result<Vec<Attribute>> { + let mut attrs = Vec::new(); + loop { + if input.peek(token::Group) { + let ahead = input.fork(); + let group = crate::group::parse_group(&ahead)?; + if !group.content.peek(Token![#]) || group.content.peek2(Token![!]) { + break; + } + let attr = group.content.call(attr::parsing::single_parse_outer)?; + if !group.content.is_empty() { + break; + } + attrs.push(attr); + } else if input.peek(Token![#]) { + attrs.push(input.call(attr::parsing::single_parse_outer)?); + } else { + break; + } + } + Ok(attrs) + } + // <UnOp> <trailer> // & <trailer> // &mut <trailer> // box <trailer> #[cfg(feature = "full")] fn unary_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - // TODO: optimize using advance_to - let ahead = input.fork(); - ahead.call(Attribute::parse_outer)?; - if ahead.peek(Token![&]) - || ahead.peek(Token![box]) - || ahead.peek(Token![*]) - || ahead.peek(Token![!]) - || ahead.peek(Token![-]) - { - let attrs = input.call(Attribute::parse_outer)?; - if input.peek(Token![&]) { + let begin = input.fork(); + let attrs = input.call(expr_attrs)?; + if input.peek(Token![&]) { + let and_token: Token![&] = input.parse()?; + let raw: Option<raw> = + if input.peek(raw) && (input.peek2(Token![mut]) || input.peek2(Token![const])) { + Some(input.parse()?) + } else { + None + }; + let mutability: Option<Token![mut]> = input.parse()?; + if raw.is_some() && mutability.is_none() { + input.parse::<Token![const]>()?; + } + let expr = Box::new(unary_expr(input, allow_struct)?); + if raw.is_some() { + Ok(Expr::Verbatim(verbatim::between(begin, input))) + } else { Ok(Expr::Reference(ExprReference { attrs, - and_token: input.parse()?, + and_token, raw: Reserved::default(), - mutability: input.parse()?, - expr: Box::new(unary_expr(input, allow_struct)?), - })) - } else if input.peek(Token![box]) { - Ok(Expr::Box(ExprBox { - attrs, - box_token: input.parse()?, - expr: Box::new(unary_expr(input, allow_struct)?), - })) - } else { - Ok(Expr::Unary(ExprUnary { - attrs, - op: input.parse()?, - expr: Box::new(unary_expr(input, allow_struct)?), + mutability, + expr, })) } + } else if input.peek(Token![box]) { + expr_box(input, attrs, allow_struct).map(Expr::Box) + } else if input.peek(Token![*]) || input.peek(Token![!]) || input.peek(Token![-]) { + expr_unary(input, attrs, allow_struct).map(Expr::Unary) } else { - trailer_expr(input, allow_struct) + trailer_expr(attrs, input, allow_struct) } } #[cfg(not(feature = "full"))] fn unary_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - // TODO: optimize using advance_to - let ahead = input.fork(); - ahead.call(Attribute::parse_outer)?; - if ahead.peek(Token![*]) || ahead.peek(Token![!]) || ahead.peek(Token![-]) { + if input.peek(Token![*]) || input.peek(Token![!]) || input.peek(Token![-]) { Ok(Expr::Unary(ExprUnary { - attrs: input.call(Attribute::parse_outer)?, + attrs: Vec::new(), op: input.parse()?, expr: Box::new(unary_expr(input, allow_struct)?), })) @@ -1495,13 +1522,11 @@ pub(crate) mod parsing { // <atom> [ <expr> ] ... // <atom> ? ... #[cfg(feature = "full")] - fn trailer_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - if input.peek(token::Group) { - return input.call(expr_group).map(Expr::Group); - } - - let outer_attrs = input.call(Attribute::parse_outer)?; - + fn trailer_expr( + outer_attrs: Vec<Attribute>, + input: ParseStream, + allow_struct: AllowStruct, + ) -> Result<Expr> { let atom = atom_expr(input, allow_struct)?; let mut e = trailer_helper(input, atom)?; @@ -1523,18 +1548,26 @@ pub(crate) mod parsing { args: content.parse_terminated(Expr::parse)?, }); } else if input.peek(Token![.]) && !input.peek(Token![..]) { - let dot_token: Token![.] = input.parse()?; + let mut dot_token: Token![.] = input.parse()?; - if input.peek(token::Await) { + let await_token: Option<token::Await> = input.parse()?; + if let Some(await_token) = await_token { e = Expr::Await(ExprAwait { attrs: Vec::new(), base: Box::new(e), dot_token, - await_token: input.parse()?, + await_token, }); continue; } + let float_token: Option<LitFloat> = input.parse()?; + if let Some(float_token) = float_token { + if multi_index(&mut e, &mut dot_token, float_token)? { + continue; + } + } + let member: Member = input.parse()?; let turbofish = if member.is_named() && input.peek(Token![::]) { Some(MethodTurbofish { @@ -1620,10 +1653,17 @@ pub(crate) mod parsing { }); } else if input.peek(Token![.]) && !input.peek(Token![..]) && !input.peek2(token::Await) { + let mut dot_token: Token![.] = input.parse()?; + let float_token: Option<LitFloat> = input.parse()?; + if let Some(float_token) = float_token { + if multi_index(&mut e, &mut dot_token, float_token)? { + continue; + } + } e = Expr::Field(ExprField { attrs: Vec::new(), base: Box::new(e), - dot_token: input.parse()?, + dot_token, member: input.parse()?, }); } else if input.peek(token::Bracket) { @@ -1646,16 +1686,20 @@ pub(crate) mod parsing { // interactions, as they are fully contained. #[cfg(feature = "full")] fn atom_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> { - if input.peek(token::Group) { + if input.peek(token::Group) + && !input.peek2(Token![::]) + && !input.peek2(Token![!]) + && !input.peek2(token::Brace) + { input.call(expr_group).map(Expr::Group) } else if input.peek(Lit) { input.parse().map(Expr::Lit) } else if input.peek(Token![async]) && (input.peek2(token::Brace) || input.peek2(Token![move]) && input.peek3(token::Brace)) { - input.call(expr_async).map(Expr::Async) + input.parse().map(Expr::Async) } else if input.peek(Token![try]) && input.peek2(token::Brace) { - input.call(expr_try_block).map(Expr::TryBlock) + input.parse().map(Expr::TryBlock) } else if input.peek(Token![|]) || input.peek(Token![async]) && (input.peek2(Token![|]) || input.peek2(Token![move])) || input.peek(Token![static]) @@ -1668,7 +1712,6 @@ pub(crate) mod parsing { || input.peek(Token![self]) || input.peek(Token![Self]) || input.peek(Token![super]) - || input.peek(Token![extern]) || input.peek(Token![crate]) { path_or_macro_or_struct(input, allow_struct) @@ -1677,13 +1720,13 @@ pub(crate) mod parsing { } else if input.peek(Token![break]) { expr_break(input, allow_struct).map(Expr::Break) } else if input.peek(Token![continue]) { - input.call(expr_continue).map(Expr::Continue) + input.parse().map(Expr::Continue) } else if input.peek(Token![return]) { expr_ret(input, allow_struct).map(Expr::Return) } else if input.peek(token::Bracket) { array_or_repeat(input) } else if input.peek(Token![let]) { - input.call(expr_let).map(Expr::Let) + input.parse().map(Expr::Let) } else if input.peek(Token![if]) { input.parse().map(Expr::If) } else if input.peek(Token![while]) { @@ -1695,13 +1738,19 @@ pub(crate) mod parsing { } else if input.peek(Token![match]) { input.parse().map(Expr::Match) } else if input.peek(Token![yield]) { - input.call(expr_yield).map(Expr::Yield) + input.parse().map(Expr::Yield) } else if input.peek(Token![unsafe]) { - input.call(expr_unsafe).map(Expr::Unsafe) + input.parse().map(Expr::Unsafe) + } else if input.peek(Token![const]) { + input.call(expr_const).map(Expr::Verbatim) } else if input.peek(token::Brace) { - input.call(expr_block).map(Expr::Block) + input.parse().map(Expr::Block) } else if input.peek(Token![..]) { expr_range(input, allow_struct).map(Expr::Range) + } else if input.peek(Token![_]) { + Ok(Expr::Verbatim(TokenStream::from( + input.parse::<TokenTree>()?, + ))) } else if input.peek(Lifetime) { let the_label: Label = input.parse()?; let mut expr = if input.peek(Token![while]) { @@ -1711,7 +1760,7 @@ pub(crate) mod parsing { } else if input.peek(Token![loop]) { Expr::Loop(input.parse()?) } else if input.peek(token::Brace) { - Expr::Block(input.call(expr_block)?) + Expr::Block(input.parse()?) } else { return Err(input.error("expected loop or block expression")); }; @@ -1740,7 +1789,6 @@ pub(crate) mod parsing { || input.peek(Token![self]) || input.peek(Token![Self]) || input.peek(Token![super]) - || input.peek(Token![extern]) || input.peek(Token![crate]) { input.parse().map(Expr::Path) @@ -1791,6 +1839,17 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprMacro { + fn parse(input: ParseStream) -> Result<Self> { + Ok(ExprMacro { + attrs: Vec::new(), + mac: input.parse()?, + }) + } + } + + #[cfg(feature = "full")] fn paren_or_tuple(input: ParseStream) -> Result<Expr> { let content; let paren_token = parenthesized!(content in input); @@ -1877,8 +1936,50 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprArray { + fn parse(input: ParseStream) -> Result<Self> { + let content; + let bracket_token = bracketed!(content in input); + let inner_attrs = content.call(Attribute::parse_inner)?; + let mut elems = Punctuated::new(); + + while !content.is_empty() { + let first: Expr = content.parse()?; + elems.push_value(first); + if content.is_empty() { + break; + } + let punct = content.parse()?; + elems.push_punct(punct); + } + + Ok(ExprArray { + attrs: inner_attrs, + bracket_token, + elems, + }) + } + } + + #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprRepeat { + fn parse(input: ParseStream) -> Result<Self> { + let content; + Ok(ExprRepeat { + bracket_token: bracketed!(content in input), + attrs: content.call(Attribute::parse_inner)?, + expr: content.parse()?, + semi_token: content.parse()?, + len: content.parse()?, + }) + } + } + + #[cfg(feature = "full")] pub(crate) fn expr_early(input: ParseStream) -> Result<Expr> { - let mut attrs = input.call(Attribute::parse_outer)?; + let mut attrs = input.call(expr_attrs)?; let mut expr = if input.peek(Token![if]) { Expr::If(input.parse()?) } else if input.peek(Token![while]) { @@ -1890,11 +1991,13 @@ pub(crate) mod parsing { } else if input.peek(Token![match]) { Expr::Match(input.parse()?) } else if input.peek(Token![try]) && input.peek2(token::Brace) { - Expr::TryBlock(input.call(expr_try_block)?) + Expr::TryBlock(input.parse()?) } else if input.peek(Token![unsafe]) { - Expr::Unsafe(input.call(expr_unsafe)?) + Expr::Unsafe(input.parse()?) + } else if input.peek(Token![const]) { + Expr::Verbatim(input.call(expr_const)?) } else if input.peek(token::Brace) { - Expr::Block(input.call(expr_block)?) + Expr::Block(input.parse()?) } else { let allow_struct = AllowStruct(true); let mut expr = unary_expr(input, allow_struct)?; @@ -1905,7 +2008,7 @@ pub(crate) mod parsing { return parse_expr(input, expr, allow_struct, Precedence::Any); }; - if input.peek(Token![.]) || input.peek(Token![?]) { + if input.peek(Token![.]) && !input.peek(Token![..]) || input.peek(Token![?]) { expr = trailer_helper(input, expr)?; attrs.extend(expr.replace_attrs(Vec::new())); @@ -1920,6 +2023,7 @@ pub(crate) mod parsing { Ok(expr) } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ExprLit { fn parse(input: ParseStream) -> Result<Self> { Ok(ExprLit { @@ -1939,7 +2043,14 @@ pub(crate) mod parsing { }) } - #[cfg(not(feature = "full"))] + #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprParen { + fn parse(input: ParseStream) -> Result<Self> { + expr_paren(input) + } + } + fn expr_paren(input: ParseStream) -> Result<ExprParen> { let content; Ok(ExprParen { @@ -1951,53 +2062,42 @@ pub(crate) mod parsing { #[cfg(feature = "full")] fn generic_method_argument(input: ParseStream) -> Result<GenericMethodArgument> { - // TODO parse const generics as well + if input.peek(Lit) { + let lit = input.parse()?; + return Ok(GenericMethodArgument::Const(Expr::Lit(lit))); + } + + if input.peek(token::Brace) { + let block: ExprBlock = input.parse()?; + return Ok(GenericMethodArgument::Const(Expr::Block(block))); + } + input.parse().map(GenericMethodArgument::Type) } #[cfg(feature = "full")] - fn expr_let(input: ParseStream) -> Result<ExprLet> { - Ok(ExprLet { - attrs: Vec::new(), - let_token: input.parse()?, - pat: { - let leading_vert: Option<Token![|]> = input.parse()?; - let pat: Pat = input.parse()?; - if leading_vert.is_some() - || input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=]) - { - let mut cases = Punctuated::new(); - cases.push_value(pat); - while input.peek(Token![|]) - && !input.peek(Token![||]) - && !input.peek(Token![|=]) - { - let punct = input.parse()?; - cases.push_punct(punct); - let pat: Pat = input.parse()?; - cases.push_value(pat); - } - Pat::Or(PatOr { - attrs: Vec::new(), - leading_vert, - cases, - }) - } else { - pat - } - }, - eq_token: input.parse()?, - expr: Box::new(input.call(expr_no_struct)?), - }) + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprLet { + fn parse(input: ParseStream) -> Result<Self> { + Ok(ExprLet { + attrs: Vec::new(), + let_token: input.parse()?, + pat: pat::parsing::multi_pat_with_leading_vert(input)?, + eq_token: input.parse()?, + expr: Box::new(input.call(Expr::parse_without_eager_brace)?), + }) + } } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ExprIf { fn parse(input: ParseStream) -> Result<Self> { + let attrs = input.call(Attribute::parse_outer)?; Ok(ExprIf { - attrs: Vec::new(), + attrs, if_token: input.parse()?, - cond: Box::new(input.call(expr_no_struct)?), + cond: Box::new(input.call(Expr::parse_without_eager_brace)?), then_branch: input.parse()?, else_branch: { if input.peek(Token![else]) { @@ -2031,31 +2131,17 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ExprForLoop { fn parse(input: ParseStream) -> Result<Self> { + let outer_attrs = input.call(Attribute::parse_outer)?; let label: Option<Label> = input.parse()?; let for_token: Token![for] = input.parse()?; - let leading_vert: Option<Token![|]> = input.parse()?; - let mut pat: Pat = input.parse()?; - if leading_vert.is_some() || input.peek(Token![|]) { - let mut cases = Punctuated::new(); - cases.push_value(pat); - while input.peek(Token![|]) { - let punct = input.parse()?; - cases.push_punct(punct); - let pat: Pat = input.parse()?; - cases.push_value(pat); - } - pat = Pat::Or(PatOr { - attrs: Vec::new(), - leading_vert, - cases, - }); - } + let pat = pat::parsing::multi_pat_with_leading_vert(input)?; let in_token: Token![in] = input.parse()?; - let expr: Expr = input.call(expr_no_struct)?; + let expr: Expr = input.call(Expr::parse_without_eager_brace)?; let content; let brace_token = braced!(content in input); @@ -2063,7 +2149,7 @@ pub(crate) mod parsing { let stmts = content.call(Block::parse_within)?; Ok(ExprForLoop { - attrs: inner_attrs, + attrs: private::attrs(outer_attrs, inner_attrs), label, for_token, pat, @@ -2075,8 +2161,10 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ExprLoop { fn parse(input: ParseStream) -> Result<Self> { + let outer_attrs = input.call(Attribute::parse_outer)?; let label: Option<Label> = input.parse()?; let loop_token: Token![loop] = input.parse()?; @@ -2086,7 +2174,7 @@ pub(crate) mod parsing { let stmts = content.call(Block::parse_within)?; Ok(ExprLoop { - attrs: inner_attrs, + attrs: private::attrs(outer_attrs, inner_attrs), label, loop_token, body: Block { brace_token, stmts }, @@ -2095,10 +2183,12 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ExprMatch { fn parse(input: ParseStream) -> Result<Self> { + let outer_attrs = input.call(Attribute::parse_outer)?; let match_token: Token![match] = input.parse()?; - let expr = expr_no_struct(input)?; + let expr = Expr::parse_without_eager_brace(input)?; let content; let brace_token = braced!(content in input); @@ -2110,7 +2200,7 @@ pub(crate) mod parsing { } Ok(ExprMatch { - attrs: inner_attrs, + attrs: private::attrs(outer_attrs, inner_attrs), match_token, expr: Box::new(expr), brace_token, @@ -2127,6 +2217,7 @@ pub(crate) mod parsing { ) => { $( #[cfg(all(feature = "full", feature = "printing"))] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for $expr_type { fn parse(input: ParseStream) -> Result<Self> { let mut expr: Expr = input.parse()?; @@ -2144,63 +2235,139 @@ pub(crate) mod parsing { } impl_by_parsing_expr! { - ExprBox, Box, "expected box expression", - ExprArray, Array, "expected slice literal expression", ExprCall, Call, "expected function call expression", ExprMethodCall, MethodCall, "expected method call expression", ExprTuple, Tuple, "expected tuple expression", ExprBinary, Binary, "expected binary operation", - ExprUnary, Unary, "expected unary operation", ExprCast, Cast, "expected cast expression", ExprType, Type, "expected type ascription expression", - ExprLet, Let, "expected let guard", - ExprClosure, Closure, "expected closure expression", - ExprUnsafe, Unsafe, "expected unsafe block", - ExprBlock, Block, "expected blocked scope", ExprAssign, Assign, "expected assignment expression", ExprAssignOp, AssignOp, "expected compound assignment expression", ExprField, Field, "expected struct field access", ExprIndex, Index, "expected indexing expression", ExprRange, Range, "expected range expression", - ExprReference, Reference, "expected referencing operation", - ExprBreak, Break, "expected break expression", - ExprContinue, Continue, "expected continue expression", - ExprReturn, Return, "expected return expression", - ExprMacro, Macro, "expected macro invocation expression", - ExprStruct, Struct, "expected struct literal expression", - ExprRepeat, Repeat, "expected array literal constructed from one repeated element", - ExprParen, Paren, "expected parenthesized expression", ExprTry, Try, "expected try expression", - ExprAsync, Async, "expected async block", - ExprTryBlock, TryBlock, "expected try block", - ExprYield, Yield, "expected yield expression", } #[cfg(feature = "full")] - fn expr_try_block(input: ParseStream) -> Result<ExprTryBlock> { - Ok(ExprTryBlock { - attrs: Vec::new(), - try_token: input.parse()?, - block: input.parse()?, + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprBox { + fn parse(input: ParseStream) -> Result<Self> { + let attrs = Vec::new(); + let allow_struct = AllowStruct(true); + expr_box(input, attrs, allow_struct) + } + } + + #[cfg(feature = "full")] + fn expr_box( + input: ParseStream, + attrs: Vec<Attribute>, + allow_struct: AllowStruct, + ) -> Result<ExprBox> { + Ok(ExprBox { + attrs, + box_token: input.parse()?, + expr: Box::new(unary_expr(input, allow_struct)?), }) } #[cfg(feature = "full")] - fn expr_yield(input: ParseStream) -> Result<ExprYield> { - Ok(ExprYield { - attrs: Vec::new(), - yield_token: input.parse()?, - expr: { - if !input.is_empty() && !input.peek(Token![,]) && !input.peek(Token![;]) { - Some(input.parse()?) - } else { - None - } - }, + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprUnary { + fn parse(input: ParseStream) -> Result<Self> { + let attrs = Vec::new(); + let allow_struct = AllowStruct(true); + expr_unary(input, attrs, allow_struct) + } + } + + #[cfg(feature = "full")] + fn expr_unary( + input: ParseStream, + attrs: Vec<Attribute>, + allow_struct: AllowStruct, + ) -> Result<ExprUnary> { + Ok(ExprUnary { + attrs, + op: input.parse()?, + expr: Box::new(unary_expr(input, allow_struct)?), }) } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprClosure { + fn parse(input: ParseStream) -> Result<Self> { + let allow_struct = AllowStruct(true); + expr_closure(input, allow_struct) + } + } + + #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprReference { + fn parse(input: ParseStream) -> Result<Self> { + let allow_struct = AllowStruct(true); + Ok(ExprReference { + attrs: Vec::new(), + and_token: input.parse()?, + raw: Reserved::default(), + mutability: input.parse()?, + expr: Box::new(unary_expr(input, allow_struct)?), + }) + } + } + + #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprBreak { + fn parse(input: ParseStream) -> Result<Self> { + let allow_struct = AllowStruct(true); + expr_break(input, allow_struct) + } + } + + #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprReturn { + fn parse(input: ParseStream) -> Result<Self> { + let allow_struct = AllowStruct(true); + expr_ret(input, allow_struct) + } + } + + #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprTryBlock { + fn parse(input: ParseStream) -> Result<Self> { + Ok(ExprTryBlock { + attrs: Vec::new(), + try_token: input.parse()?, + block: input.parse()?, + }) + } + } + + #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprYield { + fn parse(input: ParseStream) -> Result<Self> { + Ok(ExprYield { + attrs: Vec::new(), + yield_token: input.parse()?, + expr: { + if !input.is_empty() && !input.peek(Token![,]) && !input.peek(Token![;]) { + Some(input.parse()?) + } else { + None + } + }, + }) + } + } + + #[cfg(feature = "full")] fn expr_closure(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprClosure> { let asyncness: Option<Token![async]> = input.parse()?; let movability: Option<Token![static]> = if asyncness.is_none() { @@ -2257,13 +2424,16 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] - fn expr_async(input: ParseStream) -> Result<ExprAsync> { - Ok(ExprAsync { - attrs: Vec::new(), - async_token: input.parse()?, - capture: input.parse()?, - block: input.parse()?, - }) + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprAsync { + fn parse(input: ParseStream) -> Result<Self> { + Ok(ExprAsync { + attrs: Vec::new(), + async_token: input.parse()?, + capture: input.parse()?, + block: input.parse()?, + }) + } } #[cfg(feature = "full")] @@ -2296,18 +2466,24 @@ pub(crate) mod parsing { Pat::Type(_) => unreachable!(), Pat::Verbatim(_) => {} Pat::Wild(pat) => pat.attrs = attrs, - Pat::__Nonexhaustive => unreachable!(), + + #[cfg(test)] + Pat::__TestExhaustive(_) => unimplemented!(), + #[cfg(not(test))] + _ => unreachable!(), } Ok(pat) } } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ExprWhile { fn parse(input: ParseStream) -> Result<Self> { + let outer_attrs = input.call(Attribute::parse_outer)?; let label: Option<Label> = input.parse()?; let while_token: Token![while] = input.parse()?; - let cond = expr_no_struct(input)?; + let cond = Expr::parse_without_eager_brace(input)?; let content; let brace_token = braced!(content in input); @@ -2315,7 +2491,7 @@ pub(crate) mod parsing { let stmts = content.call(Block::parse_within)?; Ok(ExprWhile { - attrs: inner_attrs, + attrs: private::attrs(outer_attrs, inner_attrs), label, while_token, cond: Box::new(cond), @@ -2325,6 +2501,7 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Label { fn parse(input: ParseStream) -> Result<Self> { Ok(Label { @@ -2335,6 +2512,7 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Option<Label> { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Lifetime) { @@ -2346,12 +2524,15 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] - fn expr_continue(input: ParseStream) -> Result<ExprContinue> { - Ok(ExprContinue { - attrs: Vec::new(), - continue_token: input.parse()?, - label: input.parse()?, - }) + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprContinue { + fn parse(input: ParseStream) -> Result<Self> { + Ok(ExprContinue { + attrs: Vec::new(), + continue_token: input.parse()?, + label: input.parse()?, + }) + } } #[cfg(feature = "full")] @@ -2397,8 +2578,10 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for FieldValue { fn parse(input: ParseStream) -> Result<Self> { + let attrs = input.call(Attribute::parse_outer)?; let member: Member = input.parse()?; let (colon_token, value) = if input.peek(Token![:]) || !member.is_named() { let colon_token: Token![:] = input.parse()?; @@ -2416,7 +2599,7 @@ pub(crate) mod parsing { }; Ok(FieldValue { - attrs: Vec::new(), + attrs, member, colon_token, expr: value, @@ -2425,6 +2608,16 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprStruct { + fn parse(input: ParseStream) -> Result<Self> { + let attrs = Vec::new(); + let path: Path = input.parse()?; + expr_struct_helper(input, attrs, path) + } + } + + #[cfg(feature = "full")] fn expr_struct_helper( input: ParseStream, outer_attrs: Vec<Attribute>, @@ -2433,79 +2626,93 @@ pub(crate) mod parsing { let content; let brace_token = braced!(content in input); let inner_attrs = content.call(Attribute::parse_inner)?; + let attrs = private::attrs(outer_attrs, inner_attrs); let mut fields = Punctuated::new(); - loop { - let attrs = content.call(Attribute::parse_outer)?; - // TODO: optimize using advance_to - if content.fork().parse::<Member>().is_err() { - if attrs.is_empty() { - break; - } else { - return Err(content.error("expected struct field")); - } + while !content.is_empty() { + if content.peek(Token![..]) { + return Ok(ExprStruct { + attrs, + brace_token, + path, + fields, + dot2_token: Some(content.parse()?), + rest: if content.is_empty() { + None + } else { + Some(Box::new(content.parse()?)) + }, + }); } - fields.push(FieldValue { - attrs, - ..content.parse()? - }); - - if !content.peek(Token![,]) { + fields.push(content.parse()?); + if content.is_empty() { break; } let punct: Token![,] = content.parse()?; fields.push_punct(punct); } - let (dot2_token, rest) = if fields.empty_or_trailing() && content.peek(Token![..]) { - let dot2_token: Token![..] = content.parse()?; - let rest: Expr = content.parse()?; - (Some(dot2_token), Some(Box::new(rest))) - } else { - (None, None) - }; - Ok(ExprStruct { - attrs: private::attrs(outer_attrs, inner_attrs), + attrs, brace_token, path, fields, - dot2_token, - rest, + dot2_token: None, + rest: None, }) } #[cfg(feature = "full")] - fn expr_unsafe(input: ParseStream) -> Result<ExprUnsafe> { - let unsafe_token: Token![unsafe] = input.parse()?; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprUnsafe { + fn parse(input: ParseStream) -> Result<Self> { + let unsafe_token: Token![unsafe] = input.parse()?; - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; + let content; + let brace_token = braced!(content in input); + let inner_attrs = content.call(Attribute::parse_inner)?; + let stmts = content.call(Block::parse_within)?; - Ok(ExprUnsafe { - attrs: inner_attrs, - unsafe_token, - block: Block { brace_token, stmts }, - }) + Ok(ExprUnsafe { + attrs: inner_attrs, + unsafe_token, + block: Block { brace_token, stmts }, + }) + } } #[cfg(feature = "full")] - pub fn expr_block(input: ParseStream) -> Result<ExprBlock> { - let label: Option<Label> = input.parse()?; + pub(crate) fn expr_const(input: ParseStream) -> Result<TokenStream> { + let begin = input.fork(); + input.parse::<Token![const]>()?; let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; + braced!(content in input); + content.call(Attribute::parse_inner)?; + content.call(Block::parse_within)?; - Ok(ExprBlock { - attrs: inner_attrs, - label, - block: Block { brace_token, stmts }, - }) + Ok(verbatim::between(begin, input)) + } + + #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ExprBlock { + fn parse(input: ParseStream) -> Result<Self> { + let outer_attrs = input.call(Attribute::parse_outer)?; + let label: Option<Label> = input.parse()?; + + let content; + let brace_token = braced!(content in input); + let inner_attrs = content.call(Attribute::parse_inner)?; + let stmts = content.call(Block::parse_within)?; + + Ok(ExprBlock { + attrs: private::attrs(outer_attrs, inner_attrs), + label, + block: Block { brace_token, stmts }, + }) + } } #[cfg(feature = "full")] @@ -2530,6 +2737,7 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for RangeLimits { fn parse(input: ParseStream) -> Result<Self> { let lookahead = input.lookahead1(); @@ -2546,6 +2754,7 @@ pub(crate) mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ExprPath { fn parse(input: ParseStream) -> Result<Self> { #[cfg(not(feature = "full"))] @@ -2559,6 +2768,7 @@ pub(crate) mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Member { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Ident) { @@ -2572,32 +2782,13 @@ pub(crate) mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Arm { fn parse(input: ParseStream) -> Result<Arm> { let requires_comma; Ok(Arm { attrs: input.call(Attribute::parse_outer)?, - pat: { - let leading_vert: Option<Token![|]> = input.parse()?; - let pat: Pat = input.parse()?; - if leading_vert.is_some() || input.peek(Token![|]) { - let mut cases = Punctuated::new(); - cases.push_value(pat); - while input.peek(Token![|]) { - let punct = input.parse()?; - cases.push_punct(punct); - let pat: Pat = input.parse()?; - cases.push_value(pat); - } - Pat::Or(PatOr { - attrs: Vec::new(), - leading_vert, - cases, - }) - } else { - pat - } - }, + pat: pat::parsing::multi_pat_with_leading_vert(input)?, guard: { if input.peek(Token![if]) { let if_token: Token![if] = input.parse()?; @@ -2624,6 +2815,7 @@ pub(crate) mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Index { fn parse(input: ParseStream) -> Result<Self> { let lit: LitInt = input.parse()?; @@ -2641,6 +2833,26 @@ pub(crate) mod parsing { } } + fn multi_index(e: &mut Expr, dot_token: &mut Token![.], float: LitFloat) -> Result<bool> { + let mut float_repr = float.to_string(); + let trailing_dot = float_repr.ends_with('.'); + if trailing_dot { + float_repr.truncate(float_repr.len() - 1); + } + for part in float_repr.split('.') { + let index = crate::parse_str(part).map_err(|err| Error::new(float.span(), err))?; + let base = mem::replace(e, Expr::__TestExhaustive(crate::private(()))); + *e = Expr::Field(ExprField { + attrs: Vec::new(), + base: Box::new(base), + dot_token: Token![.](dot_token.span), + member: Member::Unnamed(index), + }); + *dot_token = Token![.](float.span()); + } + Ok(!trailing_dot) + } + #[cfg(feature = "full")] impl Member { fn is_named(&self) -> bool { @@ -2655,14 +2867,10 @@ pub(crate) mod parsing { #[cfg(feature = "printing")] pub(crate) mod printing { use super::*; - - use proc_macro2::{Literal, TokenStream}; - use quote::{ToTokens, TokenStreamExt}; - #[cfg(feature = "full")] use crate::attr::FilterAttrs; - #[cfg(feature = "full")] - use crate::print::TokensOrDefault; + use proc_macro2::{Literal, TokenStream}; + use quote::{ToTokens, TokenStreamExt}; // If the given expression is a bare `ExprStruct`, wraps it in parenthesis // before appending it to `TokenStream`. @@ -2694,6 +2902,7 @@ pub(crate) mod printing { fn inner_attrs_to_tokens(_attrs: &[Attribute], _tokens: &mut TokenStream) {} #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprBox { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2703,6 +2912,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprArray { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2713,6 +2923,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprCall { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2724,6 +2935,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprMethodCall { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2738,6 +2950,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for MethodTurbofish { fn to_tokens(&self, tokens: &mut TokenStream) { self.colon2_token.to_tokens(tokens); @@ -2748,6 +2961,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for GenericMethodArgument { fn to_tokens(&self, tokens: &mut TokenStream) { match self { @@ -2758,6 +2972,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprTuple { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2773,6 +2988,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprBinary { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2782,6 +2998,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprUnary { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2790,6 +3007,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprLit { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2797,6 +3015,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprCast { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2807,6 +3026,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprType { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2837,6 +3057,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprLet { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2848,6 +3069,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprIf { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2859,6 +3081,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprWhile { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2873,6 +3096,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprForLoop { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2889,6 +3113,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprLoop { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2902,6 +3127,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprMatch { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2923,6 +3149,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprAsync { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2933,6 +3160,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprAwait { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2943,6 +3171,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprTryBlock { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2952,6 +3181,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprYield { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2961,6 +3191,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprClosure { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2976,6 +3207,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprUnsafe { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -2988,6 +3220,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprBlock { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3000,6 +3233,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprAssign { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3010,6 +3244,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprAssignOp { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3019,6 +3254,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprField { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3028,6 +3264,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Member { fn to_tokens(&self, tokens: &mut TokenStream) { match self { @@ -3037,6 +3274,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Index { fn to_tokens(&self, tokens: &mut TokenStream) { let mut lit = Literal::i64_unsuffixed(i64::from(self.index)); @@ -3045,6 +3283,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprIndex { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3056,6 +3295,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprRange { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3068,6 +3308,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprPath { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3076,6 +3317,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprReference { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3086,6 +3328,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprBreak { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3096,6 +3339,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprContinue { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3105,6 +3349,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprReturn { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3114,6 +3359,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprMacro { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3122,6 +3368,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprStruct { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3129,15 +3376,18 @@ pub(crate) mod printing { self.brace_token.surround(tokens, |tokens| { inner_attrs_to_tokens(&self.attrs, tokens); self.fields.to_tokens(tokens); - if self.rest.is_some() { - TokensOrDefault(&self.dot2_token).to_tokens(tokens); - self.rest.to_tokens(tokens); + if let Some(dot2_token) = &self.dot2_token { + dot2_token.to_tokens(tokens); + } else if self.rest.is_some() { + Token![..](Span::call_site()).to_tokens(tokens); } + self.rest.to_tokens(tokens); }) } } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprRepeat { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3151,6 +3401,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprGroup { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3160,6 +3411,7 @@ pub(crate) mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprParen { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3171,6 +3423,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprTry { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3180,6 +3433,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Label { fn to_tokens(&self, tokens: &mut TokenStream) { self.name.to_tokens(tokens); @@ -3188,6 +3442,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for FieldValue { fn to_tokens(&self, tokens: &mut TokenStream) { outer_attrs_to_tokens(&self.attrs, tokens); @@ -3200,6 +3455,7 @@ pub(crate) mod printing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Arm { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(&self.attrs); diff --git a/1.0.7/src/ext.rs b/src/ext.rs index d09577a2..98d5550f 100644 --- a/1.0.7/src/ext.rs +++ b/src/ext.rs @@ -1,22 +1,20 @@ //! Extension traits to provide parsing methods on foreign types. //! -//! *This module is available if Syn is built with the `"parsing"` feature.* - -use proc_macro2::Ident; - -use crate::parse::{ParseStream, Result}; +//! *This module is available only if Syn is built with the `"parsing"` feature.* use crate::buffer::Cursor; use crate::parse::Peek; +use crate::parse::{ParseStream, Result}; use crate::sealed::lookahead; use crate::token::CustomToken; +use proc_macro2::Ident; /// Additional methods for `Ident` not provided by proc-macro2 or libproc_macro. /// /// This trait is sealed and cannot be implemented for types outside of Syn. It /// is implemented only for `proc_macro2::Ident`. /// -/// *This trait is available if Syn is built with the `"parsing"` feature.* +/// *This trait is available only if Syn is built with the `"parsing"` feature.* pub trait IdentExt: Sized + private::Sealed { /// Parses any identifier including keywords. /// @@ -129,7 +127,13 @@ mod private { impl Sealed for Ident {} - #[derive(Copy, Clone)] pub struct PeekFn; pub struct IdentAny; + + impl Copy for PeekFn {} + impl Clone for PeekFn { + fn clone(&self) -> Self { + *self + } + } } diff --git a/1.0.7/src/file.rs b/src/file.rs index 88c02fe8..280484f9 100644 --- a/1.0.7/src/file.rs +++ b/src/file.rs @@ -3,7 +3,7 @@ use super::*; ast_struct! { /// A complete file of Rust source code. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* /// /// # Example /// @@ -37,6 +37,8 @@ ast_struct! { /// file.read_to_string(&mut src).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. /// println!("{:#?}", syntax); /// } /// ``` @@ -49,24 +51,33 @@ ast_struct! { /// shebang: None, /// attrs: [], /// items: [ - /// ExternCrate( - /// ItemExternCrate { + /// Use( + /// ItemUse { /// attrs: [], /// vis: Inherited, - /// extern_token: Extern, - /// crate_token: Crate, - /// ident: Ident { - /// term: Term( - /// "syn" - /// ), - /// span: Span - /// }, - /// rename: None, - /// semi_token: Semi - /// } + /// use_token: Use, + /// leading_colon: None, + /// tree: Path( + /// UsePath { + /// ident: Ident( + /// std, + /// ), + /// colon2_token: Colon2, + /// tree: Name( + /// UseName { + /// ident: Ident( + /// env, + /// ), + /// }, + /// ), + /// }, + /// ), + /// semi_token: Semi, + /// }, /// ), /// ... /// ``` + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct File { pub shebang: Option<String>, pub attrs: Vec<Attribute>, @@ -77,9 +88,9 @@ ast_struct! { #[cfg(feature = "parsing")] pub mod parsing { use super::*; - use crate::parse::{Parse, ParseStream, Result}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for File { fn parse(input: ParseStream) -> Result<Self> { Ok(File { @@ -104,6 +115,7 @@ mod printing { use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for File { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.inner()); diff --git a/src/gen/clone.rs b/src/gen/clone.rs new file mode 100644 index 00000000..37670f22 --- /dev/null +++ b/src/gen/clone.rs @@ -0,0 +1,2234 @@ +// This file is @generated by syn-internal-codegen. +// It is not intended for manual editing. + +#![allow(clippy::clone_on_copy, clippy::expl_impl_clone_on_copy)] +use crate::*; +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Abi { + fn clone(&self) -> Self { + Abi { + extern_token: self.extern_token.clone(), + name: self.name.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for AngleBracketedGenericArguments { + fn clone(&self) -> Self { + AngleBracketedGenericArguments { + colon2_token: self.colon2_token.clone(), + lt_token: self.lt_token.clone(), + args: self.args.clone(), + gt_token: self.gt_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Arm { + fn clone(&self) -> Self { + Arm { + attrs: self.attrs.clone(), + pat: self.pat.clone(), + guard: self.guard.clone(), + fat_arrow_token: self.fat_arrow_token.clone(), + body: self.body.clone(), + comma: self.comma.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Copy for AttrStyle {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for AttrStyle { + fn clone(&self) -> Self { + *self + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Attribute { + fn clone(&self) -> Self { + Attribute { + pound_token: self.pound_token.clone(), + style: self.style.clone(), + bracket_token: self.bracket_token.clone(), + path: self.path.clone(), + tokens: self.tokens.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for BareFnArg { + fn clone(&self) -> Self { + BareFnArg { + attrs: self.attrs.clone(), + name: self.name.clone(), + ty: self.ty.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Copy for BinOp {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for BinOp { + fn clone(&self) -> Self { + *self + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Binding { + fn clone(&self) -> Self { + Binding { + ident: self.ident.clone(), + eq_token: self.eq_token.clone(), + ty: self.ty.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Block { + fn clone(&self) -> Self { + Block { + brace_token: self.brace_token.clone(), + stmts: self.stmts.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for BoundLifetimes { + fn clone(&self) -> Self { + BoundLifetimes { + for_token: self.for_token.clone(), + lt_token: self.lt_token.clone(), + lifetimes: self.lifetimes.clone(), + gt_token: self.gt_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ConstParam { + fn clone(&self) -> Self { + ConstParam { + attrs: self.attrs.clone(), + const_token: self.const_token.clone(), + ident: self.ident.clone(), + colon_token: self.colon_token.clone(), + ty: self.ty.clone(), + eq_token: self.eq_token.clone(), + default: self.default.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Constraint { + fn clone(&self) -> Self { + Constraint { + ident: self.ident.clone(), + colon_token: self.colon_token.clone(), + bounds: self.bounds.clone(), + } + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Data { + fn clone(&self) -> Self { + match self { + Data::Struct(v0) => Data::Struct(v0.clone()), + Data::Enum(v0) => Data::Enum(v0.clone()), + Data::Union(v0) => Data::Union(v0.clone()), + } + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for DataEnum { + fn clone(&self) -> Self { + DataEnum { + enum_token: self.enum_token.clone(), + brace_token: self.brace_token.clone(), + variants: self.variants.clone(), + } + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for DataStruct { + fn clone(&self) -> Self { + DataStruct { + struct_token: self.struct_token.clone(), + fields: self.fields.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for DataUnion { + fn clone(&self) -> Self { + DataUnion { + union_token: self.union_token.clone(), + fields: self.fields.clone(), + } + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for DeriveInput { + fn clone(&self) -> Self { + DeriveInput { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + data: self.data.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Expr { + fn clone(&self) -> Self { + match self { + #[cfg(feature = "full")] + Expr::Array(v0) => Expr::Array(v0.clone()), + #[cfg(feature = "full")] + Expr::Assign(v0) => Expr::Assign(v0.clone()), + #[cfg(feature = "full")] + Expr::AssignOp(v0) => Expr::AssignOp(v0.clone()), + #[cfg(feature = "full")] + Expr::Async(v0) => Expr::Async(v0.clone()), + #[cfg(feature = "full")] + Expr::Await(v0) => Expr::Await(v0.clone()), + Expr::Binary(v0) => Expr::Binary(v0.clone()), + #[cfg(feature = "full")] + Expr::Block(v0) => Expr::Block(v0.clone()), + #[cfg(feature = "full")] + Expr::Box(v0) => Expr::Box(v0.clone()), + #[cfg(feature = "full")] + Expr::Break(v0) => Expr::Break(v0.clone()), + Expr::Call(v0) => Expr::Call(v0.clone()), + Expr::Cast(v0) => Expr::Cast(v0.clone()), + #[cfg(feature = "full")] + Expr::Closure(v0) => Expr::Closure(v0.clone()), + #[cfg(feature = "full")] + Expr::Continue(v0) => Expr::Continue(v0.clone()), + Expr::Field(v0) => Expr::Field(v0.clone()), + #[cfg(feature = "full")] + Expr::ForLoop(v0) => Expr::ForLoop(v0.clone()), + #[cfg(feature = "full")] + Expr::Group(v0) => Expr::Group(v0.clone()), + #[cfg(feature = "full")] + Expr::If(v0) => Expr::If(v0.clone()), + Expr::Index(v0) => Expr::Index(v0.clone()), + #[cfg(feature = "full")] + Expr::Let(v0) => Expr::Let(v0.clone()), + Expr::Lit(v0) => Expr::Lit(v0.clone()), + #[cfg(feature = "full")] + Expr::Loop(v0) => Expr::Loop(v0.clone()), + #[cfg(feature = "full")] + Expr::Macro(v0) => Expr::Macro(v0.clone()), + #[cfg(feature = "full")] + Expr::Match(v0) => Expr::Match(v0.clone()), + #[cfg(feature = "full")] + Expr::MethodCall(v0) => Expr::MethodCall(v0.clone()), + Expr::Paren(v0) => Expr::Paren(v0.clone()), + Expr::Path(v0) => Expr::Path(v0.clone()), + #[cfg(feature = "full")] + Expr::Range(v0) => Expr::Range(v0.clone()), + #[cfg(feature = "full")] + Expr::Reference(v0) => Expr::Reference(v0.clone()), + #[cfg(feature = "full")] + Expr::Repeat(v0) => Expr::Repeat(v0.clone()), + #[cfg(feature = "full")] + Expr::Return(v0) => Expr::Return(v0.clone()), + #[cfg(feature = "full")] + Expr::Struct(v0) => Expr::Struct(v0.clone()), + #[cfg(feature = "full")] + Expr::Try(v0) => Expr::Try(v0.clone()), + #[cfg(feature = "full")] + Expr::TryBlock(v0) => Expr::TryBlock(v0.clone()), + #[cfg(feature = "full")] + Expr::Tuple(v0) => Expr::Tuple(v0.clone()), + #[cfg(feature = "full")] + Expr::Type(v0) => Expr::Type(v0.clone()), + Expr::Unary(v0) => Expr::Unary(v0.clone()), + #[cfg(feature = "full")] + Expr::Unsafe(v0) => Expr::Unsafe(v0.clone()), + Expr::Verbatim(v0) => Expr::Verbatim(v0.clone()), + #[cfg(feature = "full")] + Expr::While(v0) => Expr::While(v0.clone()), + #[cfg(feature = "full")] + Expr::Yield(v0) => Expr::Yield(v0.clone()), + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprArray { + fn clone(&self) -> Self { + ExprArray { + attrs: self.attrs.clone(), + bracket_token: self.bracket_token.clone(), + elems: self.elems.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprAssign { + fn clone(&self) -> Self { + ExprAssign { + attrs: self.attrs.clone(), + left: self.left.clone(), + eq_token: self.eq_token.clone(), + right: self.right.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprAssignOp { + fn clone(&self) -> Self { + ExprAssignOp { + attrs: self.attrs.clone(), + left: self.left.clone(), + op: self.op.clone(), + right: self.right.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprAsync { + fn clone(&self) -> Self { + ExprAsync { + attrs: self.attrs.clone(), + async_token: self.async_token.clone(), + capture: self.capture.clone(), + block: self.block.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprAwait { + fn clone(&self) -> Self { + ExprAwait { + attrs: self.attrs.clone(), + base: self.base.clone(), + dot_token: self.dot_token.clone(), + await_token: self.await_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprBinary { + fn clone(&self) -> Self { + ExprBinary { + attrs: self.attrs.clone(), + left: self.left.clone(), + op: self.op.clone(), + right: self.right.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprBlock { + fn clone(&self) -> Self { + ExprBlock { + attrs: self.attrs.clone(), + label: self.label.clone(), + block: self.block.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprBox { + fn clone(&self) -> Self { + ExprBox { + attrs: self.attrs.clone(), + box_token: self.box_token.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprBreak { + fn clone(&self) -> Self { + ExprBreak { + attrs: self.attrs.clone(), + break_token: self.break_token.clone(), + label: self.label.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprCall { + fn clone(&self) -> Self { + ExprCall { + attrs: self.attrs.clone(), + func: self.func.clone(), + paren_token: self.paren_token.clone(), + args: self.args.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprCast { + fn clone(&self) -> Self { + ExprCast { + attrs: self.attrs.clone(), + expr: self.expr.clone(), + as_token: self.as_token.clone(), + ty: self.ty.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprClosure { + fn clone(&self) -> Self { + ExprClosure { + attrs: self.attrs.clone(), + asyncness: self.asyncness.clone(), + movability: self.movability.clone(), + capture: self.capture.clone(), + or1_token: self.or1_token.clone(), + inputs: self.inputs.clone(), + or2_token: self.or2_token.clone(), + output: self.output.clone(), + body: self.body.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprContinue { + fn clone(&self) -> Self { + ExprContinue { + attrs: self.attrs.clone(), + continue_token: self.continue_token.clone(), + label: self.label.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprField { + fn clone(&self) -> Self { + ExprField { + attrs: self.attrs.clone(), + base: self.base.clone(), + dot_token: self.dot_token.clone(), + member: self.member.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprForLoop { + fn clone(&self) -> Self { + ExprForLoop { + attrs: self.attrs.clone(), + label: self.label.clone(), + for_token: self.for_token.clone(), + pat: self.pat.clone(), + in_token: self.in_token.clone(), + expr: self.expr.clone(), + body: self.body.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprGroup { + fn clone(&self) -> Self { + ExprGroup { + attrs: self.attrs.clone(), + group_token: self.group_token.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprIf { + fn clone(&self) -> Self { + ExprIf { + attrs: self.attrs.clone(), + if_token: self.if_token.clone(), + cond: self.cond.clone(), + then_branch: self.then_branch.clone(), + else_branch: self.else_branch.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprIndex { + fn clone(&self) -> Self { + ExprIndex { + attrs: self.attrs.clone(), + expr: self.expr.clone(), + bracket_token: self.bracket_token.clone(), + index: self.index.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprLet { + fn clone(&self) -> Self { + ExprLet { + attrs: self.attrs.clone(), + let_token: self.let_token.clone(), + pat: self.pat.clone(), + eq_token: self.eq_token.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprLit { + fn clone(&self) -> Self { + ExprLit { + attrs: self.attrs.clone(), + lit: self.lit.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprLoop { + fn clone(&self) -> Self { + ExprLoop { + attrs: self.attrs.clone(), + label: self.label.clone(), + loop_token: self.loop_token.clone(), + body: self.body.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprMacro { + fn clone(&self) -> Self { + ExprMacro { + attrs: self.attrs.clone(), + mac: self.mac.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprMatch { + fn clone(&self) -> Self { + ExprMatch { + attrs: self.attrs.clone(), + match_token: self.match_token.clone(), + expr: self.expr.clone(), + brace_token: self.brace_token.clone(), + arms: self.arms.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprMethodCall { + fn clone(&self) -> Self { + ExprMethodCall { + attrs: self.attrs.clone(), + receiver: self.receiver.clone(), + dot_token: self.dot_token.clone(), + method: self.method.clone(), + turbofish: self.turbofish.clone(), + paren_token: self.paren_token.clone(), + args: self.args.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprParen { + fn clone(&self) -> Self { + ExprParen { + attrs: self.attrs.clone(), + paren_token: self.paren_token.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprPath { + fn clone(&self) -> Self { + ExprPath { + attrs: self.attrs.clone(), + qself: self.qself.clone(), + path: self.path.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprRange { + fn clone(&self) -> Self { + ExprRange { + attrs: self.attrs.clone(), + from: self.from.clone(), + limits: self.limits.clone(), + to: self.to.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprReference { + fn clone(&self) -> Self { + ExprReference { + attrs: self.attrs.clone(), + and_token: self.and_token.clone(), + raw: self.raw.clone(), + mutability: self.mutability.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprRepeat { + fn clone(&self) -> Self { + ExprRepeat { + attrs: self.attrs.clone(), + bracket_token: self.bracket_token.clone(), + expr: self.expr.clone(), + semi_token: self.semi_token.clone(), + len: self.len.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprReturn { + fn clone(&self) -> Self { + ExprReturn { + attrs: self.attrs.clone(), + return_token: self.return_token.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprStruct { + fn clone(&self) -> Self { + ExprStruct { + attrs: self.attrs.clone(), + path: self.path.clone(), + brace_token: self.brace_token.clone(), + fields: self.fields.clone(), + dot2_token: self.dot2_token.clone(), + rest: self.rest.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprTry { + fn clone(&self) -> Self { + ExprTry { + attrs: self.attrs.clone(), + expr: self.expr.clone(), + question_token: self.question_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprTryBlock { + fn clone(&self) -> Self { + ExprTryBlock { + attrs: self.attrs.clone(), + try_token: self.try_token.clone(), + block: self.block.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprTuple { + fn clone(&self) -> Self { + ExprTuple { + attrs: self.attrs.clone(), + paren_token: self.paren_token.clone(), + elems: self.elems.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprType { + fn clone(&self) -> Self { + ExprType { + attrs: self.attrs.clone(), + expr: self.expr.clone(), + colon_token: self.colon_token.clone(), + ty: self.ty.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprUnary { + fn clone(&self) -> Self { + ExprUnary { + attrs: self.attrs.clone(), + op: self.op.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprUnsafe { + fn clone(&self) -> Self { + ExprUnsafe { + attrs: self.attrs.clone(), + unsafe_token: self.unsafe_token.clone(), + block: self.block.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprWhile { + fn clone(&self) -> Self { + ExprWhile { + attrs: self.attrs.clone(), + label: self.label.clone(), + while_token: self.while_token.clone(), + cond: self.cond.clone(), + body: self.body.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ExprYield { + fn clone(&self) -> Self { + ExprYield { + attrs: self.attrs.clone(), + yield_token: self.yield_token.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Field { + fn clone(&self) -> Self { + Field { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + ident: self.ident.clone(), + colon_token: self.colon_token.clone(), + ty: self.ty.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for FieldPat { + fn clone(&self) -> Self { + FieldPat { + attrs: self.attrs.clone(), + member: self.member.clone(), + colon_token: self.colon_token.clone(), + pat: self.pat.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for FieldValue { + fn clone(&self) -> Self { + FieldValue { + attrs: self.attrs.clone(), + member: self.member.clone(), + colon_token: self.colon_token.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Fields { + fn clone(&self) -> Self { + match self { + Fields::Named(v0) => Fields::Named(v0.clone()), + Fields::Unnamed(v0) => Fields::Unnamed(v0.clone()), + Fields::Unit => Fields::Unit, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for FieldsNamed { + fn clone(&self) -> Self { + FieldsNamed { + brace_token: self.brace_token.clone(), + named: self.named.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for FieldsUnnamed { + fn clone(&self) -> Self { + FieldsUnnamed { + paren_token: self.paren_token.clone(), + unnamed: self.unnamed.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for File { + fn clone(&self) -> Self { + File { + shebang: self.shebang.clone(), + attrs: self.attrs.clone(), + items: self.items.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for FnArg { + fn clone(&self) -> Self { + match self { + FnArg::Receiver(v0) => FnArg::Receiver(v0.clone()), + FnArg::Typed(v0) => FnArg::Typed(v0.clone()), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ForeignItem { + fn clone(&self) -> Self { + match self { + ForeignItem::Fn(v0) => ForeignItem::Fn(v0.clone()), + ForeignItem::Static(v0) => ForeignItem::Static(v0.clone()), + ForeignItem::Type(v0) => ForeignItem::Type(v0.clone()), + ForeignItem::Macro(v0) => ForeignItem::Macro(v0.clone()), + ForeignItem::Verbatim(v0) => ForeignItem::Verbatim(v0.clone()), + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ForeignItemFn { + fn clone(&self) -> Self { + ForeignItemFn { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + sig: self.sig.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ForeignItemMacro { + fn clone(&self) -> Self { + ForeignItemMacro { + attrs: self.attrs.clone(), + mac: self.mac.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ForeignItemStatic { + fn clone(&self) -> Self { + ForeignItemStatic { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + static_token: self.static_token.clone(), + mutability: self.mutability.clone(), + ident: self.ident.clone(), + colon_token: self.colon_token.clone(), + ty: self.ty.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ForeignItemType { + fn clone(&self) -> Self { + ForeignItemType { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + type_token: self.type_token.clone(), + ident: self.ident.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for GenericArgument { + fn clone(&self) -> Self { + match self { + GenericArgument::Lifetime(v0) => GenericArgument::Lifetime(v0.clone()), + GenericArgument::Type(v0) => GenericArgument::Type(v0.clone()), + GenericArgument::Binding(v0) => GenericArgument::Binding(v0.clone()), + GenericArgument::Constraint(v0) => GenericArgument::Constraint(v0.clone()), + GenericArgument::Const(v0) => GenericArgument::Const(v0.clone()), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for GenericMethodArgument { + fn clone(&self) -> Self { + match self { + GenericMethodArgument::Type(v0) => GenericMethodArgument::Type(v0.clone()), + GenericMethodArgument::Const(v0) => GenericMethodArgument::Const(v0.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for GenericParam { + fn clone(&self) -> Self { + match self { + GenericParam::Type(v0) => GenericParam::Type(v0.clone()), + GenericParam::Lifetime(v0) => GenericParam::Lifetime(v0.clone()), + GenericParam::Const(v0) => GenericParam::Const(v0.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Generics { + fn clone(&self) -> Self { + Generics { + lt_token: self.lt_token.clone(), + params: self.params.clone(), + gt_token: self.gt_token.clone(), + where_clause: self.where_clause.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ImplItem { + fn clone(&self) -> Self { + match self { + ImplItem::Const(v0) => ImplItem::Const(v0.clone()), + ImplItem::Method(v0) => ImplItem::Method(v0.clone()), + ImplItem::Type(v0) => ImplItem::Type(v0.clone()), + ImplItem::Macro(v0) => ImplItem::Macro(v0.clone()), + ImplItem::Verbatim(v0) => ImplItem::Verbatim(v0.clone()), + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ImplItemConst { + fn clone(&self) -> Self { + ImplItemConst { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + defaultness: self.defaultness.clone(), + const_token: self.const_token.clone(), + ident: self.ident.clone(), + colon_token: self.colon_token.clone(), + ty: self.ty.clone(), + eq_token: self.eq_token.clone(), + expr: self.expr.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ImplItemMacro { + fn clone(&self) -> Self { + ImplItemMacro { + attrs: self.attrs.clone(), + mac: self.mac.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ImplItemMethod { + fn clone(&self) -> Self { + ImplItemMethod { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + defaultness: self.defaultness.clone(), + sig: self.sig.clone(), + block: self.block.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ImplItemType { + fn clone(&self) -> Self { + ImplItemType { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + defaultness: self.defaultness.clone(), + type_token: self.type_token.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + eq_token: self.eq_token.clone(), + ty: self.ty.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Index { + fn clone(&self) -> Self { + Index { + index: self.index.clone(), + span: self.span.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Item { + fn clone(&self) -> Self { + match self { + Item::Const(v0) => Item::Const(v0.clone()), + Item::Enum(v0) => Item::Enum(v0.clone()), + Item::ExternCrate(v0) => Item::ExternCrate(v0.clone()), + Item::Fn(v0) => Item::Fn(v0.clone()), + Item::ForeignMod(v0) => Item::ForeignMod(v0.clone()), + Item::Impl(v0) => Item::Impl(v0.clone()), + Item::Macro(v0) => Item::Macro(v0.clone()), + Item::Macro2(v0) => Item::Macro2(v0.clone()), + Item::Mod(v0) => Item::Mod(v0.clone()), + Item::Static(v0) => Item::Static(v0.clone()), + Item::Struct(v0) => Item::Struct(v0.clone()), + Item::Trait(v0) => Item::Trait(v0.clone()), + Item::TraitAlias(v0) => Item::TraitAlias(v0.clone()), + Item::Type(v0) => Item::Type(v0.clone()), + Item::Union(v0) => Item::Union(v0.clone()), + Item::Use(v0) => Item::Use(v0.clone()), + Item::Verbatim(v0) => Item::Verbatim(v0.clone()), + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemConst { + fn clone(&self) -> Self { + ItemConst { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + const_token: self.const_token.clone(), + ident: self.ident.clone(), + colon_token: self.colon_token.clone(), + ty: self.ty.clone(), + eq_token: self.eq_token.clone(), + expr: self.expr.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemEnum { + fn clone(&self) -> Self { + ItemEnum { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + enum_token: self.enum_token.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + brace_token: self.brace_token.clone(), + variants: self.variants.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemExternCrate { + fn clone(&self) -> Self { + ItemExternCrate { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + extern_token: self.extern_token.clone(), + crate_token: self.crate_token.clone(), + ident: self.ident.clone(), + rename: self.rename.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemFn { + fn clone(&self) -> Self { + ItemFn { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + sig: self.sig.clone(), + block: self.block.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemForeignMod { + fn clone(&self) -> Self { + ItemForeignMod { + attrs: self.attrs.clone(), + abi: self.abi.clone(), + brace_token: self.brace_token.clone(), + items: self.items.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemImpl { + fn clone(&self) -> Self { + ItemImpl { + attrs: self.attrs.clone(), + defaultness: self.defaultness.clone(), + unsafety: self.unsafety.clone(), + impl_token: self.impl_token.clone(), + generics: self.generics.clone(), + trait_: self.trait_.clone(), + self_ty: self.self_ty.clone(), + brace_token: self.brace_token.clone(), + items: self.items.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemMacro { + fn clone(&self) -> Self { + ItemMacro { + attrs: self.attrs.clone(), + ident: self.ident.clone(), + mac: self.mac.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemMacro2 { + fn clone(&self) -> Self { + ItemMacro2 { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + macro_token: self.macro_token.clone(), + ident: self.ident.clone(), + rules: self.rules.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemMod { + fn clone(&self) -> Self { + ItemMod { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + mod_token: self.mod_token.clone(), + ident: self.ident.clone(), + content: self.content.clone(), + semi: self.semi.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemStatic { + fn clone(&self) -> Self { + ItemStatic { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + static_token: self.static_token.clone(), + mutability: self.mutability.clone(), + ident: self.ident.clone(), + colon_token: self.colon_token.clone(), + ty: self.ty.clone(), + eq_token: self.eq_token.clone(), + expr: self.expr.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemStruct { + fn clone(&self) -> Self { + ItemStruct { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + struct_token: self.struct_token.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + fields: self.fields.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemTrait { + fn clone(&self) -> Self { + ItemTrait { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + unsafety: self.unsafety.clone(), + auto_token: self.auto_token.clone(), + trait_token: self.trait_token.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + colon_token: self.colon_token.clone(), + supertraits: self.supertraits.clone(), + brace_token: self.brace_token.clone(), + items: self.items.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemTraitAlias { + fn clone(&self) -> Self { + ItemTraitAlias { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + trait_token: self.trait_token.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + eq_token: self.eq_token.clone(), + bounds: self.bounds.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemType { + fn clone(&self) -> Self { + ItemType { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + type_token: self.type_token.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + eq_token: self.eq_token.clone(), + ty: self.ty.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemUnion { + fn clone(&self) -> Self { + ItemUnion { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + union_token: self.union_token.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + fields: self.fields.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ItemUse { + fn clone(&self) -> Self { + ItemUse { + attrs: self.attrs.clone(), + vis: self.vis.clone(), + use_token: self.use_token.clone(), + leading_colon: self.leading_colon.clone(), + tree: self.tree.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Label { + fn clone(&self) -> Self { + Label { + name: self.name.clone(), + colon_token: self.colon_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for LifetimeDef { + fn clone(&self) -> Self { + LifetimeDef { + attrs: self.attrs.clone(), + lifetime: self.lifetime.clone(), + colon_token: self.colon_token.clone(), + bounds: self.bounds.clone(), + } + } +} +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Lit { + fn clone(&self) -> Self { + match self { + Lit::Str(v0) => Lit::Str(v0.clone()), + Lit::ByteStr(v0) => Lit::ByteStr(v0.clone()), + Lit::Byte(v0) => Lit::Byte(v0.clone()), + Lit::Char(v0) => Lit::Char(v0.clone()), + Lit::Int(v0) => Lit::Int(v0.clone()), + Lit::Float(v0) => Lit::Float(v0.clone()), + Lit::Bool(v0) => Lit::Bool(v0.clone()), + Lit::Verbatim(v0) => Lit::Verbatim(v0.clone()), + } + } +} +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for LitBool { + fn clone(&self) -> Self { + LitBool { + value: self.value.clone(), + span: self.span.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Local { + fn clone(&self) -> Self { + Local { + attrs: self.attrs.clone(), + let_token: self.let_token.clone(), + pat: self.pat.clone(), + init: self.init.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Macro { + fn clone(&self) -> Self { + Macro { + path: self.path.clone(), + bang_token: self.bang_token.clone(), + delimiter: self.delimiter.clone(), + tokens: self.tokens.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for MacroDelimiter { + fn clone(&self) -> Self { + match self { + MacroDelimiter::Paren(v0) => MacroDelimiter::Paren(v0.clone()), + MacroDelimiter::Brace(v0) => MacroDelimiter::Brace(v0.clone()), + MacroDelimiter::Bracket(v0) => MacroDelimiter::Bracket(v0.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Member { + fn clone(&self) -> Self { + match self { + Member::Named(v0) => Member::Named(v0.clone()), + Member::Unnamed(v0) => Member::Unnamed(v0.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Meta { + fn clone(&self) -> Self { + match self { + Meta::Path(v0) => Meta::Path(v0.clone()), + Meta::List(v0) => Meta::List(v0.clone()), + Meta::NameValue(v0) => Meta::NameValue(v0.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for MetaList { + fn clone(&self) -> Self { + MetaList { + path: self.path.clone(), + paren_token: self.paren_token.clone(), + nested: self.nested.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for MetaNameValue { + fn clone(&self) -> Self { + MetaNameValue { + path: self.path.clone(), + eq_token: self.eq_token.clone(), + lit: self.lit.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for MethodTurbofish { + fn clone(&self) -> Self { + MethodTurbofish { + colon2_token: self.colon2_token.clone(), + lt_token: self.lt_token.clone(), + args: self.args.clone(), + gt_token: self.gt_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for NestedMeta { + fn clone(&self) -> Self { + match self { + NestedMeta::Meta(v0) => NestedMeta::Meta(v0.clone()), + NestedMeta::Lit(v0) => NestedMeta::Lit(v0.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ParenthesizedGenericArguments { + fn clone(&self) -> Self { + ParenthesizedGenericArguments { + paren_token: self.paren_token.clone(), + inputs: self.inputs.clone(), + output: self.output.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Pat { + fn clone(&self) -> Self { + match self { + Pat::Box(v0) => Pat::Box(v0.clone()), + Pat::Ident(v0) => Pat::Ident(v0.clone()), + Pat::Lit(v0) => Pat::Lit(v0.clone()), + Pat::Macro(v0) => Pat::Macro(v0.clone()), + Pat::Or(v0) => Pat::Or(v0.clone()), + Pat::Path(v0) => Pat::Path(v0.clone()), + Pat::Range(v0) => Pat::Range(v0.clone()), + Pat::Reference(v0) => Pat::Reference(v0.clone()), + Pat::Rest(v0) => Pat::Rest(v0.clone()), + Pat::Slice(v0) => Pat::Slice(v0.clone()), + Pat::Struct(v0) => Pat::Struct(v0.clone()), + Pat::Tuple(v0) => Pat::Tuple(v0.clone()), + Pat::TupleStruct(v0) => Pat::TupleStruct(v0.clone()), + Pat::Type(v0) => Pat::Type(v0.clone()), + Pat::Verbatim(v0) => Pat::Verbatim(v0.clone()), + Pat::Wild(v0) => Pat::Wild(v0.clone()), + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatBox { + fn clone(&self) -> Self { + PatBox { + attrs: self.attrs.clone(), + box_token: self.box_token.clone(), + pat: self.pat.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatIdent { + fn clone(&self) -> Self { + PatIdent { + attrs: self.attrs.clone(), + by_ref: self.by_ref.clone(), + mutability: self.mutability.clone(), + ident: self.ident.clone(), + subpat: self.subpat.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatLit { + fn clone(&self) -> Self { + PatLit { + attrs: self.attrs.clone(), + expr: self.expr.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatMacro { + fn clone(&self) -> Self { + PatMacro { + attrs: self.attrs.clone(), + mac: self.mac.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatOr { + fn clone(&self) -> Self { + PatOr { + attrs: self.attrs.clone(), + leading_vert: self.leading_vert.clone(), + cases: self.cases.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatPath { + fn clone(&self) -> Self { + PatPath { + attrs: self.attrs.clone(), + qself: self.qself.clone(), + path: self.path.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatRange { + fn clone(&self) -> Self { + PatRange { + attrs: self.attrs.clone(), + lo: self.lo.clone(), + limits: self.limits.clone(), + hi: self.hi.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatReference { + fn clone(&self) -> Self { + PatReference { + attrs: self.attrs.clone(), + and_token: self.and_token.clone(), + mutability: self.mutability.clone(), + pat: self.pat.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatRest { + fn clone(&self) -> Self { + PatRest { + attrs: self.attrs.clone(), + dot2_token: self.dot2_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatSlice { + fn clone(&self) -> Self { + PatSlice { + attrs: self.attrs.clone(), + bracket_token: self.bracket_token.clone(), + elems: self.elems.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatStruct { + fn clone(&self) -> Self { + PatStruct { + attrs: self.attrs.clone(), + path: self.path.clone(), + brace_token: self.brace_token.clone(), + fields: self.fields.clone(), + dot2_token: self.dot2_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatTuple { + fn clone(&self) -> Self { + PatTuple { + attrs: self.attrs.clone(), + paren_token: self.paren_token.clone(), + elems: self.elems.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatTupleStruct { + fn clone(&self) -> Self { + PatTupleStruct { + attrs: self.attrs.clone(), + path: self.path.clone(), + pat: self.pat.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatType { + fn clone(&self) -> Self { + PatType { + attrs: self.attrs.clone(), + pat: self.pat.clone(), + colon_token: self.colon_token.clone(), + ty: self.ty.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatWild { + fn clone(&self) -> Self { + PatWild { + attrs: self.attrs.clone(), + underscore_token: self.underscore_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Path { + fn clone(&self) -> Self { + Path { + leading_colon: self.leading_colon.clone(), + segments: self.segments.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PathArguments { + fn clone(&self) -> Self { + match self { + PathArguments::None => PathArguments::None, + PathArguments::AngleBracketed(v0) => PathArguments::AngleBracketed(v0.clone()), + PathArguments::Parenthesized(v0) => PathArguments::Parenthesized(v0.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PathSegment { + fn clone(&self) -> Self { + PathSegment { + ident: self.ident.clone(), + arguments: self.arguments.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PredicateEq { + fn clone(&self) -> Self { + PredicateEq { + lhs_ty: self.lhs_ty.clone(), + eq_token: self.eq_token.clone(), + rhs_ty: self.rhs_ty.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PredicateLifetime { + fn clone(&self) -> Self { + PredicateLifetime { + lifetime: self.lifetime.clone(), + colon_token: self.colon_token.clone(), + bounds: self.bounds.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PredicateType { + fn clone(&self) -> Self { + PredicateType { + lifetimes: self.lifetimes.clone(), + bounded_ty: self.bounded_ty.clone(), + colon_token: self.colon_token.clone(), + bounds: self.bounds.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for QSelf { + fn clone(&self) -> Self { + QSelf { + lt_token: self.lt_token.clone(), + ty: self.ty.clone(), + position: self.position.clone(), + as_token: self.as_token.clone(), + gt_token: self.gt_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Copy for RangeLimits {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for RangeLimits { + fn clone(&self) -> Self { + *self + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Receiver { + fn clone(&self) -> Self { + Receiver { + attrs: self.attrs.clone(), + reference: self.reference.clone(), + mutability: self.mutability.clone(), + self_token: self.self_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for ReturnType { + fn clone(&self) -> Self { + match self { + ReturnType::Default => ReturnType::Default, + ReturnType::Type(v0, v1) => ReturnType::Type(v0.clone(), v1.clone()), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Signature { + fn clone(&self) -> Self { + Signature { + constness: self.constness.clone(), + asyncness: self.asyncness.clone(), + unsafety: self.unsafety.clone(), + abi: self.abi.clone(), + fn_token: self.fn_token.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + paren_token: self.paren_token.clone(), + inputs: self.inputs.clone(), + variadic: self.variadic.clone(), + output: self.output.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Stmt { + fn clone(&self) -> Self { + match self { + Stmt::Local(v0) => Stmt::Local(v0.clone()), + Stmt::Item(v0) => Stmt::Item(v0.clone()), + Stmt::Expr(v0) => Stmt::Expr(v0.clone()), + Stmt::Semi(v0, v1) => Stmt::Semi(v0.clone(), v1.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TraitBound { + fn clone(&self) -> Self { + TraitBound { + paren_token: self.paren_token.clone(), + modifier: self.modifier.clone(), + lifetimes: self.lifetimes.clone(), + path: self.path.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Copy for TraitBoundModifier {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TraitBoundModifier { + fn clone(&self) -> Self { + *self + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TraitItem { + fn clone(&self) -> Self { + match self { + TraitItem::Const(v0) => TraitItem::Const(v0.clone()), + TraitItem::Method(v0) => TraitItem::Method(v0.clone()), + TraitItem::Type(v0) => TraitItem::Type(v0.clone()), + TraitItem::Macro(v0) => TraitItem::Macro(v0.clone()), + TraitItem::Verbatim(v0) => TraitItem::Verbatim(v0.clone()), + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TraitItemConst { + fn clone(&self) -> Self { + TraitItemConst { + attrs: self.attrs.clone(), + const_token: self.const_token.clone(), + ident: self.ident.clone(), + colon_token: self.colon_token.clone(), + ty: self.ty.clone(), + default: self.default.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TraitItemMacro { + fn clone(&self) -> Self { + TraitItemMacro { + attrs: self.attrs.clone(), + mac: self.mac.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TraitItemMethod { + fn clone(&self) -> Self { + TraitItemMethod { + attrs: self.attrs.clone(), + sig: self.sig.clone(), + default: self.default.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TraitItemType { + fn clone(&self) -> Self { + TraitItemType { + attrs: self.attrs.clone(), + type_token: self.type_token.clone(), + ident: self.ident.clone(), + generics: self.generics.clone(), + colon_token: self.colon_token.clone(), + bounds: self.bounds.clone(), + default: self.default.clone(), + semi_token: self.semi_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Type { + fn clone(&self) -> Self { + match self { + Type::Array(v0) => Type::Array(v0.clone()), + Type::BareFn(v0) => Type::BareFn(v0.clone()), + Type::Group(v0) => Type::Group(v0.clone()), + Type::ImplTrait(v0) => Type::ImplTrait(v0.clone()), + Type::Infer(v0) => Type::Infer(v0.clone()), + Type::Macro(v0) => Type::Macro(v0.clone()), + Type::Never(v0) => Type::Never(v0.clone()), + Type::Paren(v0) => Type::Paren(v0.clone()), + Type::Path(v0) => Type::Path(v0.clone()), + Type::Ptr(v0) => Type::Ptr(v0.clone()), + Type::Reference(v0) => Type::Reference(v0.clone()), + Type::Slice(v0) => Type::Slice(v0.clone()), + Type::TraitObject(v0) => Type::TraitObject(v0.clone()), + Type::Tuple(v0) => Type::Tuple(v0.clone()), + Type::Verbatim(v0) => Type::Verbatim(v0.clone()), + _ => unreachable!(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeArray { + fn clone(&self) -> Self { + TypeArray { + bracket_token: self.bracket_token.clone(), + elem: self.elem.clone(), + semi_token: self.semi_token.clone(), + len: self.len.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeBareFn { + fn clone(&self) -> Self { + TypeBareFn { + lifetimes: self.lifetimes.clone(), + unsafety: self.unsafety.clone(), + abi: self.abi.clone(), + fn_token: self.fn_token.clone(), + paren_token: self.paren_token.clone(), + inputs: self.inputs.clone(), + variadic: self.variadic.clone(), + output: self.output.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeGroup { + fn clone(&self) -> Self { + TypeGroup { + group_token: self.group_token.clone(), + elem: self.elem.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeImplTrait { + fn clone(&self) -> Self { + TypeImplTrait { + impl_token: self.impl_token.clone(), + bounds: self.bounds.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeInfer { + fn clone(&self) -> Self { + TypeInfer { + underscore_token: self.underscore_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeMacro { + fn clone(&self) -> Self { + TypeMacro { + mac: self.mac.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeNever { + fn clone(&self) -> Self { + TypeNever { + bang_token: self.bang_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeParam { + fn clone(&self) -> Self { + TypeParam { + attrs: self.attrs.clone(), + ident: self.ident.clone(), + colon_token: self.colon_token.clone(), + bounds: self.bounds.clone(), + eq_token: self.eq_token.clone(), + default: self.default.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeParamBound { + fn clone(&self) -> Self { + match self { + TypeParamBound::Trait(v0) => TypeParamBound::Trait(v0.clone()), + TypeParamBound::Lifetime(v0) => TypeParamBound::Lifetime(v0.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeParen { + fn clone(&self) -> Self { + TypeParen { + paren_token: self.paren_token.clone(), + elem: self.elem.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypePath { + fn clone(&self) -> Self { + TypePath { + qself: self.qself.clone(), + path: self.path.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypePtr { + fn clone(&self) -> Self { + TypePtr { + star_token: self.star_token.clone(), + const_token: self.const_token.clone(), + mutability: self.mutability.clone(), + elem: self.elem.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeReference { + fn clone(&self) -> Self { + TypeReference { + and_token: self.and_token.clone(), + lifetime: self.lifetime.clone(), + mutability: self.mutability.clone(), + elem: self.elem.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeSlice { + fn clone(&self) -> Self { + TypeSlice { + bracket_token: self.bracket_token.clone(), + elem: self.elem.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeTraitObject { + fn clone(&self) -> Self { + TypeTraitObject { + dyn_token: self.dyn_token.clone(), + bounds: self.bounds.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for TypeTuple { + fn clone(&self) -> Self { + TypeTuple { + paren_token: self.paren_token.clone(), + elems: self.elems.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Copy for UnOp {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for UnOp { + fn clone(&self) -> Self { + *self + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for UseGlob { + fn clone(&self) -> Self { + UseGlob { + star_token: self.star_token.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for UseGroup { + fn clone(&self) -> Self { + UseGroup { + brace_token: self.brace_token.clone(), + items: self.items.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for UseName { + fn clone(&self) -> Self { + UseName { + ident: self.ident.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for UsePath { + fn clone(&self) -> Self { + UsePath { + ident: self.ident.clone(), + colon2_token: self.colon2_token.clone(), + tree: self.tree.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for UseRename { + fn clone(&self) -> Self { + UseRename { + ident: self.ident.clone(), + as_token: self.as_token.clone(), + rename: self.rename.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for UseTree { + fn clone(&self) -> Self { + match self { + UseTree::Path(v0) => UseTree::Path(v0.clone()), + UseTree::Name(v0) => UseTree::Name(v0.clone()), + UseTree::Rename(v0) => UseTree::Rename(v0.clone()), + UseTree::Glob(v0) => UseTree::Glob(v0.clone()), + UseTree::Group(v0) => UseTree::Group(v0.clone()), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Variadic { + fn clone(&self) -> Self { + Variadic { + attrs: self.attrs.clone(), + dots: self.dots.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Variant { + fn clone(&self) -> Self { + Variant { + attrs: self.attrs.clone(), + ident: self.ident.clone(), + fields: self.fields.clone(), + discriminant: self.discriminant.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for VisCrate { + fn clone(&self) -> Self { + VisCrate { + crate_token: self.crate_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for VisPublic { + fn clone(&self) -> Self { + VisPublic { + pub_token: self.pub_token.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for VisRestricted { + fn clone(&self) -> Self { + VisRestricted { + pub_token: self.pub_token.clone(), + paren_token: self.paren_token.clone(), + in_token: self.in_token.clone(), + path: self.path.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Visibility { + fn clone(&self) -> Self { + match self { + Visibility::Public(v0) => Visibility::Public(v0.clone()), + Visibility::Crate(v0) => Visibility::Crate(v0.clone()), + Visibility::Restricted(v0) => Visibility::Restricted(v0.clone()), + Visibility::Inherited => Visibility::Inherited, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for WhereClause { + fn clone(&self) -> Self { + WhereClause { + where_token: self.where_token.clone(), + predicates: self.predicates.clone(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for WherePredicate { + fn clone(&self) -> Self { + match self { + WherePredicate::Type(v0) => WherePredicate::Type(v0.clone()), + WherePredicate::Lifetime(v0) => WherePredicate::Lifetime(v0.clone()), + WherePredicate::Eq(v0) => WherePredicate::Eq(v0.clone()), + } + } +} diff --git a/src/gen/debug.rs b/src/gen/debug.rs new file mode 100644 index 00000000..3efa2788 --- /dev/null +++ b/src/gen/debug.rs @@ -0,0 +1,3035 @@ +// This file is @generated by syn-internal-codegen. +// It is not intended for manual editing. + +use crate::*; +use std::fmt::{self, Debug}; +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Abi { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Abi"); + formatter.field("extern_token", &self.extern_token); + formatter.field("name", &self.name); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for AngleBracketedGenericArguments { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("AngleBracketedGenericArguments"); + formatter.field("colon2_token", &self.colon2_token); + formatter.field("lt_token", &self.lt_token); + formatter.field("args", &self.args); + formatter.field("gt_token", &self.gt_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Arm { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Arm"); + formatter.field("attrs", &self.attrs); + formatter.field("pat", &self.pat); + formatter.field("guard", &self.guard); + formatter.field("fat_arrow_token", &self.fat_arrow_token); + formatter.field("body", &self.body); + formatter.field("comma", &self.comma); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for AttrStyle { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + AttrStyle::Outer => formatter.write_str("Outer"), + AttrStyle::Inner(v0) => { + let mut formatter = formatter.debug_tuple("Inner"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Attribute { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Attribute"); + formatter.field("pound_token", &self.pound_token); + formatter.field("style", &self.style); + formatter.field("bracket_token", &self.bracket_token); + formatter.field("path", &self.path); + formatter.field("tokens", &self.tokens); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for BareFnArg { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("BareFnArg"); + formatter.field("attrs", &self.attrs); + formatter.field("name", &self.name); + formatter.field("ty", &self.ty); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for BinOp { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + BinOp::Add(v0) => { + let mut formatter = formatter.debug_tuple("Add"); + formatter.field(v0); + formatter.finish() + } + BinOp::Sub(v0) => { + let mut formatter = formatter.debug_tuple("Sub"); + formatter.field(v0); + formatter.finish() + } + BinOp::Mul(v0) => { + let mut formatter = formatter.debug_tuple("Mul"); + formatter.field(v0); + formatter.finish() + } + BinOp::Div(v0) => { + let mut formatter = formatter.debug_tuple("Div"); + formatter.field(v0); + formatter.finish() + } + BinOp::Rem(v0) => { + let mut formatter = formatter.debug_tuple("Rem"); + formatter.field(v0); + formatter.finish() + } + BinOp::And(v0) => { + let mut formatter = formatter.debug_tuple("And"); + formatter.field(v0); + formatter.finish() + } + BinOp::Or(v0) => { + let mut formatter = formatter.debug_tuple("Or"); + formatter.field(v0); + formatter.finish() + } + BinOp::BitXor(v0) => { + let mut formatter = formatter.debug_tuple("BitXor"); + formatter.field(v0); + formatter.finish() + } + BinOp::BitAnd(v0) => { + let mut formatter = formatter.debug_tuple("BitAnd"); + formatter.field(v0); + formatter.finish() + } + BinOp::BitOr(v0) => { + let mut formatter = formatter.debug_tuple("BitOr"); + formatter.field(v0); + formatter.finish() + } + BinOp::Shl(v0) => { + let mut formatter = formatter.debug_tuple("Shl"); + formatter.field(v0); + formatter.finish() + } + BinOp::Shr(v0) => { + let mut formatter = formatter.debug_tuple("Shr"); + formatter.field(v0); + formatter.finish() + } + BinOp::Eq(v0) => { + let mut formatter = formatter.debug_tuple("Eq"); + formatter.field(v0); + formatter.finish() + } + BinOp::Lt(v0) => { + let mut formatter = formatter.debug_tuple("Lt"); + formatter.field(v0); + formatter.finish() + } + BinOp::Le(v0) => { + let mut formatter = formatter.debug_tuple("Le"); + formatter.field(v0); + formatter.finish() + } + BinOp::Ne(v0) => { + let mut formatter = formatter.debug_tuple("Ne"); + formatter.field(v0); + formatter.finish() + } + BinOp::Ge(v0) => { + let mut formatter = formatter.debug_tuple("Ge"); + formatter.field(v0); + formatter.finish() + } + BinOp::Gt(v0) => { + let mut formatter = formatter.debug_tuple("Gt"); + formatter.field(v0); + formatter.finish() + } + BinOp::AddEq(v0) => { + let mut formatter = formatter.debug_tuple("AddEq"); + formatter.field(v0); + formatter.finish() + } + BinOp::SubEq(v0) => { + let mut formatter = formatter.debug_tuple("SubEq"); + formatter.field(v0); + formatter.finish() + } + BinOp::MulEq(v0) => { + let mut formatter = formatter.debug_tuple("MulEq"); + formatter.field(v0); + formatter.finish() + } + BinOp::DivEq(v0) => { + let mut formatter = formatter.debug_tuple("DivEq"); + formatter.field(v0); + formatter.finish() + } + BinOp::RemEq(v0) => { + let mut formatter = formatter.debug_tuple("RemEq"); + formatter.field(v0); + formatter.finish() + } + BinOp::BitXorEq(v0) => { + let mut formatter = formatter.debug_tuple("BitXorEq"); + formatter.field(v0); + formatter.finish() + } + BinOp::BitAndEq(v0) => { + let mut formatter = formatter.debug_tuple("BitAndEq"); + formatter.field(v0); + formatter.finish() + } + BinOp::BitOrEq(v0) => { + let mut formatter = formatter.debug_tuple("BitOrEq"); + formatter.field(v0); + formatter.finish() + } + BinOp::ShlEq(v0) => { + let mut formatter = formatter.debug_tuple("ShlEq"); + formatter.field(v0); + formatter.finish() + } + BinOp::ShrEq(v0) => { + let mut formatter = formatter.debug_tuple("ShrEq"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Binding { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Binding"); + formatter.field("ident", &self.ident); + formatter.field("eq_token", &self.eq_token); + formatter.field("ty", &self.ty); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Block { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Block"); + formatter.field("brace_token", &self.brace_token); + formatter.field("stmts", &self.stmts); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for BoundLifetimes { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("BoundLifetimes"); + formatter.field("for_token", &self.for_token); + formatter.field("lt_token", &self.lt_token); + formatter.field("lifetimes", &self.lifetimes); + formatter.field("gt_token", &self.gt_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ConstParam { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ConstParam"); + formatter.field("attrs", &self.attrs); + formatter.field("const_token", &self.const_token); + formatter.field("ident", &self.ident); + formatter.field("colon_token", &self.colon_token); + formatter.field("ty", &self.ty); + formatter.field("eq_token", &self.eq_token); + formatter.field("default", &self.default); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Constraint { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Constraint"); + formatter.field("ident", &self.ident); + formatter.field("colon_token", &self.colon_token); + formatter.field("bounds", &self.bounds); + formatter.finish() + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Data { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Data::Struct(v0) => { + let mut formatter = formatter.debug_tuple("Struct"); + formatter.field(v0); + formatter.finish() + } + Data::Enum(v0) => { + let mut formatter = formatter.debug_tuple("Enum"); + formatter.field(v0); + formatter.finish() + } + Data::Union(v0) => { + let mut formatter = formatter.debug_tuple("Union"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for DataEnum { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("DataEnum"); + formatter.field("enum_token", &self.enum_token); + formatter.field("brace_token", &self.brace_token); + formatter.field("variants", &self.variants); + formatter.finish() + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for DataStruct { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("DataStruct"); + formatter.field("struct_token", &self.struct_token); + formatter.field("fields", &self.fields); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for DataUnion { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("DataUnion"); + formatter.field("union_token", &self.union_token); + formatter.field("fields", &self.fields); + formatter.finish() + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for DeriveInput { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("DeriveInput"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("data", &self.data); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Expr { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + #[cfg(feature = "full")] + Expr::Array(v0) => { + let mut formatter = formatter.debug_tuple("Array"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Assign(v0) => { + let mut formatter = formatter.debug_tuple("Assign"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::AssignOp(v0) => { + let mut formatter = formatter.debug_tuple("AssignOp"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Async(v0) => { + let mut formatter = formatter.debug_tuple("Async"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Await(v0) => { + let mut formatter = formatter.debug_tuple("Await"); + formatter.field(v0); + formatter.finish() + } + Expr::Binary(v0) => { + let mut formatter = formatter.debug_tuple("Binary"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Block(v0) => { + let mut formatter = formatter.debug_tuple("Block"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Box(v0) => { + let mut formatter = formatter.debug_tuple("Box"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Break(v0) => { + let mut formatter = formatter.debug_tuple("Break"); + formatter.field(v0); + formatter.finish() + } + Expr::Call(v0) => { + let mut formatter = formatter.debug_tuple("Call"); + formatter.field(v0); + formatter.finish() + } + Expr::Cast(v0) => { + let mut formatter = formatter.debug_tuple("Cast"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Closure(v0) => { + let mut formatter = formatter.debug_tuple("Closure"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Continue(v0) => { + let mut formatter = formatter.debug_tuple("Continue"); + formatter.field(v0); + formatter.finish() + } + Expr::Field(v0) => { + let mut formatter = formatter.debug_tuple("Field"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::ForLoop(v0) => { + let mut formatter = formatter.debug_tuple("ForLoop"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Group(v0) => { + let mut formatter = formatter.debug_tuple("Group"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::If(v0) => { + let mut formatter = formatter.debug_tuple("If"); + formatter.field(v0); + formatter.finish() + } + Expr::Index(v0) => { + let mut formatter = formatter.debug_tuple("Index"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Let(v0) => { + let mut formatter = formatter.debug_tuple("Let"); + formatter.field(v0); + formatter.finish() + } + Expr::Lit(v0) => { + let mut formatter = formatter.debug_tuple("Lit"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Loop(v0) => { + let mut formatter = formatter.debug_tuple("Loop"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Macro(v0) => { + let mut formatter = formatter.debug_tuple("Macro"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Match(v0) => { + let mut formatter = formatter.debug_tuple("Match"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::MethodCall(v0) => { + let mut formatter = formatter.debug_tuple("MethodCall"); + formatter.field(v0); + formatter.finish() + } + Expr::Paren(v0) => { + let mut formatter = formatter.debug_tuple("Paren"); + formatter.field(v0); + formatter.finish() + } + Expr::Path(v0) => { + let mut formatter = formatter.debug_tuple("Path"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Range(v0) => { + let mut formatter = formatter.debug_tuple("Range"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Reference(v0) => { + let mut formatter = formatter.debug_tuple("Reference"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Repeat(v0) => { + let mut formatter = formatter.debug_tuple("Repeat"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Return(v0) => { + let mut formatter = formatter.debug_tuple("Return"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Struct(v0) => { + let mut formatter = formatter.debug_tuple("Struct"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Try(v0) => { + let mut formatter = formatter.debug_tuple("Try"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::TryBlock(v0) => { + let mut formatter = formatter.debug_tuple("TryBlock"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Tuple(v0) => { + let mut formatter = formatter.debug_tuple("Tuple"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + Expr::Unary(v0) => { + let mut formatter = formatter.debug_tuple("Unary"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Unsafe(v0) => { + let mut formatter = formatter.debug_tuple("Unsafe"); + formatter.field(v0); + formatter.finish() + } + Expr::Verbatim(v0) => { + let mut formatter = formatter.debug_tuple("Verbatim"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::While(v0) => { + let mut formatter = formatter.debug_tuple("While"); + formatter.field(v0); + formatter.finish() + } + #[cfg(feature = "full")] + Expr::Yield(v0) => { + let mut formatter = formatter.debug_tuple("Yield"); + formatter.field(v0); + formatter.finish() + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprArray { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprArray"); + formatter.field("attrs", &self.attrs); + formatter.field("bracket_token", &self.bracket_token); + formatter.field("elems", &self.elems); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprAssign { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprAssign"); + formatter.field("attrs", &self.attrs); + formatter.field("left", &self.left); + formatter.field("eq_token", &self.eq_token); + formatter.field("right", &self.right); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprAssignOp { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprAssignOp"); + formatter.field("attrs", &self.attrs); + formatter.field("left", &self.left); + formatter.field("op", &self.op); + formatter.field("right", &self.right); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprAsync { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprAsync"); + formatter.field("attrs", &self.attrs); + formatter.field("async_token", &self.async_token); + formatter.field("capture", &self.capture); + formatter.field("block", &self.block); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprAwait { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprAwait"); + formatter.field("attrs", &self.attrs); + formatter.field("base", &self.base); + formatter.field("dot_token", &self.dot_token); + formatter.field("await_token", &self.await_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprBinary { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprBinary"); + formatter.field("attrs", &self.attrs); + formatter.field("left", &self.left); + formatter.field("op", &self.op); + formatter.field("right", &self.right); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprBlock { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprBlock"); + formatter.field("attrs", &self.attrs); + formatter.field("label", &self.label); + formatter.field("block", &self.block); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprBox { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprBox"); + formatter.field("attrs", &self.attrs); + formatter.field("box_token", &self.box_token); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprBreak { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprBreak"); + formatter.field("attrs", &self.attrs); + formatter.field("break_token", &self.break_token); + formatter.field("label", &self.label); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprCall { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprCall"); + formatter.field("attrs", &self.attrs); + formatter.field("func", &self.func); + formatter.field("paren_token", &self.paren_token); + formatter.field("args", &self.args); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprCast { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprCast"); + formatter.field("attrs", &self.attrs); + formatter.field("expr", &self.expr); + formatter.field("as_token", &self.as_token); + formatter.field("ty", &self.ty); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprClosure { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprClosure"); + formatter.field("attrs", &self.attrs); + formatter.field("asyncness", &self.asyncness); + formatter.field("movability", &self.movability); + formatter.field("capture", &self.capture); + formatter.field("or1_token", &self.or1_token); + formatter.field("inputs", &self.inputs); + formatter.field("or2_token", &self.or2_token); + formatter.field("output", &self.output); + formatter.field("body", &self.body); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprContinue { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprContinue"); + formatter.field("attrs", &self.attrs); + formatter.field("continue_token", &self.continue_token); + formatter.field("label", &self.label); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprField { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprField"); + formatter.field("attrs", &self.attrs); + formatter.field("base", &self.base); + formatter.field("dot_token", &self.dot_token); + formatter.field("member", &self.member); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprForLoop { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprForLoop"); + formatter.field("attrs", &self.attrs); + formatter.field("label", &self.label); + formatter.field("for_token", &self.for_token); + formatter.field("pat", &self.pat); + formatter.field("in_token", &self.in_token); + formatter.field("expr", &self.expr); + formatter.field("body", &self.body); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprGroup { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprGroup"); + formatter.field("attrs", &self.attrs); + formatter.field("group_token", &self.group_token); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprIf { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprIf"); + formatter.field("attrs", &self.attrs); + formatter.field("if_token", &self.if_token); + formatter.field("cond", &self.cond); + formatter.field("then_branch", &self.then_branch); + formatter.field("else_branch", &self.else_branch); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprIndex { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprIndex"); + formatter.field("attrs", &self.attrs); + formatter.field("expr", &self.expr); + formatter.field("bracket_token", &self.bracket_token); + formatter.field("index", &self.index); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprLet { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprLet"); + formatter.field("attrs", &self.attrs); + formatter.field("let_token", &self.let_token); + formatter.field("pat", &self.pat); + formatter.field("eq_token", &self.eq_token); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprLit { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprLit"); + formatter.field("attrs", &self.attrs); + formatter.field("lit", &self.lit); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprLoop { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprLoop"); + formatter.field("attrs", &self.attrs); + formatter.field("label", &self.label); + formatter.field("loop_token", &self.loop_token); + formatter.field("body", &self.body); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprMacro { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprMacro"); + formatter.field("attrs", &self.attrs); + formatter.field("mac", &self.mac); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprMatch { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprMatch"); + formatter.field("attrs", &self.attrs); + formatter.field("match_token", &self.match_token); + formatter.field("expr", &self.expr); + formatter.field("brace_token", &self.brace_token); + formatter.field("arms", &self.arms); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprMethodCall { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprMethodCall"); + formatter.field("attrs", &self.attrs); + formatter.field("receiver", &self.receiver); + formatter.field("dot_token", &self.dot_token); + formatter.field("method", &self.method); + formatter.field("turbofish", &self.turbofish); + formatter.field("paren_token", &self.paren_token); + formatter.field("args", &self.args); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprParen { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprParen"); + formatter.field("attrs", &self.attrs); + formatter.field("paren_token", &self.paren_token); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprPath { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprPath"); + formatter.field("attrs", &self.attrs); + formatter.field("qself", &self.qself); + formatter.field("path", &self.path); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprRange { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprRange"); + formatter.field("attrs", &self.attrs); + formatter.field("from", &self.from); + formatter.field("limits", &self.limits); + formatter.field("to", &self.to); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprReference { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprReference"); + 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(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprRepeat { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprRepeat"); + formatter.field("attrs", &self.attrs); + formatter.field("bracket_token", &self.bracket_token); + formatter.field("expr", &self.expr); + formatter.field("semi_token", &self.semi_token); + formatter.field("len", &self.len); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprReturn { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprReturn"); + formatter.field("attrs", &self.attrs); + formatter.field("return_token", &self.return_token); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprStruct { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprStruct"); + formatter.field("attrs", &self.attrs); + formatter.field("path", &self.path); + formatter.field("brace_token", &self.brace_token); + formatter.field("fields", &self.fields); + formatter.field("dot2_token", &self.dot2_token); + formatter.field("rest", &self.rest); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprTry { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprTry"); + formatter.field("attrs", &self.attrs); + formatter.field("expr", &self.expr); + formatter.field("question_token", &self.question_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprTryBlock { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprTryBlock"); + formatter.field("attrs", &self.attrs); + formatter.field("try_token", &self.try_token); + formatter.field("block", &self.block); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprTuple { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprTuple"); + formatter.field("attrs", &self.attrs); + formatter.field("paren_token", &self.paren_token); + formatter.field("elems", &self.elems); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprType { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprType"); + formatter.field("attrs", &self.attrs); + formatter.field("expr", &self.expr); + formatter.field("colon_token", &self.colon_token); + formatter.field("ty", &self.ty); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprUnary { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprUnary"); + formatter.field("attrs", &self.attrs); + formatter.field("op", &self.op); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprUnsafe { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprUnsafe"); + formatter.field("attrs", &self.attrs); + formatter.field("unsafe_token", &self.unsafe_token); + formatter.field("block", &self.block); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprWhile { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprWhile"); + formatter.field("attrs", &self.attrs); + formatter.field("label", &self.label); + formatter.field("while_token", &self.while_token); + formatter.field("cond", &self.cond); + formatter.field("body", &self.body); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ExprYield { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ExprYield"); + formatter.field("attrs", &self.attrs); + formatter.field("yield_token", &self.yield_token); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Field { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Field"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("ident", &self.ident); + formatter.field("colon_token", &self.colon_token); + formatter.field("ty", &self.ty); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for FieldPat { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("FieldPat"); + formatter.field("attrs", &self.attrs); + formatter.field("member", &self.member); + formatter.field("colon_token", &self.colon_token); + formatter.field("pat", &self.pat); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for FieldValue { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("FieldValue"); + formatter.field("attrs", &self.attrs); + formatter.field("member", &self.member); + formatter.field("colon_token", &self.colon_token); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Fields { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Fields::Named(v0) => { + let mut formatter = formatter.debug_tuple("Named"); + formatter.field(v0); + formatter.finish() + } + Fields::Unnamed(v0) => { + let mut formatter = formatter.debug_tuple("Unnamed"); + formatter.field(v0); + formatter.finish() + } + Fields::Unit => formatter.write_str("Unit"), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for FieldsNamed { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("FieldsNamed"); + formatter.field("brace_token", &self.brace_token); + formatter.field("named", &self.named); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for FieldsUnnamed { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("FieldsUnnamed"); + formatter.field("paren_token", &self.paren_token); + formatter.field("unnamed", &self.unnamed); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for File { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("File"); + formatter.field("shebang", &self.shebang); + formatter.field("attrs", &self.attrs); + formatter.field("items", &self.items); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for FnArg { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + FnArg::Receiver(v0) => { + let mut formatter = formatter.debug_tuple("Receiver"); + formatter.field(v0); + formatter.finish() + } + FnArg::Typed(v0) => { + let mut formatter = formatter.debug_tuple("Typed"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ForeignItem { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + ForeignItem::Fn(v0) => { + let mut formatter = formatter.debug_tuple("Fn"); + formatter.field(v0); + formatter.finish() + } + ForeignItem::Static(v0) => { + let mut formatter = formatter.debug_tuple("Static"); + formatter.field(v0); + formatter.finish() + } + ForeignItem::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + ForeignItem::Macro(v0) => { + let mut formatter = formatter.debug_tuple("Macro"); + formatter.field(v0); + formatter.finish() + } + ForeignItem::Verbatim(v0) => { + let mut formatter = formatter.debug_tuple("Verbatim"); + formatter.field(v0); + formatter.finish() + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ForeignItemFn { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ForeignItemFn"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("sig", &self.sig); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ForeignItemMacro { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ForeignItemMacro"); + formatter.field("attrs", &self.attrs); + formatter.field("mac", &self.mac); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ForeignItemStatic { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ForeignItemStatic"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("static_token", &self.static_token); + formatter.field("mutability", &self.mutability); + formatter.field("ident", &self.ident); + formatter.field("colon_token", &self.colon_token); + formatter.field("ty", &self.ty); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ForeignItemType { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ForeignItemType"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("type_token", &self.type_token); + formatter.field("ident", &self.ident); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for GenericArgument { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + GenericArgument::Lifetime(v0) => { + let mut formatter = formatter.debug_tuple("Lifetime"); + formatter.field(v0); + formatter.finish() + } + GenericArgument::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + GenericArgument::Binding(v0) => { + let mut formatter = formatter.debug_tuple("Binding"); + formatter.field(v0); + formatter.finish() + } + GenericArgument::Constraint(v0) => { + let mut formatter = formatter.debug_tuple("Constraint"); + formatter.field(v0); + formatter.finish() + } + GenericArgument::Const(v0) => { + let mut formatter = formatter.debug_tuple("Const"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for GenericMethodArgument { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + GenericMethodArgument::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + GenericMethodArgument::Const(v0) => { + let mut formatter = formatter.debug_tuple("Const"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for GenericParam { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + GenericParam::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + GenericParam::Lifetime(v0) => { + let mut formatter = formatter.debug_tuple("Lifetime"); + formatter.field(v0); + formatter.finish() + } + GenericParam::Const(v0) => { + let mut formatter = formatter.debug_tuple("Const"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Generics { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Generics"); + formatter.field("lt_token", &self.lt_token); + formatter.field("params", &self.params); + formatter.field("gt_token", &self.gt_token); + formatter.field("where_clause", &self.where_clause); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ImplItem { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + ImplItem::Const(v0) => { + let mut formatter = formatter.debug_tuple("Const"); + formatter.field(v0); + formatter.finish() + } + ImplItem::Method(v0) => { + let mut formatter = formatter.debug_tuple("Method"); + formatter.field(v0); + formatter.finish() + } + ImplItem::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + ImplItem::Macro(v0) => { + let mut formatter = formatter.debug_tuple("Macro"); + formatter.field(v0); + formatter.finish() + } + ImplItem::Verbatim(v0) => { + let mut formatter = formatter.debug_tuple("Verbatim"); + formatter.field(v0); + formatter.finish() + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ImplItemConst { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ImplItemConst"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("defaultness", &self.defaultness); + formatter.field("const_token", &self.const_token); + formatter.field("ident", &self.ident); + formatter.field("colon_token", &self.colon_token); + formatter.field("ty", &self.ty); + formatter.field("eq_token", &self.eq_token); + formatter.field("expr", &self.expr); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ImplItemMacro { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ImplItemMacro"); + formatter.field("attrs", &self.attrs); + formatter.field("mac", &self.mac); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ImplItemMethod { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ImplItemMethod"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("defaultness", &self.defaultness); + formatter.field("sig", &self.sig); + formatter.field("block", &self.block); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ImplItemType { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ImplItemType"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("defaultness", &self.defaultness); + formatter.field("type_token", &self.type_token); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("eq_token", &self.eq_token); + formatter.field("ty", &self.ty); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Index { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Index"); + formatter.field("index", &self.index); + formatter.field("span", &self.span); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Item { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Item::Const(v0) => { + let mut formatter = formatter.debug_tuple("Const"); + formatter.field(v0); + formatter.finish() + } + Item::Enum(v0) => { + let mut formatter = formatter.debug_tuple("Enum"); + formatter.field(v0); + formatter.finish() + } + Item::ExternCrate(v0) => { + let mut formatter = formatter.debug_tuple("ExternCrate"); + formatter.field(v0); + formatter.finish() + } + Item::Fn(v0) => { + let mut formatter = formatter.debug_tuple("Fn"); + formatter.field(v0); + formatter.finish() + } + Item::ForeignMod(v0) => { + let mut formatter = formatter.debug_tuple("ForeignMod"); + formatter.field(v0); + formatter.finish() + } + Item::Impl(v0) => { + let mut formatter = formatter.debug_tuple("Impl"); + formatter.field(v0); + formatter.finish() + } + Item::Macro(v0) => { + let mut formatter = formatter.debug_tuple("Macro"); + formatter.field(v0); + formatter.finish() + } + Item::Macro2(v0) => { + let mut formatter = formatter.debug_tuple("Macro2"); + formatter.field(v0); + formatter.finish() + } + Item::Mod(v0) => { + let mut formatter = formatter.debug_tuple("Mod"); + formatter.field(v0); + formatter.finish() + } + Item::Static(v0) => { + let mut formatter = formatter.debug_tuple("Static"); + formatter.field(v0); + formatter.finish() + } + Item::Struct(v0) => { + let mut formatter = formatter.debug_tuple("Struct"); + formatter.field(v0); + formatter.finish() + } + Item::Trait(v0) => { + let mut formatter = formatter.debug_tuple("Trait"); + formatter.field(v0); + formatter.finish() + } + Item::TraitAlias(v0) => { + let mut formatter = formatter.debug_tuple("TraitAlias"); + formatter.field(v0); + formatter.finish() + } + Item::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + Item::Union(v0) => { + let mut formatter = formatter.debug_tuple("Union"); + formatter.field(v0); + formatter.finish() + } + Item::Use(v0) => { + let mut formatter = formatter.debug_tuple("Use"); + formatter.field(v0); + formatter.finish() + } + Item::Verbatim(v0) => { + let mut formatter = formatter.debug_tuple("Verbatim"); + formatter.field(v0); + formatter.finish() + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemConst { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemConst"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("const_token", &self.const_token); + formatter.field("ident", &self.ident); + formatter.field("colon_token", &self.colon_token); + formatter.field("ty", &self.ty); + formatter.field("eq_token", &self.eq_token); + formatter.field("expr", &self.expr); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemEnum { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemEnum"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("enum_token", &self.enum_token); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("brace_token", &self.brace_token); + formatter.field("variants", &self.variants); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemExternCrate { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemExternCrate"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("extern_token", &self.extern_token); + formatter.field("crate_token", &self.crate_token); + formatter.field("ident", &self.ident); + formatter.field("rename", &self.rename); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemFn { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemFn"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("sig", &self.sig); + formatter.field("block", &self.block); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemForeignMod { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemForeignMod"); + formatter.field("attrs", &self.attrs); + formatter.field("abi", &self.abi); + formatter.field("brace_token", &self.brace_token); + formatter.field("items", &self.items); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemImpl { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemImpl"); + formatter.field("attrs", &self.attrs); + formatter.field("defaultness", &self.defaultness); + formatter.field("unsafety", &self.unsafety); + formatter.field("impl_token", &self.impl_token); + formatter.field("generics", &self.generics); + formatter.field("trait_", &self.trait_); + formatter.field("self_ty", &self.self_ty); + formatter.field("brace_token", &self.brace_token); + formatter.field("items", &self.items); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemMacro { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemMacro"); + formatter.field("attrs", &self.attrs); + formatter.field("ident", &self.ident); + formatter.field("mac", &self.mac); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemMacro2 { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemMacro2"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("macro_token", &self.macro_token); + formatter.field("ident", &self.ident); + formatter.field("rules", &self.rules); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemMod { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemMod"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("mod_token", &self.mod_token); + formatter.field("ident", &self.ident); + formatter.field("content", &self.content); + formatter.field("semi", &self.semi); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemStatic { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemStatic"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("static_token", &self.static_token); + formatter.field("mutability", &self.mutability); + formatter.field("ident", &self.ident); + formatter.field("colon_token", &self.colon_token); + formatter.field("ty", &self.ty); + formatter.field("eq_token", &self.eq_token); + formatter.field("expr", &self.expr); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemStruct { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemStruct"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("struct_token", &self.struct_token); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("fields", &self.fields); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemTrait { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemTrait"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("unsafety", &self.unsafety); + formatter.field("auto_token", &self.auto_token); + formatter.field("trait_token", &self.trait_token); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("colon_token", &self.colon_token); + formatter.field("supertraits", &self.supertraits); + formatter.field("brace_token", &self.brace_token); + formatter.field("items", &self.items); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemTraitAlias { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemTraitAlias"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("trait_token", &self.trait_token); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("eq_token", &self.eq_token); + formatter.field("bounds", &self.bounds); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemType { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemType"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("type_token", &self.type_token); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("eq_token", &self.eq_token); + formatter.field("ty", &self.ty); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemUnion { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemUnion"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("union_token", &self.union_token); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("fields", &self.fields); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ItemUse { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ItemUse"); + formatter.field("attrs", &self.attrs); + formatter.field("vis", &self.vis); + formatter.field("use_token", &self.use_token); + formatter.field("leading_colon", &self.leading_colon); + formatter.field("tree", &self.tree); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Label { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Label"); + formatter.field("name", &self.name); + formatter.field("colon_token", &self.colon_token); + formatter.finish() + } +} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Lifetime { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Lifetime"); + formatter.field("apostrophe", &self.apostrophe); + formatter.field("ident", &self.ident); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for LifetimeDef { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("LifetimeDef"); + formatter.field("attrs", &self.attrs); + formatter.field("lifetime", &self.lifetime); + formatter.field("colon_token", &self.colon_token); + formatter.field("bounds", &self.bounds); + formatter.finish() + } +} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Lit { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Lit::Str(v0) => { + let mut formatter = formatter.debug_tuple("Str"); + formatter.field(v0); + formatter.finish() + } + Lit::ByteStr(v0) => { + let mut formatter = formatter.debug_tuple("ByteStr"); + formatter.field(v0); + formatter.finish() + } + Lit::Byte(v0) => { + let mut formatter = formatter.debug_tuple("Byte"); + formatter.field(v0); + formatter.finish() + } + Lit::Char(v0) => { + let mut formatter = formatter.debug_tuple("Char"); + formatter.field(v0); + formatter.finish() + } + Lit::Int(v0) => { + let mut formatter = formatter.debug_tuple("Int"); + formatter.field(v0); + formatter.finish() + } + Lit::Float(v0) => { + let mut formatter = formatter.debug_tuple("Float"); + formatter.field(v0); + formatter.finish() + } + Lit::Bool(v0) => { + let mut formatter = formatter.debug_tuple("Bool"); + formatter.field(v0); + formatter.finish() + } + Lit::Verbatim(v0) => { + let mut formatter = formatter.debug_tuple("Verbatim"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Local { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Local"); + formatter.field("attrs", &self.attrs); + formatter.field("let_token", &self.let_token); + formatter.field("pat", &self.pat); + formatter.field("init", &self.init); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Macro { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Macro"); + formatter.field("path", &self.path); + formatter.field("bang_token", &self.bang_token); + formatter.field("delimiter", &self.delimiter); + formatter.field("tokens", &self.tokens); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for MacroDelimiter { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + MacroDelimiter::Paren(v0) => { + let mut formatter = formatter.debug_tuple("Paren"); + formatter.field(v0); + formatter.finish() + } + MacroDelimiter::Brace(v0) => { + let mut formatter = formatter.debug_tuple("Brace"); + formatter.field(v0); + formatter.finish() + } + MacroDelimiter::Bracket(v0) => { + let mut formatter = formatter.debug_tuple("Bracket"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Member { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Member::Named(v0) => { + let mut formatter = formatter.debug_tuple("Named"); + formatter.field(v0); + formatter.finish() + } + Member::Unnamed(v0) => { + let mut formatter = formatter.debug_tuple("Unnamed"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Meta { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Meta::Path(v0) => { + let mut formatter = formatter.debug_tuple("Path"); + formatter.field(v0); + formatter.finish() + } + Meta::List(v0) => { + let mut formatter = formatter.debug_tuple("List"); + formatter.field(v0); + formatter.finish() + } + Meta::NameValue(v0) => { + let mut formatter = formatter.debug_tuple("NameValue"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for MetaList { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("MetaList"); + formatter.field("path", &self.path); + formatter.field("paren_token", &self.paren_token); + formatter.field("nested", &self.nested); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for MetaNameValue { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("MetaNameValue"); + formatter.field("path", &self.path); + formatter.field("eq_token", &self.eq_token); + formatter.field("lit", &self.lit); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for MethodTurbofish { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("MethodTurbofish"); + formatter.field("colon2_token", &self.colon2_token); + formatter.field("lt_token", &self.lt_token); + formatter.field("args", &self.args); + formatter.field("gt_token", &self.gt_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for NestedMeta { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + NestedMeta::Meta(v0) => { + let mut formatter = formatter.debug_tuple("Meta"); + formatter.field(v0); + formatter.finish() + } + NestedMeta::Lit(v0) => { + let mut formatter = formatter.debug_tuple("Lit"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ParenthesizedGenericArguments { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("ParenthesizedGenericArguments"); + formatter.field("paren_token", &self.paren_token); + formatter.field("inputs", &self.inputs); + formatter.field("output", &self.output); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Pat { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Pat::Box(v0) => { + let mut formatter = formatter.debug_tuple("Box"); + formatter.field(v0); + formatter.finish() + } + Pat::Ident(v0) => { + let mut formatter = formatter.debug_tuple("Ident"); + formatter.field(v0); + formatter.finish() + } + Pat::Lit(v0) => { + let mut formatter = formatter.debug_tuple("Lit"); + formatter.field(v0); + formatter.finish() + } + Pat::Macro(v0) => { + let mut formatter = formatter.debug_tuple("Macro"); + formatter.field(v0); + formatter.finish() + } + Pat::Or(v0) => { + let mut formatter = formatter.debug_tuple("Or"); + formatter.field(v0); + formatter.finish() + } + Pat::Path(v0) => { + let mut formatter = formatter.debug_tuple("Path"); + formatter.field(v0); + formatter.finish() + } + Pat::Range(v0) => { + let mut formatter = formatter.debug_tuple("Range"); + formatter.field(v0); + formatter.finish() + } + Pat::Reference(v0) => { + let mut formatter = formatter.debug_tuple("Reference"); + formatter.field(v0); + formatter.finish() + } + Pat::Rest(v0) => { + let mut formatter = formatter.debug_tuple("Rest"); + formatter.field(v0); + formatter.finish() + } + Pat::Slice(v0) => { + let mut formatter = formatter.debug_tuple("Slice"); + formatter.field(v0); + formatter.finish() + } + Pat::Struct(v0) => { + let mut formatter = formatter.debug_tuple("Struct"); + formatter.field(v0); + formatter.finish() + } + Pat::Tuple(v0) => { + let mut formatter = formatter.debug_tuple("Tuple"); + formatter.field(v0); + formatter.finish() + } + Pat::TupleStruct(v0) => { + let mut formatter = formatter.debug_tuple("TupleStruct"); + formatter.field(v0); + formatter.finish() + } + Pat::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + Pat::Verbatim(v0) => { + let mut formatter = formatter.debug_tuple("Verbatim"); + formatter.field(v0); + formatter.finish() + } + Pat::Wild(v0) => { + let mut formatter = formatter.debug_tuple("Wild"); + formatter.field(v0); + formatter.finish() + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatBox { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatBox"); + formatter.field("attrs", &self.attrs); + formatter.field("box_token", &self.box_token); + formatter.field("pat", &self.pat); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatIdent { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatIdent"); + formatter.field("attrs", &self.attrs); + formatter.field("by_ref", &self.by_ref); + formatter.field("mutability", &self.mutability); + formatter.field("ident", &self.ident); + formatter.field("subpat", &self.subpat); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatLit { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatLit"); + formatter.field("attrs", &self.attrs); + formatter.field("expr", &self.expr); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatMacro { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatMacro"); + formatter.field("attrs", &self.attrs); + formatter.field("mac", &self.mac); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatOr { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatOr"); + formatter.field("attrs", &self.attrs); + formatter.field("leading_vert", &self.leading_vert); + formatter.field("cases", &self.cases); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatPath { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatPath"); + formatter.field("attrs", &self.attrs); + formatter.field("qself", &self.qself); + formatter.field("path", &self.path); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatRange { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatRange"); + formatter.field("attrs", &self.attrs); + formatter.field("lo", &self.lo); + formatter.field("limits", &self.limits); + formatter.field("hi", &self.hi); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatReference { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatReference"); + formatter.field("attrs", &self.attrs); + formatter.field("and_token", &self.and_token); + formatter.field("mutability", &self.mutability); + formatter.field("pat", &self.pat); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatRest { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatRest"); + formatter.field("attrs", &self.attrs); + formatter.field("dot2_token", &self.dot2_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatSlice { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatSlice"); + formatter.field("attrs", &self.attrs); + formatter.field("bracket_token", &self.bracket_token); + formatter.field("elems", &self.elems); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatStruct { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatStruct"); + formatter.field("attrs", &self.attrs); + formatter.field("path", &self.path); + formatter.field("brace_token", &self.brace_token); + formatter.field("fields", &self.fields); + formatter.field("dot2_token", &self.dot2_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatTuple { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatTuple"); + formatter.field("attrs", &self.attrs); + formatter.field("paren_token", &self.paren_token); + formatter.field("elems", &self.elems); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatTupleStruct { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatTupleStruct"); + formatter.field("attrs", &self.attrs); + formatter.field("path", &self.path); + formatter.field("pat", &self.pat); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatType { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatType"); + formatter.field("attrs", &self.attrs); + formatter.field("pat", &self.pat); + formatter.field("colon_token", &self.colon_token); + formatter.field("ty", &self.ty); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatWild { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatWild"); + formatter.field("attrs", &self.attrs); + formatter.field("underscore_token", &self.underscore_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Path { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Path"); + formatter.field("leading_colon", &self.leading_colon); + formatter.field("segments", &self.segments); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PathArguments { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + PathArguments::None => formatter.write_str("None"), + PathArguments::AngleBracketed(v0) => { + let mut formatter = formatter.debug_tuple("AngleBracketed"); + formatter.field(v0); + formatter.finish() + } + PathArguments::Parenthesized(v0) => { + let mut formatter = formatter.debug_tuple("Parenthesized"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PathSegment { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PathSegment"); + formatter.field("ident", &self.ident); + formatter.field("arguments", &self.arguments); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PredicateEq { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PredicateEq"); + formatter.field("lhs_ty", &self.lhs_ty); + formatter.field("eq_token", &self.eq_token); + formatter.field("rhs_ty", &self.rhs_ty); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PredicateLifetime { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PredicateLifetime"); + formatter.field("lifetime", &self.lifetime); + formatter.field("colon_token", &self.colon_token); + formatter.field("bounds", &self.bounds); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PredicateType { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PredicateType"); + formatter.field("lifetimes", &self.lifetimes); + formatter.field("bounded_ty", &self.bounded_ty); + formatter.field("colon_token", &self.colon_token); + formatter.field("bounds", &self.bounds); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for QSelf { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("QSelf"); + formatter.field("lt_token", &self.lt_token); + formatter.field("ty", &self.ty); + formatter.field("position", &self.position); + formatter.field("as_token", &self.as_token); + formatter.field("gt_token", &self.gt_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for RangeLimits { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + RangeLimits::HalfOpen(v0) => { + let mut formatter = formatter.debug_tuple("HalfOpen"); + formatter.field(v0); + formatter.finish() + } + RangeLimits::Closed(v0) => { + let mut formatter = formatter.debug_tuple("Closed"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Receiver { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Receiver"); + formatter.field("attrs", &self.attrs); + formatter.field("reference", &self.reference); + formatter.field("mutability", &self.mutability); + formatter.field("self_token", &self.self_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for ReturnType { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + ReturnType::Default => formatter.write_str("Default"), + ReturnType::Type(v0, v1) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.field(v1); + formatter.finish() + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Signature { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Signature"); + formatter.field("constness", &self.constness); + formatter.field("asyncness", &self.asyncness); + formatter.field("unsafety", &self.unsafety); + formatter.field("abi", &self.abi); + formatter.field("fn_token", &self.fn_token); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("paren_token", &self.paren_token); + formatter.field("inputs", &self.inputs); + formatter.field("variadic", &self.variadic); + formatter.field("output", &self.output); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Stmt { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Stmt::Local(v0) => { + let mut formatter = formatter.debug_tuple("Local"); + formatter.field(v0); + formatter.finish() + } + Stmt::Item(v0) => { + let mut formatter = formatter.debug_tuple("Item"); + formatter.field(v0); + formatter.finish() + } + Stmt::Expr(v0) => { + let mut formatter = formatter.debug_tuple("Expr"); + formatter.field(v0); + formatter.finish() + } + Stmt::Semi(v0, v1) => { + let mut formatter = formatter.debug_tuple("Semi"); + formatter.field(v0); + formatter.field(v1); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TraitBound { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TraitBound"); + formatter.field("paren_token", &self.paren_token); + formatter.field("modifier", &self.modifier); + formatter.field("lifetimes", &self.lifetimes); + formatter.field("path", &self.path); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TraitBoundModifier { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + TraitBoundModifier::None => formatter.write_str("None"), + TraitBoundModifier::Maybe(v0) => { + let mut formatter = formatter.debug_tuple("Maybe"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TraitItem { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + TraitItem::Const(v0) => { + let mut formatter = formatter.debug_tuple("Const"); + formatter.field(v0); + formatter.finish() + } + TraitItem::Method(v0) => { + let mut formatter = formatter.debug_tuple("Method"); + formatter.field(v0); + formatter.finish() + } + TraitItem::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + TraitItem::Macro(v0) => { + let mut formatter = formatter.debug_tuple("Macro"); + formatter.field(v0); + formatter.finish() + } + TraitItem::Verbatim(v0) => { + let mut formatter = formatter.debug_tuple("Verbatim"); + formatter.field(v0); + formatter.finish() + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TraitItemConst { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TraitItemConst"); + formatter.field("attrs", &self.attrs); + formatter.field("const_token", &self.const_token); + formatter.field("ident", &self.ident); + formatter.field("colon_token", &self.colon_token); + formatter.field("ty", &self.ty); + formatter.field("default", &self.default); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TraitItemMacro { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TraitItemMacro"); + formatter.field("attrs", &self.attrs); + formatter.field("mac", &self.mac); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TraitItemMethod { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TraitItemMethod"); + formatter.field("attrs", &self.attrs); + formatter.field("sig", &self.sig); + formatter.field("default", &self.default); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TraitItemType { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TraitItemType"); + formatter.field("attrs", &self.attrs); + formatter.field("type_token", &self.type_token); + formatter.field("ident", &self.ident); + formatter.field("generics", &self.generics); + formatter.field("colon_token", &self.colon_token); + formatter.field("bounds", &self.bounds); + formatter.field("default", &self.default); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Type { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Type::Array(v0) => { + let mut formatter = formatter.debug_tuple("Array"); + formatter.field(v0); + formatter.finish() + } + Type::BareFn(v0) => { + let mut formatter = formatter.debug_tuple("BareFn"); + formatter.field(v0); + formatter.finish() + } + Type::Group(v0) => { + let mut formatter = formatter.debug_tuple("Group"); + formatter.field(v0); + formatter.finish() + } + Type::ImplTrait(v0) => { + let mut formatter = formatter.debug_tuple("ImplTrait"); + formatter.field(v0); + formatter.finish() + } + Type::Infer(v0) => { + let mut formatter = formatter.debug_tuple("Infer"); + formatter.field(v0); + formatter.finish() + } + Type::Macro(v0) => { + let mut formatter = formatter.debug_tuple("Macro"); + formatter.field(v0); + formatter.finish() + } + Type::Never(v0) => { + let mut formatter = formatter.debug_tuple("Never"); + formatter.field(v0); + formatter.finish() + } + Type::Paren(v0) => { + let mut formatter = formatter.debug_tuple("Paren"); + formatter.field(v0); + formatter.finish() + } + Type::Path(v0) => { + let mut formatter = formatter.debug_tuple("Path"); + formatter.field(v0); + formatter.finish() + } + Type::Ptr(v0) => { + let mut formatter = formatter.debug_tuple("Ptr"); + formatter.field(v0); + formatter.finish() + } + Type::Reference(v0) => { + let mut formatter = formatter.debug_tuple("Reference"); + formatter.field(v0); + formatter.finish() + } + Type::Slice(v0) => { + let mut formatter = formatter.debug_tuple("Slice"); + formatter.field(v0); + formatter.finish() + } + Type::TraitObject(v0) => { + let mut formatter = formatter.debug_tuple("TraitObject"); + formatter.field(v0); + formatter.finish() + } + Type::Tuple(v0) => { + let mut formatter = formatter.debug_tuple("Tuple"); + formatter.field(v0); + formatter.finish() + } + Type::Verbatim(v0) => { + let mut formatter = formatter.debug_tuple("Verbatim"); + formatter.field(v0); + formatter.finish() + } + _ => unreachable!(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeArray { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeArray"); + formatter.field("bracket_token", &self.bracket_token); + formatter.field("elem", &self.elem); + formatter.field("semi_token", &self.semi_token); + formatter.field("len", &self.len); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeBareFn { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeBareFn"); + formatter.field("lifetimes", &self.lifetimes); + formatter.field("unsafety", &self.unsafety); + formatter.field("abi", &self.abi); + formatter.field("fn_token", &self.fn_token); + formatter.field("paren_token", &self.paren_token); + formatter.field("inputs", &self.inputs); + formatter.field("variadic", &self.variadic); + formatter.field("output", &self.output); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeGroup { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeGroup"); + formatter.field("group_token", &self.group_token); + formatter.field("elem", &self.elem); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeImplTrait { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeImplTrait"); + formatter.field("impl_token", &self.impl_token); + formatter.field("bounds", &self.bounds); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeInfer { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeInfer"); + formatter.field("underscore_token", &self.underscore_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeMacro { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeMacro"); + formatter.field("mac", &self.mac); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeNever { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeNever"); + formatter.field("bang_token", &self.bang_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeParam { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeParam"); + formatter.field("attrs", &self.attrs); + formatter.field("ident", &self.ident); + formatter.field("colon_token", &self.colon_token); + formatter.field("bounds", &self.bounds); + formatter.field("eq_token", &self.eq_token); + formatter.field("default", &self.default); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeParamBound { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + TypeParamBound::Trait(v0) => { + let mut formatter = formatter.debug_tuple("Trait"); + formatter.field(v0); + formatter.finish() + } + TypeParamBound::Lifetime(v0) => { + let mut formatter = formatter.debug_tuple("Lifetime"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeParen { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeParen"); + formatter.field("paren_token", &self.paren_token); + formatter.field("elem", &self.elem); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypePath { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypePath"); + formatter.field("qself", &self.qself); + formatter.field("path", &self.path); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypePtr { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypePtr"); + formatter.field("star_token", &self.star_token); + formatter.field("const_token", &self.const_token); + formatter.field("mutability", &self.mutability); + formatter.field("elem", &self.elem); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeReference { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeReference"); + formatter.field("and_token", &self.and_token); + formatter.field("lifetime", &self.lifetime); + formatter.field("mutability", &self.mutability); + formatter.field("elem", &self.elem); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeSlice { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeSlice"); + formatter.field("bracket_token", &self.bracket_token); + formatter.field("elem", &self.elem); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeTraitObject { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeTraitObject"); + formatter.field("dyn_token", &self.dyn_token); + formatter.field("bounds", &self.bounds); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for TypeTuple { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("TypeTuple"); + formatter.field("paren_token", &self.paren_token); + formatter.field("elems", &self.elems); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for UnOp { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + UnOp::Deref(v0) => { + let mut formatter = formatter.debug_tuple("Deref"); + formatter.field(v0); + formatter.finish() + } + UnOp::Not(v0) => { + let mut formatter = formatter.debug_tuple("Not"); + formatter.field(v0); + formatter.finish() + } + UnOp::Neg(v0) => { + let mut formatter = formatter.debug_tuple("Neg"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for UseGlob { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("UseGlob"); + formatter.field("star_token", &self.star_token); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for UseGroup { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("UseGroup"); + formatter.field("brace_token", &self.brace_token); + formatter.field("items", &self.items); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for UseName { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("UseName"); + formatter.field("ident", &self.ident); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for UsePath { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("UsePath"); + formatter.field("ident", &self.ident); + formatter.field("colon2_token", &self.colon2_token); + formatter.field("tree", &self.tree); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for UseRename { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("UseRename"); + formatter.field("ident", &self.ident); + formatter.field("as_token", &self.as_token); + formatter.field("rename", &self.rename); + formatter.finish() + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for UseTree { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + UseTree::Path(v0) => { + let mut formatter = formatter.debug_tuple("Path"); + formatter.field(v0); + formatter.finish() + } + UseTree::Name(v0) => { + let mut formatter = formatter.debug_tuple("Name"); + formatter.field(v0); + formatter.finish() + } + UseTree::Rename(v0) => { + let mut formatter = formatter.debug_tuple("Rename"); + formatter.field(v0); + formatter.finish() + } + UseTree::Glob(v0) => { + let mut formatter = formatter.debug_tuple("Glob"); + formatter.field(v0); + formatter.finish() + } + UseTree::Group(v0) => { + let mut formatter = formatter.debug_tuple("Group"); + formatter.field(v0); + formatter.finish() + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Variadic { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Variadic"); + formatter.field("attrs", &self.attrs); + formatter.field("dots", &self.dots); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Variant { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Variant"); + formatter.field("attrs", &self.attrs); + formatter.field("ident", &self.ident); + formatter.field("fields", &self.fields); + formatter.field("discriminant", &self.discriminant); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for VisCrate { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("VisCrate"); + formatter.field("crate_token", &self.crate_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for VisPublic { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("VisPublic"); + formatter.field("pub_token", &self.pub_token); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for VisRestricted { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("VisRestricted"); + formatter.field("pub_token", &self.pub_token); + formatter.field("paren_token", &self.paren_token); + formatter.field("in_token", &self.in_token); + formatter.field("path", &self.path); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Visibility { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Visibility::Public(v0) => { + let mut formatter = formatter.debug_tuple("Public"); + formatter.field(v0); + formatter.finish() + } + Visibility::Crate(v0) => { + let mut formatter = formatter.debug_tuple("Crate"); + formatter.field(v0); + formatter.finish() + } + Visibility::Restricted(v0) => { + let mut formatter = formatter.debug_tuple("Restricted"); + formatter.field(v0); + formatter.finish() + } + Visibility::Inherited => formatter.write_str("Inherited"), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for WhereClause { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("WhereClause"); + formatter.field("where_token", &self.where_token); + formatter.field("predicates", &self.predicates); + formatter.finish() + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for WherePredicate { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + WherePredicate::Type(v0) => { + let mut formatter = formatter.debug_tuple("Type"); + formatter.field(v0); + formatter.finish() + } + WherePredicate::Lifetime(v0) => { + let mut formatter = formatter.debug_tuple("Lifetime"); + formatter.field(v0); + formatter.finish() + } + WherePredicate::Eq(v0) => { + let mut formatter = formatter.debug_tuple("Eq"); + formatter.field(v0); + formatter.finish() + } + } + } +} diff --git a/src/gen/eq.rs b/src/gen/eq.rs new file mode 100644 index 00000000..e6e85323 --- /dev/null +++ b/src/gen/eq.rs @@ -0,0 +1,2288 @@ +// This file is @generated by syn-internal-codegen. +// It is not intended for manual editing. + +#[cfg(any(feature = "derive", feature = "full"))] +use crate::tt::TokenStreamHelper; +use crate::*; +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Abi {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Abi { + fn eq(&self, other: &Self) -> bool { + self.name == other.name + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for AngleBracketedGenericArguments {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for AngleBracketedGenericArguments { + fn eq(&self, other: &Self) -> bool { + self.colon2_token == other.colon2_token && self.args == other.args + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Arm {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Arm { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.pat == other.pat + && self.guard == other.guard + && self.body == other.body + && self.comma == other.comma + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for AttrStyle {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for AttrStyle { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (AttrStyle::Outer, AttrStyle::Outer) => true, + (AttrStyle::Inner(_), AttrStyle::Inner(_)) => true, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Attribute {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Attribute { + fn eq(&self, other: &Self) -> bool { + self.style == other.style + && self.path == other.path + && TokenStreamHelper(&self.tokens) == TokenStreamHelper(&other.tokens) + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for BareFnArg {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for BareFnArg { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.name == other.name && self.ty == other.ty + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for BinOp {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for BinOp { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (BinOp::Add(_), BinOp::Add(_)) => true, + (BinOp::Sub(_), BinOp::Sub(_)) => true, + (BinOp::Mul(_), BinOp::Mul(_)) => true, + (BinOp::Div(_), BinOp::Div(_)) => true, + (BinOp::Rem(_), BinOp::Rem(_)) => true, + (BinOp::And(_), BinOp::And(_)) => true, + (BinOp::Or(_), BinOp::Or(_)) => true, + (BinOp::BitXor(_), BinOp::BitXor(_)) => true, + (BinOp::BitAnd(_), BinOp::BitAnd(_)) => true, + (BinOp::BitOr(_), BinOp::BitOr(_)) => true, + (BinOp::Shl(_), BinOp::Shl(_)) => true, + (BinOp::Shr(_), BinOp::Shr(_)) => true, + (BinOp::Eq(_), BinOp::Eq(_)) => true, + (BinOp::Lt(_), BinOp::Lt(_)) => true, + (BinOp::Le(_), BinOp::Le(_)) => true, + (BinOp::Ne(_), BinOp::Ne(_)) => true, + (BinOp::Ge(_), BinOp::Ge(_)) => true, + (BinOp::Gt(_), BinOp::Gt(_)) => true, + (BinOp::AddEq(_), BinOp::AddEq(_)) => true, + (BinOp::SubEq(_), BinOp::SubEq(_)) => true, + (BinOp::MulEq(_), BinOp::MulEq(_)) => true, + (BinOp::DivEq(_), BinOp::DivEq(_)) => true, + (BinOp::RemEq(_), BinOp::RemEq(_)) => true, + (BinOp::BitXorEq(_), BinOp::BitXorEq(_)) => true, + (BinOp::BitAndEq(_), BinOp::BitAndEq(_)) => true, + (BinOp::BitOrEq(_), BinOp::BitOrEq(_)) => true, + (BinOp::ShlEq(_), BinOp::ShlEq(_)) => true, + (BinOp::ShrEq(_), BinOp::ShrEq(_)) => true, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Binding {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Binding { + fn eq(&self, other: &Self) -> bool { + self.ident == other.ident && self.ty == other.ty + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Block {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Block { + fn eq(&self, other: &Self) -> bool { + self.stmts == other.stmts + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for BoundLifetimes {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for BoundLifetimes { + fn eq(&self, other: &Self) -> bool { + self.lifetimes == other.lifetimes + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ConstParam {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ConstParam { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.ident == other.ident + && self.ty == other.ty + && self.eq_token == other.eq_token + && self.default == other.default + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Constraint {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Constraint { + fn eq(&self, other: &Self) -> bool { + self.ident == other.ident && self.bounds == other.bounds + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Data {} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Data { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Data::Struct(self0), Data::Struct(other0)) => self0 == other0, + (Data::Enum(self0), Data::Enum(other0)) => self0 == other0, + (Data::Union(self0), Data::Union(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for DataEnum {} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for DataEnum { + fn eq(&self, other: &Self) -> bool { + self.variants == other.variants + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for DataStruct {} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for DataStruct { + fn eq(&self, other: &Self) -> bool { + self.fields == other.fields && self.semi_token == other.semi_token + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for DataUnion {} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for DataUnion { + fn eq(&self, other: &Self) -> bool { + self.fields == other.fields + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for DeriveInput {} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for DeriveInput { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.generics == other.generics + && self.data == other.data + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Expr {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Expr { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + #[cfg(feature = "full")] + (Expr::Array(self0), Expr::Array(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Assign(self0), Expr::Assign(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::AssignOp(self0), Expr::AssignOp(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Async(self0), Expr::Async(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Await(self0), Expr::Await(other0)) => self0 == other0, + (Expr::Binary(self0), Expr::Binary(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Block(self0), Expr::Block(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Box(self0), Expr::Box(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Break(self0), Expr::Break(other0)) => self0 == other0, + (Expr::Call(self0), Expr::Call(other0)) => self0 == other0, + (Expr::Cast(self0), Expr::Cast(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Closure(self0), Expr::Closure(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Continue(self0), Expr::Continue(other0)) => self0 == other0, + (Expr::Field(self0), Expr::Field(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::ForLoop(self0), Expr::ForLoop(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Group(self0), Expr::Group(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::If(self0), Expr::If(other0)) => self0 == other0, + (Expr::Index(self0), Expr::Index(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Let(self0), Expr::Let(other0)) => self0 == other0, + (Expr::Lit(self0), Expr::Lit(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Loop(self0), Expr::Loop(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Macro(self0), Expr::Macro(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Match(self0), Expr::Match(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::MethodCall(self0), Expr::MethodCall(other0)) => self0 == other0, + (Expr::Paren(self0), Expr::Paren(other0)) => self0 == other0, + (Expr::Path(self0), Expr::Path(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Range(self0), Expr::Range(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Reference(self0), Expr::Reference(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Repeat(self0), Expr::Repeat(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Return(self0), Expr::Return(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Struct(self0), Expr::Struct(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Try(self0), Expr::Try(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::TryBlock(self0), Expr::TryBlock(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Tuple(self0), Expr::Tuple(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Type(self0), Expr::Type(other0)) => self0 == other0, + (Expr::Unary(self0), Expr::Unary(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Unsafe(self0), Expr::Unsafe(other0)) => self0 == other0, + (Expr::Verbatim(self0), Expr::Verbatim(other0)) => { + TokenStreamHelper(self0) == TokenStreamHelper(other0) + } + #[cfg(feature = "full")] + (Expr::While(self0), Expr::While(other0)) => self0 == other0, + #[cfg(feature = "full")] + (Expr::Yield(self0), Expr::Yield(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprArray {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprArray { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.elems == other.elems + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprAssign {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprAssign { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.left == other.left && self.right == other.right + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprAssignOp {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprAssignOp { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.left == other.left + && self.op == other.op + && self.right == other.right + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprAsync {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprAsync { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.capture == other.capture && self.block == other.block + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprAwait {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprAwait { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.base == other.base + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprBinary {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprBinary { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.left == other.left + && self.op == other.op + && self.right == other.right + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprBlock {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprBlock { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.label == other.label && self.block == other.block + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprBox {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprBox { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprBreak {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprBreak { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.label == other.label && self.expr == other.expr + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprCall {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprCall { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.func == other.func && self.args == other.args + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprCast {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprCast { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr && self.ty == other.ty + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprClosure {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprClosure { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.asyncness == other.asyncness + && self.movability == other.movability + && self.capture == other.capture + && self.inputs == other.inputs + && self.output == other.output + && self.body == other.body + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprContinue {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprContinue { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.label == other.label + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprField {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprField { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.base == other.base && self.member == other.member + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprForLoop {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprForLoop { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.label == other.label + && self.pat == other.pat + && self.expr == other.expr + && self.body == other.body + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprGroup {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprGroup { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprIf {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprIf { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.cond == other.cond + && self.then_branch == other.then_branch + && self.else_branch == other.else_branch + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprIndex {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprIndex { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr && self.index == other.index + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprLet {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprLet { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.pat == other.pat && self.expr == other.expr + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprLit {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprLit { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.lit == other.lit + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprLoop {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprLoop { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.label == other.label && self.body == other.body + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprMacro {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprMacro { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.mac == other.mac + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprMatch {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprMatch { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr && self.arms == other.arms + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprMethodCall {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprMethodCall { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.receiver == other.receiver + && self.method == other.method + && self.turbofish == other.turbofish + && self.args == other.args + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprParen {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprParen { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprPath {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprPath { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.qself == other.qself && self.path == other.path + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprRange {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprRange { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.from == other.from + && self.limits == other.limits + && self.to == other.to + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprReference {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprReference { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.mutability == other.mutability && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprRepeat {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprRepeat { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr && self.len == other.len + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprReturn {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprReturn { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprStruct {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprStruct { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.path == other.path + && self.fields == other.fields + && self.dot2_token == other.dot2_token + && self.rest == other.rest + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprTry {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprTry { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprTryBlock {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprTryBlock { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.block == other.block + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprTuple {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprTuple { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.elems == other.elems + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprType {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprType { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr && self.ty == other.ty + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprUnary {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprUnary { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.op == other.op && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprUnsafe {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprUnsafe { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.block == other.block + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprWhile {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprWhile { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.label == other.label + && self.cond == other.cond + && self.body == other.body + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ExprYield {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ExprYield { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Field {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Field { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.colon_token == other.colon_token + && self.ty == other.ty + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for FieldPat {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for FieldPat { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.member == other.member + && self.colon_token == other.colon_token + && self.pat == other.pat + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for FieldValue {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for FieldValue { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.member == other.member + && self.colon_token == other.colon_token + && self.expr == other.expr + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Fields {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Fields { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Fields::Named(self0), Fields::Named(other0)) => self0 == other0, + (Fields::Unnamed(self0), Fields::Unnamed(other0)) => self0 == other0, + (Fields::Unit, Fields::Unit) => true, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for FieldsNamed {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for FieldsNamed { + fn eq(&self, other: &Self) -> bool { + self.named == other.named + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for FieldsUnnamed {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for FieldsUnnamed { + fn eq(&self, other: &Self) -> bool { + self.unnamed == other.unnamed + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for File {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for File { + fn eq(&self, other: &Self) -> bool { + self.shebang == other.shebang && self.attrs == other.attrs && self.items == other.items + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for FnArg {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for FnArg { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (FnArg::Receiver(self0), FnArg::Receiver(other0)) => self0 == other0, + (FnArg::Typed(self0), FnArg::Typed(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ForeignItem {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ForeignItem { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (ForeignItem::Fn(self0), ForeignItem::Fn(other0)) => self0 == other0, + (ForeignItem::Static(self0), ForeignItem::Static(other0)) => self0 == other0, + (ForeignItem::Type(self0), ForeignItem::Type(other0)) => self0 == other0, + (ForeignItem::Macro(self0), ForeignItem::Macro(other0)) => self0 == other0, + (ForeignItem::Verbatim(self0), ForeignItem::Verbatim(other0)) => { + TokenStreamHelper(self0) == TokenStreamHelper(other0) + } + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ForeignItemFn {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ForeignItemFn { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.vis == other.vis && self.sig == other.sig + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ForeignItemMacro {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ForeignItemMacro { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.mac == other.mac && self.semi_token == other.semi_token + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ForeignItemStatic {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ForeignItemStatic { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.mutability == other.mutability + && self.ident == other.ident + && self.ty == other.ty + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ForeignItemType {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ForeignItemType { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.vis == other.vis && self.ident == other.ident + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for GenericArgument {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for GenericArgument { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (GenericArgument::Lifetime(self0), GenericArgument::Lifetime(other0)) => { + self0 == other0 + } + (GenericArgument::Type(self0), GenericArgument::Type(other0)) => self0 == other0, + (GenericArgument::Binding(self0), GenericArgument::Binding(other0)) => self0 == other0, + (GenericArgument::Constraint(self0), GenericArgument::Constraint(other0)) => { + self0 == other0 + } + (GenericArgument::Const(self0), GenericArgument::Const(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for GenericMethodArgument {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for GenericMethodArgument { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (GenericMethodArgument::Type(self0), GenericMethodArgument::Type(other0)) => { + self0 == other0 + } + (GenericMethodArgument::Const(self0), GenericMethodArgument::Const(other0)) => { + self0 == other0 + } + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for GenericParam {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for GenericParam { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (GenericParam::Type(self0), GenericParam::Type(other0)) => self0 == other0, + (GenericParam::Lifetime(self0), GenericParam::Lifetime(other0)) => self0 == other0, + (GenericParam::Const(self0), GenericParam::Const(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Generics {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Generics { + fn eq(&self, other: &Self) -> bool { + self.lt_token == other.lt_token + && self.params == other.params + && self.gt_token == other.gt_token + && self.where_clause == other.where_clause + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ImplItem {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ImplItem { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (ImplItem::Const(self0), ImplItem::Const(other0)) => self0 == other0, + (ImplItem::Method(self0), ImplItem::Method(other0)) => self0 == other0, + (ImplItem::Type(self0), ImplItem::Type(other0)) => self0 == other0, + (ImplItem::Macro(self0), ImplItem::Macro(other0)) => self0 == other0, + (ImplItem::Verbatim(self0), ImplItem::Verbatim(other0)) => { + TokenStreamHelper(self0) == TokenStreamHelper(other0) + } + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ImplItemConst {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ImplItemConst { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.defaultness == other.defaultness + && self.ident == other.ident + && self.ty == other.ty + && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ImplItemMacro {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ImplItemMacro { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.mac == other.mac && self.semi_token == other.semi_token + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ImplItemMethod {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ImplItemMethod { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.defaultness == other.defaultness + && self.sig == other.sig + && self.block == other.block + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ImplItemType {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ImplItemType { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.defaultness == other.defaultness + && self.ident == other.ident + && self.generics == other.generics + && self.ty == other.ty + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Item {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Item { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Item::Const(self0), Item::Const(other0)) => self0 == other0, + (Item::Enum(self0), Item::Enum(other0)) => self0 == other0, + (Item::ExternCrate(self0), Item::ExternCrate(other0)) => self0 == other0, + (Item::Fn(self0), Item::Fn(other0)) => self0 == other0, + (Item::ForeignMod(self0), Item::ForeignMod(other0)) => self0 == other0, + (Item::Impl(self0), Item::Impl(other0)) => self0 == other0, + (Item::Macro(self0), Item::Macro(other0)) => self0 == other0, + (Item::Macro2(self0), Item::Macro2(other0)) => self0 == other0, + (Item::Mod(self0), Item::Mod(other0)) => self0 == other0, + (Item::Static(self0), Item::Static(other0)) => self0 == other0, + (Item::Struct(self0), Item::Struct(other0)) => self0 == other0, + (Item::Trait(self0), Item::Trait(other0)) => self0 == other0, + (Item::TraitAlias(self0), Item::TraitAlias(other0)) => self0 == other0, + (Item::Type(self0), Item::Type(other0)) => self0 == other0, + (Item::Union(self0), Item::Union(other0)) => self0 == other0, + (Item::Use(self0), Item::Use(other0)) => self0 == other0, + (Item::Verbatim(self0), Item::Verbatim(other0)) => { + TokenStreamHelper(self0) == TokenStreamHelper(other0) + } + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemConst {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemConst { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.ty == other.ty + && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemEnum {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemEnum { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.generics == other.generics + && self.variants == other.variants + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemExternCrate {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemExternCrate { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.rename == other.rename + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemFn {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemFn { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.sig == other.sig + && self.block == other.block + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemForeignMod {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemForeignMod { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.abi == other.abi && self.items == other.items + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemImpl {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemImpl { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.defaultness == other.defaultness + && self.unsafety == other.unsafety + && self.generics == other.generics + && self.trait_ == other.trait_ + && self.self_ty == other.self_ty + && self.items == other.items + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemMacro {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemMacro { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.ident == other.ident + && self.mac == other.mac + && self.semi_token == other.semi_token + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemMacro2 {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemMacro2 { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && TokenStreamHelper(&self.rules) == TokenStreamHelper(&other.rules) + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemMod {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemMod { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.content == other.content + && self.semi == other.semi + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemStatic {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemStatic { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.mutability == other.mutability + && self.ident == other.ident + && self.ty == other.ty + && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemStruct {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemStruct { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.generics == other.generics + && self.fields == other.fields + && self.semi_token == other.semi_token + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemTrait {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemTrait { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.unsafety == other.unsafety + && self.auto_token == other.auto_token + && self.ident == other.ident + && self.generics == other.generics + && self.colon_token == other.colon_token + && self.supertraits == other.supertraits + && self.items == other.items + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemTraitAlias {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemTraitAlias { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.generics == other.generics + && self.bounds == other.bounds + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemType {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemType { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.generics == other.generics + && self.ty == other.ty + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemUnion {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemUnion { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.ident == other.ident + && self.generics == other.generics + && self.fields == other.fields + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ItemUse {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ItemUse { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.vis == other.vis + && self.leading_colon == other.leading_colon + && self.tree == other.tree + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Label {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Label { + fn eq(&self, other: &Self) -> bool { + self.name == other.name + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for LifetimeDef {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for LifetimeDef { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.lifetime == other.lifetime + && self.colon_token == other.colon_token + && self.bounds == other.bounds + } +} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Lit {} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Lit { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Lit::Str(self0), Lit::Str(other0)) => self0 == other0, + (Lit::ByteStr(self0), Lit::ByteStr(other0)) => self0 == other0, + (Lit::Byte(self0), Lit::Byte(other0)) => self0 == other0, + (Lit::Char(self0), Lit::Char(other0)) => self0 == other0, + (Lit::Int(self0), Lit::Int(other0)) => self0 == other0, + (Lit::Float(self0), Lit::Float(other0)) => self0 == other0, + (Lit::Bool(self0), Lit::Bool(other0)) => self0 == other0, + (Lit::Verbatim(self0), Lit::Verbatim(other0)) => { + self0.to_string() == other0.to_string() + } + _ => false, + } + } +} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for LitBool {} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for LitBool { + fn eq(&self, other: &Self) -> bool { + self.value == other.value + } +} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for LitByte {} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for LitByteStr {} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for LitChar {} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for LitFloat {} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for LitInt {} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for LitStr {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Local {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Local { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.pat == other.pat && self.init == other.init + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Macro {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Macro { + fn eq(&self, other: &Self) -> bool { + self.path == other.path + && self.delimiter == other.delimiter + && TokenStreamHelper(&self.tokens) == TokenStreamHelper(&other.tokens) + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for MacroDelimiter {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for MacroDelimiter { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (MacroDelimiter::Paren(_), MacroDelimiter::Paren(_)) => true, + (MacroDelimiter::Brace(_), MacroDelimiter::Brace(_)) => true, + (MacroDelimiter::Bracket(_), MacroDelimiter::Bracket(_)) => true, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Meta {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Meta { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Meta::Path(self0), Meta::Path(other0)) => self0 == other0, + (Meta::List(self0), Meta::List(other0)) => self0 == other0, + (Meta::NameValue(self0), Meta::NameValue(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for MetaList {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for MetaList { + fn eq(&self, other: &Self) -> bool { + self.path == other.path && self.nested == other.nested + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for MetaNameValue {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for MetaNameValue { + fn eq(&self, other: &Self) -> bool { + self.path == other.path && self.lit == other.lit + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for MethodTurbofish {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for MethodTurbofish { + fn eq(&self, other: &Self) -> bool { + self.args == other.args + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for NestedMeta {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for NestedMeta { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (NestedMeta::Meta(self0), NestedMeta::Meta(other0)) => self0 == other0, + (NestedMeta::Lit(self0), NestedMeta::Lit(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ParenthesizedGenericArguments {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ParenthesizedGenericArguments { + fn eq(&self, other: &Self) -> bool { + self.inputs == other.inputs && self.output == other.output + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Pat {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Pat { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Pat::Box(self0), Pat::Box(other0)) => self0 == other0, + (Pat::Ident(self0), Pat::Ident(other0)) => self0 == other0, + (Pat::Lit(self0), Pat::Lit(other0)) => self0 == other0, + (Pat::Macro(self0), Pat::Macro(other0)) => self0 == other0, + (Pat::Or(self0), Pat::Or(other0)) => self0 == other0, + (Pat::Path(self0), Pat::Path(other0)) => self0 == other0, + (Pat::Range(self0), Pat::Range(other0)) => self0 == other0, + (Pat::Reference(self0), Pat::Reference(other0)) => self0 == other0, + (Pat::Rest(self0), Pat::Rest(other0)) => self0 == other0, + (Pat::Slice(self0), Pat::Slice(other0)) => self0 == other0, + (Pat::Struct(self0), Pat::Struct(other0)) => self0 == other0, + (Pat::Tuple(self0), Pat::Tuple(other0)) => self0 == other0, + (Pat::TupleStruct(self0), Pat::TupleStruct(other0)) => self0 == other0, + (Pat::Type(self0), Pat::Type(other0)) => self0 == other0, + (Pat::Verbatim(self0), Pat::Verbatim(other0)) => { + TokenStreamHelper(self0) == TokenStreamHelper(other0) + } + (Pat::Wild(self0), Pat::Wild(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatBox {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatBox { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.pat == other.pat + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatIdent {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatIdent { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.by_ref == other.by_ref + && self.mutability == other.mutability + && self.ident == other.ident + && self.subpat == other.subpat + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatLit {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatLit { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.expr == other.expr + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatMacro {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatMacro { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.mac == other.mac + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatOr {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatOr { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.leading_vert == other.leading_vert + && self.cases == other.cases + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatPath {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatPath { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.qself == other.qself && self.path == other.path + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatRange {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatRange { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.lo == other.lo + && self.limits == other.limits + && self.hi == other.hi + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatReference {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatReference { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.mutability == other.mutability && self.pat == other.pat + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatRest {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatRest { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatSlice {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatSlice { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.elems == other.elems + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatStruct {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatStruct { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.path == other.path + && self.fields == other.fields + && self.dot2_token == other.dot2_token + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatTuple {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatTuple { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.elems == other.elems + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatTupleStruct {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatTupleStruct { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.path == other.path && self.pat == other.pat + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatType {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatType { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.pat == other.pat && self.ty == other.ty + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatWild {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatWild { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Path {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Path { + fn eq(&self, other: &Self) -> bool { + self.leading_colon == other.leading_colon && self.segments == other.segments + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PathArguments {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PathArguments { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (PathArguments::None, PathArguments::None) => true, + (PathArguments::AngleBracketed(self0), PathArguments::AngleBracketed(other0)) => { + self0 == other0 + } + (PathArguments::Parenthesized(self0), PathArguments::Parenthesized(other0)) => { + self0 == other0 + } + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PathSegment {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PathSegment { + fn eq(&self, other: &Self) -> bool { + self.ident == other.ident && self.arguments == other.arguments + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PredicateEq {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PredicateEq { + fn eq(&self, other: &Self) -> bool { + self.lhs_ty == other.lhs_ty && self.rhs_ty == other.rhs_ty + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PredicateLifetime {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PredicateLifetime { + fn eq(&self, other: &Self) -> bool { + self.lifetime == other.lifetime && self.bounds == other.bounds + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PredicateType {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PredicateType { + fn eq(&self, other: &Self) -> bool { + self.lifetimes == other.lifetimes + && self.bounded_ty == other.bounded_ty + && self.bounds == other.bounds + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for QSelf {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for QSelf { + fn eq(&self, other: &Self) -> bool { + self.ty == other.ty && self.position == other.position && self.as_token == other.as_token + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for RangeLimits {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for RangeLimits { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (RangeLimits::HalfOpen(_), RangeLimits::HalfOpen(_)) => true, + (RangeLimits::Closed(_), RangeLimits::Closed(_)) => true, + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Receiver {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Receiver { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.reference == other.reference + && self.mutability == other.mutability + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for ReturnType {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for ReturnType { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (ReturnType::Default, ReturnType::Default) => true, + (ReturnType::Type(_, self1), ReturnType::Type(_, other1)) => self1 == other1, + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Signature {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Signature { + fn eq(&self, other: &Self) -> bool { + self.constness == other.constness + && self.asyncness == other.asyncness + && self.unsafety == other.unsafety + && self.abi == other.abi + && self.ident == other.ident + && self.generics == other.generics + && self.inputs == other.inputs + && self.variadic == other.variadic + && self.output == other.output + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Stmt {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Stmt { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Stmt::Local(self0), Stmt::Local(other0)) => self0 == other0, + (Stmt::Item(self0), Stmt::Item(other0)) => self0 == other0, + (Stmt::Expr(self0), Stmt::Expr(other0)) => self0 == other0, + (Stmt::Semi(self0, _), Stmt::Semi(other0, _)) => self0 == other0, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TraitBound {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TraitBound { + fn eq(&self, other: &Self) -> bool { + self.paren_token == other.paren_token + && self.modifier == other.modifier + && self.lifetimes == other.lifetimes + && self.path == other.path + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TraitBoundModifier {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TraitBoundModifier { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (TraitBoundModifier::None, TraitBoundModifier::None) => true, + (TraitBoundModifier::Maybe(_), TraitBoundModifier::Maybe(_)) => true, + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TraitItem {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TraitItem { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (TraitItem::Const(self0), TraitItem::Const(other0)) => self0 == other0, + (TraitItem::Method(self0), TraitItem::Method(other0)) => self0 == other0, + (TraitItem::Type(self0), TraitItem::Type(other0)) => self0 == other0, + (TraitItem::Macro(self0), TraitItem::Macro(other0)) => self0 == other0, + (TraitItem::Verbatim(self0), TraitItem::Verbatim(other0)) => { + TokenStreamHelper(self0) == TokenStreamHelper(other0) + } + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TraitItemConst {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TraitItemConst { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.ident == other.ident + && self.ty == other.ty + && self.default == other.default + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TraitItemMacro {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TraitItemMacro { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.mac == other.mac && self.semi_token == other.semi_token + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TraitItemMethod {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TraitItemMethod { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.sig == other.sig + && self.default == other.default + && self.semi_token == other.semi_token + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TraitItemType {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TraitItemType { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.ident == other.ident + && self.generics == other.generics + && self.colon_token == other.colon_token + && self.bounds == other.bounds + && self.default == other.default + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Type {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Type { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Type::Array(self0), Type::Array(other0)) => self0 == other0, + (Type::BareFn(self0), Type::BareFn(other0)) => self0 == other0, + (Type::Group(self0), Type::Group(other0)) => self0 == other0, + (Type::ImplTrait(self0), Type::ImplTrait(other0)) => self0 == other0, + (Type::Infer(self0), Type::Infer(other0)) => self0 == other0, + (Type::Macro(self0), Type::Macro(other0)) => self0 == other0, + (Type::Never(self0), Type::Never(other0)) => self0 == other0, + (Type::Paren(self0), Type::Paren(other0)) => self0 == other0, + (Type::Path(self0), Type::Path(other0)) => self0 == other0, + (Type::Ptr(self0), Type::Ptr(other0)) => self0 == other0, + (Type::Reference(self0), Type::Reference(other0)) => self0 == other0, + (Type::Slice(self0), Type::Slice(other0)) => self0 == other0, + (Type::TraitObject(self0), Type::TraitObject(other0)) => self0 == other0, + (Type::Tuple(self0), Type::Tuple(other0)) => self0 == other0, + (Type::Verbatim(self0), Type::Verbatim(other0)) => { + TokenStreamHelper(self0) == TokenStreamHelper(other0) + } + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeArray {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeArray { + fn eq(&self, other: &Self) -> bool { + self.elem == other.elem && self.len == other.len + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeBareFn {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeBareFn { + fn eq(&self, other: &Self) -> bool { + self.lifetimes == other.lifetimes + && self.unsafety == other.unsafety + && self.abi == other.abi + && self.inputs == other.inputs + && self.variadic == other.variadic + && self.output == other.output + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeGroup {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeGroup { + fn eq(&self, other: &Self) -> bool { + self.elem == other.elem + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeImplTrait {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeImplTrait { + fn eq(&self, other: &Self) -> bool { + self.bounds == other.bounds + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeInfer {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeInfer { + fn eq(&self, _other: &Self) -> bool { + true + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeMacro {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeMacro { + fn eq(&self, other: &Self) -> bool { + self.mac == other.mac + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeNever {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeNever { + fn eq(&self, _other: &Self) -> bool { + true + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeParam {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeParam { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.ident == other.ident + && self.colon_token == other.colon_token + && self.bounds == other.bounds + && self.eq_token == other.eq_token + && self.default == other.default + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeParamBound {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeParamBound { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (TypeParamBound::Trait(self0), TypeParamBound::Trait(other0)) => self0 == other0, + (TypeParamBound::Lifetime(self0), TypeParamBound::Lifetime(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeParen {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeParen { + fn eq(&self, other: &Self) -> bool { + self.elem == other.elem + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypePath {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypePath { + fn eq(&self, other: &Self) -> bool { + self.qself == other.qself && self.path == other.path + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypePtr {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypePtr { + fn eq(&self, other: &Self) -> bool { + self.const_token == other.const_token + && self.mutability == other.mutability + && self.elem == other.elem + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeReference {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeReference { + fn eq(&self, other: &Self) -> bool { + self.lifetime == other.lifetime + && self.mutability == other.mutability + && self.elem == other.elem + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeSlice {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeSlice { + fn eq(&self, other: &Self) -> bool { + self.elem == other.elem + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeTraitObject {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeTraitObject { + fn eq(&self, other: &Self) -> bool { + self.dyn_token == other.dyn_token && self.bounds == other.bounds + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for TypeTuple {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for TypeTuple { + fn eq(&self, other: &Self) -> bool { + self.elems == other.elems + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for UnOp {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for UnOp { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (UnOp::Deref(_), UnOp::Deref(_)) => true, + (UnOp::Not(_), UnOp::Not(_)) => true, + (UnOp::Neg(_), UnOp::Neg(_)) => true, + _ => false, + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for UseGlob {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for UseGlob { + fn eq(&self, _other: &Self) -> bool { + true + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for UseGroup {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for UseGroup { + fn eq(&self, other: &Self) -> bool { + self.items == other.items + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for UseName {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for UseName { + fn eq(&self, other: &Self) -> bool { + self.ident == other.ident + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for UsePath {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for UsePath { + fn eq(&self, other: &Self) -> bool { + self.ident == other.ident && self.tree == other.tree + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for UseRename {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for UseRename { + fn eq(&self, other: &Self) -> bool { + self.ident == other.ident && self.rename == other.rename + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for UseTree {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for UseTree { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (UseTree::Path(self0), UseTree::Path(other0)) => self0 == other0, + (UseTree::Name(self0), UseTree::Name(other0)) => self0 == other0, + (UseTree::Rename(self0), UseTree::Rename(other0)) => self0 == other0, + (UseTree::Glob(self0), UseTree::Glob(other0)) => self0 == other0, + (UseTree::Group(self0), UseTree::Group(other0)) => self0 == other0, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Variadic {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Variadic { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Variant {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Variant { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs + && self.ident == other.ident + && self.fields == other.fields + && self.discriminant == other.discriminant + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for VisCrate {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for VisCrate { + fn eq(&self, _other: &Self) -> bool { + true + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for VisPublic {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for VisPublic { + fn eq(&self, _other: &Self) -> bool { + true + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for VisRestricted {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for VisRestricted { + fn eq(&self, other: &Self) -> bool { + self.in_token == other.in_token && self.path == other.path + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for Visibility {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for Visibility { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Visibility::Public(self0), Visibility::Public(other0)) => self0 == other0, + (Visibility::Crate(self0), Visibility::Crate(other0)) => self0 == other0, + (Visibility::Restricted(self0), Visibility::Restricted(other0)) => self0 == other0, + (Visibility::Inherited, Visibility::Inherited) => true, + _ => false, + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for WhereClause {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for WhereClause { + fn eq(&self, other: &Self) -> bool { + self.predicates == other.predicates + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for WherePredicate {} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for WherePredicate { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (WherePredicate::Type(self0), WherePredicate::Type(other0)) => self0 == other0, + (WherePredicate::Lifetime(self0), WherePredicate::Lifetime(other0)) => self0 == other0, + (WherePredicate::Eq(self0), WherePredicate::Eq(other0)) => self0 == other0, + _ => false, + } + } +} diff --git a/1.0.7/src/gen/fold.rs b/src/gen/fold.rs index f51218b7..d9dd32a4 100644 --- a/1.0.7/src/gen/fold.rs +++ b/src/gen/fold.rs @@ -2,6 +2,7 @@ // It is not intended for manual editing. #![allow(unreachable_code, unused_variables)] +#![allow(clippy::match_wildcard_for_single_variants)] #[cfg(any(feature = "full", feature = "derive"))] use crate::gen::helper::fold::*; #[cfg(any(feature = "full", feature = "derive"))] @@ -26,7 +27,7 @@ macro_rules! full { /// /// [module documentation]: self /// -/// *This trait is available if Syn is built with the `"fold"` feature.* +/// *This trait is available only if Syn is built with the `"fold"` feature.* pub trait Fold { #[cfg(any(feature = "derive", feature = "full"))] fn fold_abi(&mut self, i: Abi) -> Abi { @@ -433,35 +434,27 @@ pub trait Fold { fn fold_lifetime_def(&mut self, i: LifetimeDef) -> LifetimeDef { fold_lifetime_def(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn fold_lit(&mut self, i: Lit) -> Lit { fold_lit(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn fold_lit_bool(&mut self, i: LitBool) -> LitBool { fold_lit_bool(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn fold_lit_byte(&mut self, i: LitByte) -> LitByte { fold_lit_byte(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn fold_lit_byte_str(&mut self, i: LitByteStr) -> LitByteStr { fold_lit_byte_str(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn fold_lit_char(&mut self, i: LitChar) -> LitChar { fold_lit_char(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn fold_lit_float(&mut self, i: LitFloat) -> LitFloat { fold_lit_float(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn fold_lit_int(&mut self, i: LitInt) -> LitInt { fold_lit_int(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn fold_lit_str(&mut self, i: LitStr) -> LitStr { fold_lit_str(self, i) } @@ -799,10 +792,10 @@ where F: Fold + ?Sized, { AngleBracketedGenericArguments { - colon2_token: (node.colon2_token).map(|it| Token ! [ :: ](tokens_helper(f, &it.spans))), - lt_token: Token ! [ < ](tokens_helper(f, &node.lt_token.spans)), + colon2_token: (node.colon2_token).map(|it| Token ! [::](tokens_helper(f, &it.spans))), + lt_token: Token ! [<](tokens_helper(f, &node.lt_token.spans)), args: FoldHelper::lift(node.args, |it| f.fold_generic_argument(it)), - gt_token: Token ! [ > ](tokens_helper(f, &node.gt_token.spans)), + gt_token: Token ! [>](tokens_helper(f, &node.gt_token.spans)), } } #[cfg(feature = "full")] @@ -819,9 +812,9 @@ where Box::new(f.fold_expr(*(it).1)), ) }), - fat_arrow_token: Token ! [ => ](tokens_helper(f, &node.fat_arrow_token.spans)), + fat_arrow_token: Token ! [=>](tokens_helper(f, &node.fat_arrow_token.spans)), body: Box::new(f.fold_expr(*node.body)), - comma: (node.comma).map(|it| Token ! [ , ](tokens_helper(f, &it.spans))), + comma: (node.comma).map(|it| Token ! [,](tokens_helper(f, &it.spans))), } } #[cfg(any(feature = "derive", feature = "full"))] @@ -842,7 +835,7 @@ where F: Fold + ?Sized, { Attribute { - pound_token: Token ! [ # ](tokens_helper(f, &node.pound_token.spans)), + pound_token: Token ! [#](tokens_helper(f, &node.pound_token.spans)), style: f.fold_attr_style(node.style), bracket_token: Bracket(tokens_helper(f, &node.bracket_token.span)), path: f.fold_path(node.path), @@ -859,7 +852,7 @@ where name: (node.name).map(|it| { ( f.fold_ident((it).0), - Token ! [ : ](tokens_helper(f, &(it).1.spans)), + Token ! [:](tokens_helper(f, &(it).1.spans)), ) }), ty: f.fold_type(node.ty), @@ -871,59 +864,47 @@ where F: Fold + ?Sized, { match node { - BinOp::Add(_binding_0) => BinOp::Add(Token ! [ + ](tokens_helper(f, &_binding_0.spans))), - BinOp::Sub(_binding_0) => BinOp::Sub(Token ! [ - ](tokens_helper(f, &_binding_0.spans))), - BinOp::Mul(_binding_0) => BinOp::Mul(Token ! [ * ](tokens_helper(f, &_binding_0.spans))), - BinOp::Div(_binding_0) => BinOp::Div(Token ! [ / ](tokens_helper(f, &_binding_0.spans))), - BinOp::Rem(_binding_0) => BinOp::Rem(Token ! [ % ](tokens_helper(f, &_binding_0.spans))), - BinOp::And(_binding_0) => BinOp::And(Token ! [ && ](tokens_helper(f, &_binding_0.spans))), - BinOp::Or(_binding_0) => BinOp::Or(Token ! [ || ](tokens_helper(f, &_binding_0.spans))), + BinOp::Add(_binding_0) => BinOp::Add(Token ! [+](tokens_helper(f, &_binding_0.spans))), + BinOp::Sub(_binding_0) => BinOp::Sub(Token ! [-](tokens_helper(f, &_binding_0.spans))), + BinOp::Mul(_binding_0) => BinOp::Mul(Token ! [*](tokens_helper(f, &_binding_0.spans))), + BinOp::Div(_binding_0) => BinOp::Div(Token ! [/](tokens_helper(f, &_binding_0.spans))), + BinOp::Rem(_binding_0) => BinOp::Rem(Token ! [%](tokens_helper(f, &_binding_0.spans))), + BinOp::And(_binding_0) => BinOp::And(Token ! [&&](tokens_helper(f, &_binding_0.spans))), + BinOp::Or(_binding_0) => BinOp::Or(Token ! [||](tokens_helper(f, &_binding_0.spans))), BinOp::BitXor(_binding_0) => { - BinOp::BitXor(Token ! [ ^ ](tokens_helper(f, &_binding_0.spans))) + BinOp::BitXor(Token ! [^](tokens_helper(f, &_binding_0.spans))) } BinOp::BitAnd(_binding_0) => { - BinOp::BitAnd(Token ! [ & ](tokens_helper(f, &_binding_0.spans))) - } - BinOp::BitOr(_binding_0) => { - BinOp::BitOr(Token ! [ | ](tokens_helper(f, &_binding_0.spans))) - } - BinOp::Shl(_binding_0) => BinOp::Shl(Token ! [ << ](tokens_helper(f, &_binding_0.spans))), - BinOp::Shr(_binding_0) => BinOp::Shr(Token ! [ >> ](tokens_helper(f, &_binding_0.spans))), - BinOp::Eq(_binding_0) => BinOp::Eq(Token ! [ == ](tokens_helper(f, &_binding_0.spans))), - BinOp::Lt(_binding_0) => BinOp::Lt(Token ! [ < ](tokens_helper(f, &_binding_0.spans))), - BinOp::Le(_binding_0) => BinOp::Le(Token ! [ <= ](tokens_helper(f, &_binding_0.spans))), - BinOp::Ne(_binding_0) => BinOp::Ne(Token ! [ != ](tokens_helper(f, &_binding_0.spans))), - BinOp::Ge(_binding_0) => BinOp::Ge(Token ! [ >= ](tokens_helper(f, &_binding_0.spans))), - BinOp::Gt(_binding_0) => BinOp::Gt(Token ! [ > ](tokens_helper(f, &_binding_0.spans))), - BinOp::AddEq(_binding_0) => { - BinOp::AddEq(Token ! [ += ](tokens_helper(f, &_binding_0.spans))) - } - BinOp::SubEq(_binding_0) => { - BinOp::SubEq(Token ! [ -= ](tokens_helper(f, &_binding_0.spans))) - } - BinOp::MulEq(_binding_0) => { - BinOp::MulEq(Token ! [ *= ](tokens_helper(f, &_binding_0.spans))) - } - BinOp::DivEq(_binding_0) => { - BinOp::DivEq(Token ! [ /= ](tokens_helper(f, &_binding_0.spans))) - } - BinOp::RemEq(_binding_0) => { - BinOp::RemEq(Token ! [ %= ](tokens_helper(f, &_binding_0.spans))) + BinOp::BitAnd(Token ! [&](tokens_helper(f, &_binding_0.spans))) } + BinOp::BitOr(_binding_0) => BinOp::BitOr(Token ! [|](tokens_helper(f, &_binding_0.spans))), + BinOp::Shl(_binding_0) => BinOp::Shl(Token ! [<<](tokens_helper(f, &_binding_0.spans))), + BinOp::Shr(_binding_0) => BinOp::Shr(Token ! [>>](tokens_helper(f, &_binding_0.spans))), + BinOp::Eq(_binding_0) => BinOp::Eq(Token ! [==](tokens_helper(f, &_binding_0.spans))), + BinOp::Lt(_binding_0) => BinOp::Lt(Token ! [<](tokens_helper(f, &_binding_0.spans))), + BinOp::Le(_binding_0) => BinOp::Le(Token ! [<=](tokens_helper(f, &_binding_0.spans))), + BinOp::Ne(_binding_0) => BinOp::Ne(Token ! [!=](tokens_helper(f, &_binding_0.spans))), + BinOp::Ge(_binding_0) => BinOp::Ge(Token ! [>=](tokens_helper(f, &_binding_0.spans))), + BinOp::Gt(_binding_0) => BinOp::Gt(Token ! [>](tokens_helper(f, &_binding_0.spans))), + BinOp::AddEq(_binding_0) => BinOp::AddEq(Token ! [+=](tokens_helper(f, &_binding_0.spans))), + BinOp::SubEq(_binding_0) => BinOp::SubEq(Token ! [-=](tokens_helper(f, &_binding_0.spans))), + BinOp::MulEq(_binding_0) => BinOp::MulEq(Token ! [*=](tokens_helper(f, &_binding_0.spans))), + BinOp::DivEq(_binding_0) => BinOp::DivEq(Token ! [/=](tokens_helper(f, &_binding_0.spans))), + BinOp::RemEq(_binding_0) => BinOp::RemEq(Token ! [%=](tokens_helper(f, &_binding_0.spans))), BinOp::BitXorEq(_binding_0) => { - BinOp::BitXorEq(Token ! [ ^= ](tokens_helper(f, &_binding_0.spans))) + BinOp::BitXorEq(Token ! [^=](tokens_helper(f, &_binding_0.spans))) } BinOp::BitAndEq(_binding_0) => { - BinOp::BitAndEq(Token ! [ &= ](tokens_helper(f, &_binding_0.spans))) + BinOp::BitAndEq(Token ! [&=](tokens_helper(f, &_binding_0.spans))) } BinOp::BitOrEq(_binding_0) => { - BinOp::BitOrEq(Token ! [ |= ](tokens_helper(f, &_binding_0.spans))) + BinOp::BitOrEq(Token ! [|=](tokens_helper(f, &_binding_0.spans))) } BinOp::ShlEq(_binding_0) => { - BinOp::ShlEq(Token ! [ <<= ](tokens_helper(f, &_binding_0.spans))) + BinOp::ShlEq(Token ! [<<=](tokens_helper(f, &_binding_0.spans))) } BinOp::ShrEq(_binding_0) => { - BinOp::ShrEq(Token ! [ >>= ](tokens_helper(f, &_binding_0.spans))) + BinOp::ShrEq(Token ! [>>=](tokens_helper(f, &_binding_0.spans))) } } } @@ -934,7 +915,7 @@ where { Binding { ident: f.fold_ident(node.ident), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), ty: f.fold_type(node.ty), } } @@ -955,9 +936,9 @@ where { BoundLifetimes { for_token: Token![for](tokens_helper(f, &node.for_token.span)), - lt_token: Token ! [ < ](tokens_helper(f, &node.lt_token.spans)), + lt_token: Token ! [<](tokens_helper(f, &node.lt_token.spans)), lifetimes: FoldHelper::lift(node.lifetimes, |it| f.fold_lifetime_def(it)), - gt_token: Token ! [ > ](tokens_helper(f, &node.gt_token.spans)), + gt_token: Token ! [>](tokens_helper(f, &node.gt_token.spans)), } } #[cfg(any(feature = "derive", feature = "full"))] @@ -969,9 +950,9 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), const_token: Token![const](tokens_helper(f, &node.const_token.span)), ident: f.fold_ident(node.ident), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), ty: f.fold_type(node.ty), - eq_token: (node.eq_token).map(|it| Token ! [ = ](tokens_helper(f, &it.spans))), + eq_token: (node.eq_token).map(|it| Token ! [=](tokens_helper(f, &it.spans))), default: (node.default).map(|it| f.fold_expr(it)), } } @@ -982,7 +963,7 @@ where { Constraint { ident: f.fold_ident(node.ident), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), bounds: FoldHelper::lift(node.bounds, |it| f.fold_type_param_bound(it)), } } @@ -1016,7 +997,7 @@ where DataStruct { struct_token: Token![struct](tokens_helper(f, &node.struct_token.span)), fields: f.fold_fields(node.fields), - semi_token: (node.semi_token).map(|it| Token ! [ ; ](tokens_helper(f, &it.spans))), + semi_token: (node.semi_token).map(|it| Token ! [;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "derive")] @@ -1112,7 +1093,7 @@ where ExprAssign { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), left: Box::new(f.fold_expr(*node.left)), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), right: Box::new(f.fold_expr(*node.right)), } } @@ -1148,7 +1129,7 @@ where ExprAwait { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), base: Box::new(f.fold_expr(*node.base)), - dot_token: Token ! [ . ](tokens_helper(f, &node.dot_token.spans)), + dot_token: Token ! [.](tokens_helper(f, &node.dot_token.spans)), await_token: crate::token::Await(tokens_helper(f, &node.await_token.span)), } } @@ -1232,9 +1213,9 @@ where asyncness: (node.asyncness).map(|it| Token![async](tokens_helper(f, &it.span))), movability: (node.movability).map(|it| Token![static](tokens_helper(f, &it.span))), capture: (node.capture).map(|it| Token![move](tokens_helper(f, &it.span))), - or1_token: Token ! [ | ](tokens_helper(f, &node.or1_token.spans)), + or1_token: Token ! [|](tokens_helper(f, &node.or1_token.spans)), inputs: FoldHelper::lift(node.inputs, |it| f.fold_pat(it)), - or2_token: Token ! [ | ](tokens_helper(f, &node.or2_token.spans)), + or2_token: Token ! [|](tokens_helper(f, &node.or2_token.spans)), output: f.fold_return_type(node.output), body: Box::new(f.fold_expr(*node.body)), } @@ -1258,7 +1239,7 @@ where ExprField { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), base: Box::new(f.fold_expr(*node.base)), - dot_token: Token ! [ . ](tokens_helper(f, &node.dot_token.spans)), + dot_token: Token ! [.](tokens_helper(f, &node.dot_token.spans)), member: f.fold_member(node.member), } } @@ -1327,7 +1308,7 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), let_token: Token![let](tokens_helper(f, &node.let_token.span)), pat: f.fold_pat(node.pat), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), expr: Box::new(f.fold_expr(*node.expr)), } } @@ -1384,7 +1365,7 @@ where ExprMethodCall { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), receiver: Box::new(f.fold_expr(*node.receiver)), - dot_token: Token ! [ . ](tokens_helper(f, &node.dot_token.spans)), + dot_token: Token ! [.](tokens_helper(f, &node.dot_token.spans)), method: f.fold_ident(node.method), turbofish: (node.turbofish).map(|it| f.fold_method_turbofish(it)), paren_token: Paren(tokens_helper(f, &node.paren_token.span)), @@ -1432,7 +1413,7 @@ where { ExprReference { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), - and_token: Token ! [ & ](tokens_helper(f, &node.and_token.spans)), + and_token: Token ! [&](tokens_helper(f, &node.and_token.spans)), raw: node.raw, mutability: (node.mutability).map(|it| Token![mut](tokens_helper(f, &it.span))), expr: Box::new(f.fold_expr(*node.expr)), @@ -1447,7 +1428,7 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), bracket_token: Bracket(tokens_helper(f, &node.bracket_token.span)), expr: Box::new(f.fold_expr(*node.expr)), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), len: Box::new(f.fold_expr(*node.len)), } } @@ -1484,7 +1465,7 @@ where ExprTry { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), expr: Box::new(f.fold_expr(*node.expr)), - question_token: Token ! [ ? ](tokens_helper(f, &node.question_token.spans)), + question_token: Token ! [?](tokens_helper(f, &node.question_token.spans)), } } #[cfg(feature = "full")] @@ -1517,7 +1498,7 @@ where ExprType { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), expr: Box::new(f.fold_expr(*node.expr)), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), ty: Box::new(f.fold_type(*node.ty)), } } @@ -1576,7 +1557,7 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), vis: f.fold_visibility(node.vis), ident: (node.ident).map(|it| f.fold_ident(it)), - colon_token: (node.colon_token).map(|it| Token ! [ : ](tokens_helper(f, &it.spans))), + colon_token: (node.colon_token).map(|it| Token ! [:](tokens_helper(f, &it.spans))), ty: f.fold_type(node.ty), } } @@ -1588,7 +1569,7 @@ where FieldPat { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), member: f.fold_member(node.member), - colon_token: (node.colon_token).map(|it| Token ! [ : ](tokens_helper(f, &it.spans))), + colon_token: (node.colon_token).map(|it| Token ! [:](tokens_helper(f, &it.spans))), pat: Box::new(f.fold_pat(*node.pat)), } } @@ -1600,7 +1581,7 @@ where FieldValue { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), member: f.fold_member(node.member), - colon_token: (node.colon_token).map(|it| Token ! [ : ](tokens_helper(f, &it.spans))), + colon_token: (node.colon_token).map(|it| Token ! [:](tokens_helper(f, &it.spans))), expr: f.fold_expr(node.expr), } } @@ -1681,7 +1662,7 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), vis: f.fold_visibility(node.vis), sig: f.fold_signature(node.sig), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -1692,7 +1673,7 @@ where ForeignItemMacro { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), mac: f.fold_macro(node.mac), - semi_token: (node.semi_token).map(|it| Token ! [ ; ](tokens_helper(f, &it.spans))), + semi_token: (node.semi_token).map(|it| Token ! [;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "full")] @@ -1706,9 +1687,9 @@ where static_token: Token![static](tokens_helper(f, &node.static_token.span)), mutability: (node.mutability).map(|it| Token![mut](tokens_helper(f, &it.span))), ident: f.fold_ident(node.ident), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), ty: Box::new(f.fold_type(*node.ty)), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -1721,7 +1702,7 @@ where vis: f.fold_visibility(node.vis), type_token: Token![type](tokens_helper(f, &node.type_token.span)), ident: f.fold_ident(node.ident), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(any(feature = "derive", feature = "full"))] @@ -1779,9 +1760,9 @@ where F: Fold + ?Sized, { Generics { - lt_token: (node.lt_token).map(|it| Token ! [ < ](tokens_helper(f, &it.spans))), + lt_token: (node.lt_token).map(|it| Token ! [<](tokens_helper(f, &it.spans))), params: FoldHelper::lift(node.params, |it| f.fold_generic_param(it)), - gt_token: (node.gt_token).map(|it| Token ! [ > ](tokens_helper(f, &it.spans))), + gt_token: (node.gt_token).map(|it| Token ! [>](tokens_helper(f, &it.spans))), where_clause: (node.where_clause).map(|it| f.fold_where_clause(it)), } } @@ -1819,11 +1800,11 @@ where defaultness: (node.defaultness).map(|it| Token![default](tokens_helper(f, &it.span))), const_token: Token![const](tokens_helper(f, &node.const_token.span)), ident: f.fold_ident(node.ident), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), ty: f.fold_type(node.ty), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), expr: f.fold_expr(node.expr), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -1834,7 +1815,7 @@ where ImplItemMacro { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), mac: f.fold_macro(node.mac), - semi_token: (node.semi_token).map(|it| Token ! [ ; ](tokens_helper(f, &it.spans))), + semi_token: (node.semi_token).map(|it| Token ! [;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "full")] @@ -1862,9 +1843,9 @@ where type_token: Token![type](tokens_helper(f, &node.type_token.span)), ident: f.fold_ident(node.ident), generics: f.fold_generics(node.generics), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), ty: f.fold_type(node.ty), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(any(feature = "derive", feature = "full"))] @@ -1913,11 +1894,11 @@ where vis: f.fold_visibility(node.vis), const_token: Token![const](tokens_helper(f, &node.const_token.span)), ident: f.fold_ident(node.ident), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), ty: Box::new(f.fold_type(*node.ty)), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), expr: Box::new(f.fold_expr(*node.expr)), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -1952,7 +1933,7 @@ where f.fold_ident((it).1), ) }), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -2011,7 +1992,7 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), ident: (node.ident).map(|it| f.fold_ident(it)), mac: f.fold_macro(node.mac), - semi_token: (node.semi_token).map(|it| Token ! [ ; ](tokens_helper(f, &it.spans))), + semi_token: (node.semi_token).map(|it| Token ! [;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "full")] @@ -2043,7 +2024,7 @@ where FoldHelper::lift((it).1, |it| f.fold_item(it)), ) }), - semi: (node.semi).map(|it| Token ! [ ; ](tokens_helper(f, &it.spans))), + semi: (node.semi).map(|it| Token ! [;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "full")] @@ -2057,11 +2038,11 @@ where static_token: Token![static](tokens_helper(f, &node.static_token.span)), mutability: (node.mutability).map(|it| Token![mut](tokens_helper(f, &it.span))), ident: f.fold_ident(node.ident), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), ty: Box::new(f.fold_type(*node.ty)), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), expr: Box::new(f.fold_expr(*node.expr)), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -2076,7 +2057,7 @@ where ident: f.fold_ident(node.ident), generics: f.fold_generics(node.generics), fields: f.fold_fields(node.fields), - semi_token: (node.semi_token).map(|it| Token ! [ ; ](tokens_helper(f, &it.spans))), + semi_token: (node.semi_token).map(|it| Token ! [;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "full")] @@ -2092,7 +2073,7 @@ where trait_token: Token![trait](tokens_helper(f, &node.trait_token.span)), ident: f.fold_ident(node.ident), generics: f.fold_generics(node.generics), - colon_token: (node.colon_token).map(|it| Token ! [ : ](tokens_helper(f, &it.spans))), + colon_token: (node.colon_token).map(|it| Token ! [:](tokens_helper(f, &it.spans))), supertraits: FoldHelper::lift(node.supertraits, |it| f.fold_type_param_bound(it)), brace_token: Brace(tokens_helper(f, &node.brace_token.span)), items: FoldHelper::lift(node.items, |it| f.fold_trait_item(it)), @@ -2109,9 +2090,9 @@ where trait_token: Token![trait](tokens_helper(f, &node.trait_token.span)), ident: f.fold_ident(node.ident), generics: f.fold_generics(node.generics), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), bounds: FoldHelper::lift(node.bounds, |it| f.fold_type_param_bound(it)), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -2125,9 +2106,9 @@ where type_token: Token![type](tokens_helper(f, &node.type_token.span)), ident: f.fold_ident(node.ident), generics: f.fold_generics(node.generics), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), ty: Box::new(f.fold_type(*node.ty)), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -2153,9 +2134,9 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), vis: f.fold_visibility(node.vis), use_token: Token![use](tokens_helper(f, &node.use_token.span)), - leading_colon: (node.leading_colon).map(|it| Token ! [ :: ](tokens_helper(f, &it.spans))), + leading_colon: (node.leading_colon).map(|it| Token ! [::](tokens_helper(f, &it.spans))), tree: f.fold_use_tree(node.tree), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -2165,7 +2146,7 @@ where { Label { name: f.fold_lifetime(node.name), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), } } pub fn fold_lifetime<F>(f: &mut F, node: Lifetime) -> Lifetime @@ -2185,11 +2166,10 @@ where LifetimeDef { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), lifetime: f.fold_lifetime(node.lifetime), - colon_token: (node.colon_token).map(|it| Token ! [ : ](tokens_helper(f, &it.spans))), + colon_token: (node.colon_token).map(|it| Token ! [:](tokens_helper(f, &it.spans))), bounds: FoldHelper::lift(node.bounds, |it| f.fold_lifetime(it)), } } -#[cfg(any(feature = "derive", feature = "full"))] pub fn fold_lit<F>(f: &mut F, node: Lit) -> Lit where F: Fold + ?Sized, @@ -2205,7 +2185,6 @@ where Lit::Verbatim(_binding_0) => Lit::Verbatim(_binding_0), } } -#[cfg(any(feature = "derive", feature = "full"))] pub fn fold_lit_bool<F>(f: &mut F, node: LitBool) -> LitBool where F: Fold + ?Sized, @@ -2215,7 +2194,6 @@ where span: f.fold_span(node.span), } } -#[cfg(any(feature = "derive", feature = "full"))] pub fn fold_lit_byte<F>(f: &mut F, node: LitByte) -> LitByte where F: Fold + ?Sized, @@ -2225,7 +2203,6 @@ where node.set_span(span); node } -#[cfg(any(feature = "derive", feature = "full"))] pub fn fold_lit_byte_str<F>(f: &mut F, node: LitByteStr) -> LitByteStr where F: Fold + ?Sized, @@ -2235,7 +2212,6 @@ where node.set_span(span); node } -#[cfg(any(feature = "derive", feature = "full"))] pub fn fold_lit_char<F>(f: &mut F, node: LitChar) -> LitChar where F: Fold + ?Sized, @@ -2245,7 +2221,6 @@ where node.set_span(span); node } -#[cfg(any(feature = "derive", feature = "full"))] pub fn fold_lit_float<F>(f: &mut F, node: LitFloat) -> LitFloat where F: Fold + ?Sized, @@ -2255,7 +2230,6 @@ where node.set_span(span); node } -#[cfg(any(feature = "derive", feature = "full"))] pub fn fold_lit_int<F>(f: &mut F, node: LitInt) -> LitInt where F: Fold + ?Sized, @@ -2265,7 +2239,6 @@ where node.set_span(span); node } -#[cfg(any(feature = "derive", feature = "full"))] pub fn fold_lit_str<F>(f: &mut F, node: LitStr) -> LitStr where F: Fold + ?Sized, @@ -2286,11 +2259,11 @@ where pat: f.fold_pat(node.pat), init: (node.init).map(|it| { ( - Token ! [ = ](tokens_helper(f, &(it).0.spans)), + Token ! [=](tokens_helper(f, &(it).0.spans)), Box::new(f.fold_expr(*(it).1)), ) }), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(any(feature = "derive", feature = "full"))] @@ -2361,7 +2334,7 @@ where { MetaNameValue { path: f.fold_path(node.path), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), lit: f.fold_lit(node.lit), } } @@ -2371,10 +2344,10 @@ where F: Fold + ?Sized, { MethodTurbofish { - colon2_token: Token ! [ :: ](tokens_helper(f, &node.colon2_token.spans)), - lt_token: Token ! [ < ](tokens_helper(f, &node.lt_token.spans)), + colon2_token: Token ! [::](tokens_helper(f, &node.colon2_token.spans)), + lt_token: Token ! [<](tokens_helper(f, &node.lt_token.spans)), args: FoldHelper::lift(node.args, |it| f.fold_generic_method_argument(it)), - gt_token: Token ! [ > ](tokens_helper(f, &node.gt_token.spans)), + gt_token: Token ! [>](tokens_helper(f, &node.gt_token.spans)), } } #[cfg(any(feature = "derive", feature = "full"))] @@ -2449,7 +2422,7 @@ where ident: f.fold_ident(node.ident), subpat: (node.subpat).map(|it| { ( - Token ! [ @ ](tokens_helper(f, &(it).0.spans)), + Token ! [@](tokens_helper(f, &(it).0.spans)), Box::new(f.fold_pat(*(it).1)), ) }), @@ -2482,7 +2455,7 @@ where { PatOr { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), - leading_vert: (node.leading_vert).map(|it| Token ! [ | ](tokens_helper(f, &it.spans))), + leading_vert: (node.leading_vert).map(|it| Token ! [|](tokens_helper(f, &it.spans))), cases: FoldHelper::lift(node.cases, |it| f.fold_pat(it)), } } @@ -2516,7 +2489,7 @@ where { PatReference { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), - and_token: Token ! [ & ](tokens_helper(f, &node.and_token.spans)), + and_token: Token ! [&](tokens_helper(f, &node.and_token.spans)), mutability: (node.mutability).map(|it| Token![mut](tokens_helper(f, &it.span))), pat: Box::new(f.fold_pat(*node.pat)), } @@ -2585,7 +2558,7 @@ where PatType { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), pat: Box::new(f.fold_pat(*node.pat)), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), ty: Box::new(f.fold_type(*node.ty)), } } @@ -2605,7 +2578,7 @@ where F: Fold + ?Sized, { Path { - leading_colon: (node.leading_colon).map(|it| Token ! [ :: ](tokens_helper(f, &it.spans))), + leading_colon: (node.leading_colon).map(|it| Token ! [::](tokens_helper(f, &it.spans))), segments: FoldHelper::lift(node.segments, |it| f.fold_path_segment(it)), } } @@ -2641,7 +2614,7 @@ where { PredicateEq { lhs_ty: f.fold_type(node.lhs_ty), - eq_token: Token ! [ = ](tokens_helper(f, &node.eq_token.spans)), + eq_token: Token ! [=](tokens_helper(f, &node.eq_token.spans)), rhs_ty: f.fold_type(node.rhs_ty), } } @@ -2652,7 +2625,7 @@ where { PredicateLifetime { lifetime: f.fold_lifetime(node.lifetime), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), bounds: FoldHelper::lift(node.bounds, |it| f.fold_lifetime(it)), } } @@ -2664,7 +2637,7 @@ where PredicateType { lifetimes: (node.lifetimes).map(|it| f.fold_bound_lifetimes(it)), bounded_ty: f.fold_type(node.bounded_ty), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), bounds: FoldHelper::lift(node.bounds, |it| f.fold_type_param_bound(it)), } } @@ -2674,11 +2647,11 @@ where F: Fold + ?Sized, { QSelf { - lt_token: Token ! [ < ](tokens_helper(f, &node.lt_token.spans)), + lt_token: Token ! [<](tokens_helper(f, &node.lt_token.spans)), ty: Box::new(f.fold_type(*node.ty)), position: node.position, as_token: (node.as_token).map(|it| Token![as](tokens_helper(f, &it.span))), - gt_token: Token ! [ > ](tokens_helper(f, &node.gt_token.spans)), + gt_token: Token ! [>](tokens_helper(f, &node.gt_token.spans)), } } #[cfg(feature = "full")] @@ -2691,7 +2664,7 @@ where RangeLimits::HalfOpen(Token![..](tokens_helper(f, &_binding_0.spans))) } RangeLimits::Closed(_binding_0) => { - RangeLimits::Closed(Token ! [ ..= ](tokens_helper(f, &_binding_0.spans))) + RangeLimits::Closed(Token ! [..=](tokens_helper(f, &_binding_0.spans))) } } } @@ -2704,7 +2677,7 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), reference: (node.reference).map(|it| { ( - Token ! [ & ](tokens_helper(f, &(it).0.spans)), + Token ! [&](tokens_helper(f, &(it).0.spans)), ((it).1).map(|it| f.fold_lifetime(it)), ) }), @@ -2720,7 +2693,7 @@ where match node { ReturnType::Default => ReturnType::Default, ReturnType::Type(_binding_0, _binding_1) => ReturnType::Type( - Token ! [ -> ](tokens_helper(f, &_binding_0.spans)), + Token ! [->](tokens_helper(f, &_binding_0.spans)), Box::new(f.fold_type(*_binding_1)), ), } @@ -2761,7 +2734,7 @@ where Stmt::Expr(_binding_0) => Stmt::Expr(f.fold_expr(_binding_0)), Stmt::Semi(_binding_0, _binding_1) => Stmt::Semi( f.fold_expr(_binding_0), - Token ! [ ; ](tokens_helper(f, &_binding_1.spans)), + Token ! [;](tokens_helper(f, &_binding_1.spans)), ), } } @@ -2785,7 +2758,7 @@ where match node { TraitBoundModifier::None => TraitBoundModifier::None, TraitBoundModifier::Maybe(_binding_0) => { - TraitBoundModifier::Maybe(Token ! [ ? ](tokens_helper(f, &_binding_0.spans))) + TraitBoundModifier::Maybe(Token ! [?](tokens_helper(f, &_binding_0.spans))) } } } @@ -2812,15 +2785,15 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), const_token: Token![const](tokens_helper(f, &node.const_token.span)), ident: f.fold_ident(node.ident), - colon_token: Token ! [ : ](tokens_helper(f, &node.colon_token.spans)), + colon_token: Token ! [:](tokens_helper(f, &node.colon_token.spans)), ty: f.fold_type(node.ty), default: (node.default).map(|it| { ( - Token ! [ = ](tokens_helper(f, &(it).0.spans)), + Token ! [=](tokens_helper(f, &(it).0.spans)), f.fold_expr((it).1), ) }), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(feature = "full")] @@ -2831,7 +2804,7 @@ where TraitItemMacro { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), mac: f.fold_macro(node.mac), - semi_token: (node.semi_token).map(|it| Token ! [ ; ](tokens_helper(f, &it.spans))), + semi_token: (node.semi_token).map(|it| Token ! [;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "full")] @@ -2843,7 +2816,7 @@ where attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), sig: f.fold_signature(node.sig), default: (node.default).map(|it| f.fold_block(it)), - semi_token: (node.semi_token).map(|it| Token ! [ ; ](tokens_helper(f, &it.spans))), + semi_token: (node.semi_token).map(|it| Token ! [;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "full")] @@ -2856,15 +2829,15 @@ where type_token: Token![type](tokens_helper(f, &node.type_token.span)), ident: f.fold_ident(node.ident), generics: f.fold_generics(node.generics), - colon_token: (node.colon_token).map(|it| Token ! [ : ](tokens_helper(f, &it.spans))), + colon_token: (node.colon_token).map(|it| Token ! [:](tokens_helper(f, &it.spans))), bounds: FoldHelper::lift(node.bounds, |it| f.fold_type_param_bound(it)), default: (node.default).map(|it| { ( - Token ! [ = ](tokens_helper(f, &(it).0.spans)), + Token ! [=](tokens_helper(f, &(it).0.spans)), f.fold_type((it).1), ) }), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), } } #[cfg(any(feature = "derive", feature = "full"))] @@ -2899,7 +2872,7 @@ where TypeArray { bracket_token: Bracket(tokens_helper(f, &node.bracket_token.span)), elem: Box::new(f.fold_type(*node.elem)), - semi_token: Token ! [ ; ](tokens_helper(f, &node.semi_token.spans)), + semi_token: Token ! [;](tokens_helper(f, &node.semi_token.spans)), len: f.fold_expr(node.len), } } @@ -2974,9 +2947,9 @@ where TypeParam { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), ident: f.fold_ident(node.ident), - colon_token: (node.colon_token).map(|it| Token ! [ : ](tokens_helper(f, &it.spans))), + colon_token: (node.colon_token).map(|it| Token ! [:](tokens_helper(f, &it.spans))), bounds: FoldHelper::lift(node.bounds, |it| f.fold_type_param_bound(it)), - eq_token: (node.eq_token).map(|it| Token ! [ = ](tokens_helper(f, &it.spans))), + eq_token: (node.eq_token).map(|it| Token ! [=](tokens_helper(f, &it.spans))), default: (node.default).map(|it| f.fold_type(it)), } } @@ -3018,7 +2991,7 @@ where F: Fold + ?Sized, { TypePtr { - star_token: Token ! [ * ](tokens_helper(f, &node.star_token.spans)), + star_token: Token ! [*](tokens_helper(f, &node.star_token.spans)), const_token: (node.const_token).map(|it| Token![const](tokens_helper(f, &it.span))), mutability: (node.mutability).map(|it| Token![mut](tokens_helper(f, &it.span))), elem: Box::new(f.fold_type(*node.elem)), @@ -3030,7 +3003,7 @@ where F: Fold + ?Sized, { TypeReference { - and_token: Token ! [ & ](tokens_helper(f, &node.and_token.spans)), + and_token: Token ! [&](tokens_helper(f, &node.and_token.spans)), lifetime: (node.lifetime).map(|it| f.fold_lifetime(it)), mutability: (node.mutability).map(|it| Token![mut](tokens_helper(f, &it.span))), elem: Box::new(f.fold_type(*node.elem)), @@ -3072,9 +3045,9 @@ where F: Fold + ?Sized, { match node { - UnOp::Deref(_binding_0) => UnOp::Deref(Token ! [ * ](tokens_helper(f, &_binding_0.spans))), + UnOp::Deref(_binding_0) => UnOp::Deref(Token ! [*](tokens_helper(f, &_binding_0.spans))), UnOp::Not(_binding_0) => UnOp::Not(Token![!](tokens_helper(f, &_binding_0.spans))), - UnOp::Neg(_binding_0) => UnOp::Neg(Token ! [ - ](tokens_helper(f, &_binding_0.spans))), + UnOp::Neg(_binding_0) => UnOp::Neg(Token ! [-](tokens_helper(f, &_binding_0.spans))), } } #[cfg(feature = "full")] @@ -3083,7 +3056,7 @@ where F: Fold + ?Sized, { UseGlob { - star_token: Token ! [ * ](tokens_helper(f, &node.star_token.spans)), + star_token: Token ! [*](tokens_helper(f, &node.star_token.spans)), } } #[cfg(feature = "full")] @@ -3112,7 +3085,7 @@ where { UsePath { ident: f.fold_ident(node.ident), - colon2_token: Token ! [ :: ](tokens_helper(f, &node.colon2_token.spans)), + colon2_token: Token ! [::](tokens_helper(f, &node.colon2_token.spans)), tree: Box::new(f.fold_use_tree(*node.tree)), } } @@ -3147,7 +3120,7 @@ where { Variadic { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), - dots: Token ! [ ... ](tokens_helper(f, &node.dots.spans)), + dots: Token ! [...](tokens_helper(f, &node.dots.spans)), } } #[cfg(any(feature = "derive", feature = "full"))] @@ -3161,7 +3134,7 @@ where fields: f.fold_fields(node.fields), discriminant: (node.discriminant).map(|it| { ( - Token ! [ = ](tokens_helper(f, &(it).0.spans)), + Token ! [=](tokens_helper(f, &(it).0.spans)), f.fold_expr((it).1), ) }), diff --git a/src/gen/hash.rs b/src/gen/hash.rs new file mode 100644 index 00000000..7247174a --- /dev/null +++ b/src/gen/hash.rs @@ -0,0 +1,2867 @@ +// This file is @generated by syn-internal-codegen. +// It is not intended for manual editing. + +#[cfg(any(feature = "derive", feature = "full"))] +use crate::tt::TokenStreamHelper; +use crate::*; +use std::hash::{Hash, Hasher}; +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Abi { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.name.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for AngleBracketedGenericArguments { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.colon2_token.hash(state); + self.args.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Arm { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.pat.hash(state); + self.guard.hash(state); + self.body.hash(state); + self.comma.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for AttrStyle { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + AttrStyle::Outer => { + state.write_u8(0u8); + } + AttrStyle::Inner(_) => { + state.write_u8(1u8); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Attribute { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.style.hash(state); + self.path.hash(state); + TokenStreamHelper(&self.tokens).hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for BareFnArg { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.name.hash(state); + self.ty.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for BinOp { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + BinOp::Add(_) => { + state.write_u8(0u8); + } + BinOp::Sub(_) => { + state.write_u8(1u8); + } + BinOp::Mul(_) => { + state.write_u8(2u8); + } + BinOp::Div(_) => { + state.write_u8(3u8); + } + BinOp::Rem(_) => { + state.write_u8(4u8); + } + BinOp::And(_) => { + state.write_u8(5u8); + } + BinOp::Or(_) => { + state.write_u8(6u8); + } + BinOp::BitXor(_) => { + state.write_u8(7u8); + } + BinOp::BitAnd(_) => { + state.write_u8(8u8); + } + BinOp::BitOr(_) => { + state.write_u8(9u8); + } + BinOp::Shl(_) => { + state.write_u8(10u8); + } + BinOp::Shr(_) => { + state.write_u8(11u8); + } + BinOp::Eq(_) => { + state.write_u8(12u8); + } + BinOp::Lt(_) => { + state.write_u8(13u8); + } + BinOp::Le(_) => { + state.write_u8(14u8); + } + BinOp::Ne(_) => { + state.write_u8(15u8); + } + BinOp::Ge(_) => { + state.write_u8(16u8); + } + BinOp::Gt(_) => { + state.write_u8(17u8); + } + BinOp::AddEq(_) => { + state.write_u8(18u8); + } + BinOp::SubEq(_) => { + state.write_u8(19u8); + } + BinOp::MulEq(_) => { + state.write_u8(20u8); + } + BinOp::DivEq(_) => { + state.write_u8(21u8); + } + BinOp::RemEq(_) => { + state.write_u8(22u8); + } + BinOp::BitXorEq(_) => { + state.write_u8(23u8); + } + BinOp::BitAndEq(_) => { + state.write_u8(24u8); + } + BinOp::BitOrEq(_) => { + state.write_u8(25u8); + } + BinOp::ShlEq(_) => { + state.write_u8(26u8); + } + BinOp::ShrEq(_) => { + state.write_u8(27u8); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Binding { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.ident.hash(state); + self.ty.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Block { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.stmts.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for BoundLifetimes { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.lifetimes.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ConstParam { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.ident.hash(state); + self.ty.hash(state); + self.eq_token.hash(state); + self.default.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Constraint { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.ident.hash(state); + self.bounds.hash(state); + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Data { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + Data::Struct(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + Data::Enum(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + Data::Union(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + } + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for DataEnum { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.variants.hash(state); + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for DataStruct { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.fields.hash(state); + self.semi_token.hash(state); + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for DataUnion { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.fields.hash(state); + } +} +#[cfg(feature = "derive")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for DeriveInput { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.data.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Expr { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + #[cfg(feature = "full")] + Expr::Array(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Assign(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::AssignOp(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Async(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Await(v0) => { + state.write_u8(4u8); + v0.hash(state); + } + Expr::Binary(v0) => { + state.write_u8(5u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Block(v0) => { + state.write_u8(6u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Box(v0) => { + state.write_u8(7u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Break(v0) => { + state.write_u8(8u8); + v0.hash(state); + } + Expr::Call(v0) => { + state.write_u8(9u8); + v0.hash(state); + } + Expr::Cast(v0) => { + state.write_u8(10u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Closure(v0) => { + state.write_u8(11u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Continue(v0) => { + state.write_u8(12u8); + v0.hash(state); + } + Expr::Field(v0) => { + state.write_u8(13u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::ForLoop(v0) => { + state.write_u8(14u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Group(v0) => { + state.write_u8(15u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::If(v0) => { + state.write_u8(16u8); + v0.hash(state); + } + Expr::Index(v0) => { + state.write_u8(17u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Let(v0) => { + state.write_u8(18u8); + v0.hash(state); + } + Expr::Lit(v0) => { + state.write_u8(19u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Loop(v0) => { + state.write_u8(20u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Macro(v0) => { + state.write_u8(21u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Match(v0) => { + state.write_u8(22u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::MethodCall(v0) => { + state.write_u8(23u8); + v0.hash(state); + } + Expr::Paren(v0) => { + state.write_u8(24u8); + v0.hash(state); + } + Expr::Path(v0) => { + state.write_u8(25u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Range(v0) => { + state.write_u8(26u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Reference(v0) => { + state.write_u8(27u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Repeat(v0) => { + state.write_u8(28u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Return(v0) => { + state.write_u8(29u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Struct(v0) => { + state.write_u8(30u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Try(v0) => { + state.write_u8(31u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::TryBlock(v0) => { + state.write_u8(32u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Tuple(v0) => { + state.write_u8(33u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Type(v0) => { + state.write_u8(34u8); + v0.hash(state); + } + Expr::Unary(v0) => { + state.write_u8(35u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Unsafe(v0) => { + state.write_u8(36u8); + v0.hash(state); + } + Expr::Verbatim(v0) => { + state.write_u8(37u8); + TokenStreamHelper(v0).hash(state); + } + #[cfg(feature = "full")] + Expr::While(v0) => { + state.write_u8(38u8); + v0.hash(state); + } + #[cfg(feature = "full")] + Expr::Yield(v0) => { + state.write_u8(39u8); + v0.hash(state); + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprArray { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.elems.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprAssign { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.left.hash(state); + self.right.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprAssignOp { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.left.hash(state); + self.op.hash(state); + self.right.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprAsync { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.capture.hash(state); + self.block.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprAwait { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.base.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprBinary { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.left.hash(state); + self.op.hash(state); + self.right.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprBlock { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.label.hash(state); + self.block.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprBox { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprBreak { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.label.hash(state); + self.expr.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprCall { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.func.hash(state); + self.args.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprCast { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + self.ty.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprClosure { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.asyncness.hash(state); + self.movability.hash(state); + self.capture.hash(state); + self.inputs.hash(state); + self.output.hash(state); + self.body.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprContinue { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.label.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprField { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.base.hash(state); + self.member.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprForLoop { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.label.hash(state); + self.pat.hash(state); + self.expr.hash(state); + self.body.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprGroup { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprIf { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.cond.hash(state); + self.then_branch.hash(state); + self.else_branch.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprIndex { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + self.index.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprLet { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.pat.hash(state); + self.expr.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprLit { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.lit.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprLoop { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.label.hash(state); + self.body.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprMacro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.mac.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprMatch { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + self.arms.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprMethodCall { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.receiver.hash(state); + self.method.hash(state); + self.turbofish.hash(state); + self.args.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprParen { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprPath { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.qself.hash(state); + self.path.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprRange { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.from.hash(state); + self.limits.hash(state); + self.to.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprReference { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.mutability.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprRepeat { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + self.len.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprReturn { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprStruct { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.path.hash(state); + self.fields.hash(state); + self.dot2_token.hash(state); + self.rest.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprTry { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprTryBlock { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.block.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprTuple { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.elems.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprType { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + self.ty.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprUnary { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.op.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprUnsafe { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.block.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprWhile { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.label.hash(state); + self.cond.hash(state); + self.body.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ExprYield { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Field { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.colon_token.hash(state); + self.ty.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for FieldPat { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.member.hash(state); + self.colon_token.hash(state); + self.pat.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for FieldValue { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.member.hash(state); + self.colon_token.hash(state); + self.expr.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Fields { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + Fields::Named(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + Fields::Unnamed(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + Fields::Unit => { + state.write_u8(2u8); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for FieldsNamed { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.named.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for FieldsUnnamed { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.unnamed.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for File { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.shebang.hash(state); + self.attrs.hash(state); + self.items.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for FnArg { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + FnArg::Receiver(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + FnArg::Typed(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ForeignItem { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + ForeignItem::Fn(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + ForeignItem::Static(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + ForeignItem::Type(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + ForeignItem::Macro(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + ForeignItem::Verbatim(v0) => { + state.write_u8(4u8); + TokenStreamHelper(v0).hash(state); + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ForeignItemFn { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.sig.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ForeignItemMacro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.mac.hash(state); + self.semi_token.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ForeignItemStatic { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.mutability.hash(state); + self.ident.hash(state); + self.ty.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ForeignItemType { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for GenericArgument { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + GenericArgument::Lifetime(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + GenericArgument::Type(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + GenericArgument::Binding(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + GenericArgument::Constraint(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + GenericArgument::Const(v0) => { + state.write_u8(4u8); + v0.hash(state); + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for GenericMethodArgument { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + GenericMethodArgument::Type(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + GenericMethodArgument::Const(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for GenericParam { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + GenericParam::Type(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + GenericParam::Lifetime(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + GenericParam::Const(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Generics { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.lt_token.hash(state); + self.params.hash(state); + self.gt_token.hash(state); + self.where_clause.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ImplItem { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + ImplItem::Const(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + ImplItem::Method(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + ImplItem::Type(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + ImplItem::Macro(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + ImplItem::Verbatim(v0) => { + state.write_u8(4u8); + TokenStreamHelper(v0).hash(state); + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ImplItemConst { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.defaultness.hash(state); + self.ident.hash(state); + self.ty.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ImplItemMacro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.mac.hash(state); + self.semi_token.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ImplItemMethod { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.defaultness.hash(state); + self.sig.hash(state); + self.block.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ImplItemType { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.defaultness.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.ty.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Item { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + Item::Const(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + Item::Enum(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + Item::ExternCrate(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + Item::Fn(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + Item::ForeignMod(v0) => { + state.write_u8(4u8); + v0.hash(state); + } + Item::Impl(v0) => { + state.write_u8(5u8); + v0.hash(state); + } + Item::Macro(v0) => { + state.write_u8(6u8); + v0.hash(state); + } + Item::Macro2(v0) => { + state.write_u8(7u8); + v0.hash(state); + } + Item::Mod(v0) => { + state.write_u8(8u8); + v0.hash(state); + } + Item::Static(v0) => { + state.write_u8(9u8); + v0.hash(state); + } + Item::Struct(v0) => { + state.write_u8(10u8); + v0.hash(state); + } + Item::Trait(v0) => { + state.write_u8(11u8); + v0.hash(state); + } + Item::TraitAlias(v0) => { + state.write_u8(12u8); + v0.hash(state); + } + Item::Type(v0) => { + state.write_u8(13u8); + v0.hash(state); + } + Item::Union(v0) => { + state.write_u8(14u8); + v0.hash(state); + } + Item::Use(v0) => { + state.write_u8(15u8); + v0.hash(state); + } + Item::Verbatim(v0) => { + state.write_u8(16u8); + TokenStreamHelper(v0).hash(state); + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemConst { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.ty.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemEnum { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.variants.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemExternCrate { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.rename.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemFn { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.sig.hash(state); + self.block.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemForeignMod { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.abi.hash(state); + self.items.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemImpl { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.defaultness.hash(state); + self.unsafety.hash(state); + self.generics.hash(state); + self.trait_.hash(state); + self.self_ty.hash(state); + self.items.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemMacro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.ident.hash(state); + self.mac.hash(state); + self.semi_token.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemMacro2 { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + TokenStreamHelper(&self.rules).hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemMod { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.content.hash(state); + self.semi.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemStatic { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.mutability.hash(state); + self.ident.hash(state); + self.ty.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemStruct { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.fields.hash(state); + self.semi_token.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemTrait { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.unsafety.hash(state); + self.auto_token.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.colon_token.hash(state); + self.supertraits.hash(state); + self.items.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemTraitAlias { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.bounds.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemType { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.ty.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemUnion { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.fields.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ItemUse { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.leading_colon.hash(state); + self.tree.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Label { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.name.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for LifetimeDef { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.lifetime.hash(state); + self.colon_token.hash(state); + self.bounds.hash(state); + } +} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Lit { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + Lit::Str(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + Lit::ByteStr(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + Lit::Byte(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + Lit::Char(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + Lit::Int(v0) => { + state.write_u8(4u8); + v0.hash(state); + } + Lit::Float(v0) => { + state.write_u8(5u8); + v0.hash(state); + } + Lit::Bool(v0) => { + state.write_u8(6u8); + v0.hash(state); + } + Lit::Verbatim(v0) => { + state.write_u8(7u8); + v0.to_string().hash(state); + } + } + } +} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for LitBool { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.value.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Local { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.pat.hash(state); + self.init.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Macro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.path.hash(state); + self.delimiter.hash(state); + TokenStreamHelper(&self.tokens).hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for MacroDelimiter { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + MacroDelimiter::Paren(_) => { + state.write_u8(0u8); + } + MacroDelimiter::Brace(_) => { + state.write_u8(1u8); + } + MacroDelimiter::Bracket(_) => { + state.write_u8(2u8); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Meta { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + Meta::Path(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + Meta::List(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + Meta::NameValue(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for MetaList { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.path.hash(state); + self.nested.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for MetaNameValue { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.path.hash(state); + self.lit.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for MethodTurbofish { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.args.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for NestedMeta { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + NestedMeta::Meta(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + NestedMeta::Lit(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ParenthesizedGenericArguments { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.inputs.hash(state); + self.output.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Pat { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + Pat::Box(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + Pat::Ident(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + Pat::Lit(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + Pat::Macro(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + Pat::Or(v0) => { + state.write_u8(4u8); + v0.hash(state); + } + Pat::Path(v0) => { + state.write_u8(5u8); + v0.hash(state); + } + Pat::Range(v0) => { + state.write_u8(6u8); + v0.hash(state); + } + Pat::Reference(v0) => { + state.write_u8(7u8); + v0.hash(state); + } + Pat::Rest(v0) => { + state.write_u8(8u8); + v0.hash(state); + } + Pat::Slice(v0) => { + state.write_u8(9u8); + v0.hash(state); + } + Pat::Struct(v0) => { + state.write_u8(10u8); + v0.hash(state); + } + Pat::Tuple(v0) => { + state.write_u8(11u8); + v0.hash(state); + } + Pat::TupleStruct(v0) => { + state.write_u8(12u8); + v0.hash(state); + } + Pat::Type(v0) => { + state.write_u8(13u8); + v0.hash(state); + } + Pat::Verbatim(v0) => { + state.write_u8(14u8); + TokenStreamHelper(v0).hash(state); + } + Pat::Wild(v0) => { + state.write_u8(15u8); + v0.hash(state); + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatBox { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.pat.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatIdent { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.by_ref.hash(state); + self.mutability.hash(state); + self.ident.hash(state); + self.subpat.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatLit { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.expr.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatMacro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.mac.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatOr { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.leading_vert.hash(state); + self.cases.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatPath { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.qself.hash(state); + self.path.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatRange { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.lo.hash(state); + self.limits.hash(state); + self.hi.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatReference { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.mutability.hash(state); + self.pat.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatRest { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatSlice { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.elems.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatStruct { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.path.hash(state); + self.fields.hash(state); + self.dot2_token.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatTuple { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.elems.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatTupleStruct { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.path.hash(state); + self.pat.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatType { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.pat.hash(state); + self.ty.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatWild { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Path { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.leading_colon.hash(state); + self.segments.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PathArguments { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + PathArguments::None => { + state.write_u8(0u8); + } + PathArguments::AngleBracketed(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + PathArguments::Parenthesized(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PathSegment { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.ident.hash(state); + self.arguments.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PredicateEq { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.lhs_ty.hash(state); + self.rhs_ty.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PredicateLifetime { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.lifetime.hash(state); + self.bounds.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PredicateType { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.lifetimes.hash(state); + self.bounded_ty.hash(state); + self.bounds.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for QSelf { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.ty.hash(state); + self.position.hash(state); + self.as_token.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for RangeLimits { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + RangeLimits::HalfOpen(_) => { + state.write_u8(0u8); + } + RangeLimits::Closed(_) => { + state.write_u8(1u8); + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Receiver { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.reference.hash(state); + self.mutability.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for ReturnType { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + ReturnType::Default => { + state.write_u8(0u8); + } + ReturnType::Type(_, v1) => { + state.write_u8(1u8); + v1.hash(state); + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Signature { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.constness.hash(state); + self.asyncness.hash(state); + self.unsafety.hash(state); + self.abi.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.inputs.hash(state); + self.variadic.hash(state); + self.output.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Stmt { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + Stmt::Local(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + Stmt::Item(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + Stmt::Expr(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + Stmt::Semi(v0, _) => { + state.write_u8(3u8); + v0.hash(state); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TraitBound { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.paren_token.hash(state); + self.modifier.hash(state); + self.lifetimes.hash(state); + self.path.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TraitBoundModifier { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + TraitBoundModifier::None => { + state.write_u8(0u8); + } + TraitBoundModifier::Maybe(_) => { + state.write_u8(1u8); + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TraitItem { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + TraitItem::Const(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + TraitItem::Method(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + TraitItem::Type(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + TraitItem::Macro(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + TraitItem::Verbatim(v0) => { + state.write_u8(4u8); + TokenStreamHelper(v0).hash(state); + } + _ => unreachable!(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TraitItemConst { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.ident.hash(state); + self.ty.hash(state); + self.default.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TraitItemMacro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.mac.hash(state); + self.semi_token.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TraitItemMethod { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.sig.hash(state); + self.default.hash(state); + self.semi_token.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TraitItemType { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.ident.hash(state); + self.generics.hash(state); + self.colon_token.hash(state); + self.bounds.hash(state); + self.default.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Type { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + Type::Array(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + Type::BareFn(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + Type::Group(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + Type::ImplTrait(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + Type::Infer(v0) => { + state.write_u8(4u8); + v0.hash(state); + } + Type::Macro(v0) => { + state.write_u8(5u8); + v0.hash(state); + } + Type::Never(v0) => { + state.write_u8(6u8); + v0.hash(state); + } + Type::Paren(v0) => { + state.write_u8(7u8); + v0.hash(state); + } + Type::Path(v0) => { + state.write_u8(8u8); + v0.hash(state); + } + Type::Ptr(v0) => { + state.write_u8(9u8); + v0.hash(state); + } + Type::Reference(v0) => { + state.write_u8(10u8); + v0.hash(state); + } + Type::Slice(v0) => { + state.write_u8(11u8); + v0.hash(state); + } + Type::TraitObject(v0) => { + state.write_u8(12u8); + v0.hash(state); + } + Type::Tuple(v0) => { + state.write_u8(13u8); + v0.hash(state); + } + Type::Verbatim(v0) => { + state.write_u8(14u8); + TokenStreamHelper(v0).hash(state); + } + _ => unreachable!(), + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeArray { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.elem.hash(state); + self.len.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeBareFn { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.lifetimes.hash(state); + self.unsafety.hash(state); + self.abi.hash(state); + self.inputs.hash(state); + self.variadic.hash(state); + self.output.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeGroup { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.elem.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeImplTrait { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.bounds.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeInfer { + fn hash<H>(&self, _state: &mut H) + where + H: Hasher, + { + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeMacro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.mac.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeNever { + fn hash<H>(&self, _state: &mut H) + where + H: Hasher, + { + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeParam { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.ident.hash(state); + self.colon_token.hash(state); + self.bounds.hash(state); + self.eq_token.hash(state); + self.default.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeParamBound { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + TypeParamBound::Trait(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + TypeParamBound::Lifetime(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeParen { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.elem.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypePath { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.qself.hash(state); + self.path.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypePtr { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.const_token.hash(state); + self.mutability.hash(state); + self.elem.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeReference { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.lifetime.hash(state); + self.mutability.hash(state); + self.elem.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeSlice { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.elem.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeTraitObject { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.dyn_token.hash(state); + self.bounds.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for TypeTuple { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.elems.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for UnOp { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + UnOp::Deref(_) => { + state.write_u8(0u8); + } + UnOp::Not(_) => { + state.write_u8(1u8); + } + UnOp::Neg(_) => { + state.write_u8(2u8); + } + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for UseGlob { + fn hash<H>(&self, _state: &mut H) + where + H: Hasher, + { + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for UseGroup { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.items.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for UseName { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.ident.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for UsePath { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.ident.hash(state); + self.tree.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for UseRename { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.ident.hash(state); + self.rename.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for UseTree { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + UseTree::Path(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + UseTree::Name(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + UseTree::Rename(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + UseTree::Glob(v0) => { + state.write_u8(3u8); + v0.hash(state); + } + UseTree::Group(v0) => { + state.write_u8(4u8); + v0.hash(state); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Variadic { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Variant { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.ident.hash(state); + self.fields.hash(state); + self.discriminant.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for VisCrate { + fn hash<H>(&self, _state: &mut H) + where + H: Hasher, + { + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for VisPublic { + fn hash<H>(&self, _state: &mut H) + where + H: Hasher, + { + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for VisRestricted { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.in_token.hash(state); + self.path.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for Visibility { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + Visibility::Public(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + Visibility::Crate(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + Visibility::Restricted(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + Visibility::Inherited => { + state.write_u8(3u8); + } + } + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for WhereClause { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.predicates.hash(state); + } +} +#[cfg(any(feature = "derive", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for WherePredicate { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + match self { + WherePredicate::Type(v0) => { + state.write_u8(0u8); + v0.hash(state); + } + WherePredicate::Lifetime(v0) => { + state.write_u8(1u8); + v0.hash(state); + } + WherePredicate::Eq(v0) => { + state.write_u8(2u8); + v0.hash(state); + } + } + } +} diff --git a/1.0.7/src/gen/visit.rs b/src/gen/visit.rs index b667f530..24d34b74 100644 --- a/1.0.7/src/gen/visit.rs +++ b/src/gen/visit.rs @@ -20,7 +20,6 @@ macro_rules! full { unreachable!() }; } -#[cfg(any(feature = "full", feature = "derive"))] macro_rules! skip { ($($tt:tt)*) => {}; } @@ -30,7 +29,7 @@ macro_rules! skip { /// /// [module documentation]: self /// -/// *This trait is available if Syn is built with the `"visit"` feature.* +/// *This trait is available only if Syn is built with the `"visit"` feature.* pub trait Visit<'ast> { #[cfg(any(feature = "derive", feature = "full"))] fn visit_abi(&mut self, i: &'ast Abi) { @@ -434,35 +433,27 @@ pub trait Visit<'ast> { fn visit_lifetime_def(&mut self, i: &'ast LifetimeDef) { visit_lifetime_def(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit(&mut self, i: &'ast Lit) { visit_lit(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_bool(&mut self, i: &'ast LitBool) { visit_lit_bool(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_byte(&mut self, i: &'ast LitByte) { visit_lit_byte(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_byte_str(&mut self, i: &'ast LitByteStr) { visit_lit_byte_str(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_char(&mut self, i: &'ast LitChar) { visit_lit_char(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_float(&mut self, i: &'ast LitFloat) { visit_lit_float(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_int(&mut self, i: &'ast LitInt) { visit_lit_int(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_str(&mut self, i: &'ast LitStr) { visit_lit_str(self, i) } @@ -2537,7 +2528,6 @@ where } } } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit<'ast, V>(v: &mut V, node: &'ast Lit) where V: Visit<'ast> + ?Sized, @@ -2569,7 +2559,6 @@ where } } } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_bool<'ast, V>(v: &mut V, node: &'ast LitBool) where V: Visit<'ast> + ?Sized, @@ -2577,37 +2566,31 @@ where skip!(node.value); v.visit_span(&node.span); } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_byte<'ast, V>(v: &mut V, node: &'ast LitByte) where V: Visit<'ast> + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_byte_str<'ast, V>(v: &mut V, node: &'ast LitByteStr) where V: Visit<'ast> + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_char<'ast, V>(v: &mut V, node: &'ast LitChar) where V: Visit<'ast> + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_float<'ast, V>(v: &mut V, node: &'ast LitFloat) where V: Visit<'ast> + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_int<'ast, V>(v: &mut V, node: &'ast LitInt) where V: Visit<'ast> + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_str<'ast, V>(v: &mut V, node: &'ast LitStr) where V: Visit<'ast> + ?Sized, diff --git a/1.0.7/src/gen/visit_mut.rs b/src/gen/visit_mut.rs index 5cddb827..5ce11f0b 100644 --- a/1.0.7/src/gen/visit_mut.rs +++ b/src/gen/visit_mut.rs @@ -20,7 +20,6 @@ macro_rules! full { unreachable!() }; } -#[cfg(any(feature = "full", feature = "derive"))] macro_rules! skip { ($($tt:tt)*) => {}; } @@ -31,7 +30,7 @@ macro_rules! skip { /// /// [module documentation]: self /// -/// *This trait is available if Syn is built with the `"visit-mut"` feature.* +/// *This trait is available only if Syn is built with the `"visit-mut"` feature.* pub trait VisitMut { #[cfg(any(feature = "derive", feature = "full"))] fn visit_abi_mut(&mut self, i: &mut Abi) { @@ -438,35 +437,27 @@ pub trait VisitMut { fn visit_lifetime_def_mut(&mut self, i: &mut LifetimeDef) { visit_lifetime_def_mut(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_mut(&mut self, i: &mut Lit) { visit_lit_mut(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_bool_mut(&mut self, i: &mut LitBool) { visit_lit_bool_mut(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_byte_mut(&mut self, i: &mut LitByte) { visit_lit_byte_mut(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_byte_str_mut(&mut self, i: &mut LitByteStr) { visit_lit_byte_str_mut(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_char_mut(&mut self, i: &mut LitChar) { visit_lit_char_mut(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_float_mut(&mut self, i: &mut LitFloat) { visit_lit_float_mut(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_int_mut(&mut self, i: &mut LitInt) { visit_lit_int_mut(self, i) } - #[cfg(any(feature = "derive", feature = "full"))] fn visit_lit_str_mut(&mut self, i: &mut LitStr) { visit_lit_str_mut(self, i) } @@ -2543,7 +2534,6 @@ where } } } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_mut<V>(v: &mut V, node: &mut Lit) where V: VisitMut + ?Sized, @@ -2575,7 +2565,6 @@ where } } } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_bool_mut<V>(v: &mut V, node: &mut LitBool) where V: VisitMut + ?Sized, @@ -2583,37 +2572,31 @@ where skip!(node.value); v.visit_span_mut(&mut node.span); } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_byte_mut<V>(v: &mut V, node: &mut LitByte) where V: VisitMut + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_byte_str_mut<V>(v: &mut V, node: &mut LitByteStr) where V: VisitMut + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_char_mut<V>(v: &mut V, node: &mut LitChar) where V: VisitMut + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_float_mut<V>(v: &mut V, node: &mut LitFloat) where V: VisitMut + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_int_mut<V>(v: &mut V, node: &mut LitInt) where V: VisitMut + ?Sized, { } -#[cfg(any(feature = "derive", feature = "full"))] pub fn visit_lit_str_mut<V>(v: &mut V, node: &mut LitStr) where V: VisitMut + ?Sized, diff --git a/1.0.7/src/gen_helper.rs b/src/gen_helper.rs index b2796126..b2796126 100644 --- a/1.0.7/src/gen_helper.rs +++ b/src/gen_helper.rs diff --git a/1.0.7/src/generics.rs b/src/generics.rs index d357cbbc..de0772a7 100644 --- a/1.0.7/src/generics.rs +++ b/src/generics.rs @@ -1,13 +1,17 @@ use super::*; use crate::punctuated::{Iter, IterMut, Punctuated}; +#[cfg(all(feature = "printing", feature = "extra-traits"))] +use std::fmt::{self, Debug}; +#[cfg(all(feature = "printing", feature = "extra-traits"))] +use std::hash::{Hash, Hasher}; ast_struct! { /// Lifetimes and type parameters attached to a declaration of a function, /// enum, trait, etc. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* - #[derive(Default)] + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct Generics { pub lt_token: Option<Token![<]>, pub params: Punctuated<GenericParam, Token![,]>, @@ -20,17 +24,15 @@ ast_enum_of_structs! { /// A generic type parameter, lifetime, or const generic: `T: Into<String>`, /// `'a: 'b`, `const LEN: usize`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum GenericParam { /// A generic type parameter: `T: Into<String>`. Type(TypeParam), @@ -46,8 +48,9 @@ ast_enum_of_structs! { ast_struct! { /// A generic type parameter: `T: Into<String>`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeParam { pub attrs: Vec<Attribute>, pub ident: Ident, @@ -61,8 +64,9 @@ ast_struct! { ast_struct! { /// A lifetime definition: `'a: 'b + 'c + 'd`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct LifetimeDef { pub attrs: Vec<Attribute>, pub lifetime: Lifetime, @@ -74,8 +78,9 @@ ast_struct! { ast_struct! { /// A const generic parameter: `const LENGTH: usize`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ConstParam { pub attrs: Vec<Attribute>, pub const_token: Token![const], @@ -87,6 +92,17 @@ ast_struct! { } } +impl Default for Generics { + fn default() -> Self { + Generics { + lt_token: None, + params: Punctuated::new(), + gt_token: None, + where_clause: None, + } + } +} + impl Generics { /// Returns an /// <code @@ -280,29 +296,35 @@ impl<'a> Iterator for ConstParamsMut<'a> { /// Returned by `Generics::split_for_impl`. /// -/// *This type is available if Syn is built with the `"derive"` or `"full"` +/// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature and the `"printing"` feature.* #[cfg(feature = "printing")] -#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] -#[cfg_attr(feature = "clone-impls", derive(Clone))] +#[cfg_attr( + doc_cfg, + doc(cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))) +)] pub struct ImplGenerics<'a>(&'a Generics); /// Returned by `Generics::split_for_impl`. /// -/// *This type is available if Syn is built with the `"derive"` or `"full"` +/// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature and the `"printing"` feature.* #[cfg(feature = "printing")] -#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] -#[cfg_attr(feature = "clone-impls", derive(Clone))] +#[cfg_attr( + doc_cfg, + doc(cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))) +)] pub struct TypeGenerics<'a>(&'a Generics); /// Returned by `TypeGenerics::as_turbofish`. /// -/// *This type is available if Syn is built with the `"derive"` or `"full"` +/// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature and the `"printing"` feature.* #[cfg(feature = "printing")] -#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] -#[cfg_attr(feature = "clone-impls", derive(Clone))] +#[cfg_attr( + doc_cfg, + doc(cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))) +)] pub struct Turbofish<'a>(&'a Generics); #[cfg(feature = "printing")] @@ -326,8 +348,12 @@ impl Generics { /// # ; /// ``` /// - /// *This method is available if Syn is built with the `"derive"` or + /// *This method is available only if Syn is built with the `"derive"` or /// `"full"` feature and the `"printing"` feature.* + #[cfg_attr( + doc_cfg, + doc(cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))) + )] pub fn split_for_impl(&self) -> (ImplGenerics, TypeGenerics, Option<&WhereClause>) { ( ImplGenerics(self), @@ -338,10 +364,61 @@ impl Generics { } #[cfg(feature = "printing")] +macro_rules! generics_wrapper_impls { + ($ty:ident) => { + #[cfg(feature = "clone-impls")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] + impl<'a> Clone for $ty<'a> { + fn clone(&self) -> Self { + $ty(self.0) + } + } + + #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] + impl<'a> Debug for $ty<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_tuple(stringify!($ty)) + .field(self.0) + .finish() + } + } + + #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] + impl<'a> Eq for $ty<'a> {} + + #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] + impl<'a> PartialEq for $ty<'a> { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } + } + + #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] + impl<'a> Hash for $ty<'a> { + fn hash<H: Hasher>(&self, state: &mut H) { + self.0.hash(state); + } + } + }; +} + +#[cfg(feature = "printing")] +generics_wrapper_impls!(ImplGenerics); +#[cfg(feature = "printing")] +generics_wrapper_impls!(TypeGenerics); +#[cfg(feature = "printing")] +generics_wrapper_impls!(Turbofish); + +#[cfg(feature = "printing")] impl<'a> TypeGenerics<'a> { /// Turn a type's generics like `<X, Y>` into a turbofish like `::<X, Y>`. /// - /// *This method is available if Syn is built with the `"derive"` or + /// *This method is available only if Syn is built with the `"derive"` or /// `"full"` feature and the `"printing"` feature.* pub fn as_turbofish(&self) -> Turbofish { Turbofish(self.0) @@ -351,9 +428,9 @@ impl<'a> TypeGenerics<'a> { ast_struct! { /// A set of bound lifetimes: `for<'a, 'b, 'c>`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* - #[derive(Default)] + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct BoundLifetimes { pub for_token: Token![for], pub lt_token: Token![<], @@ -362,6 +439,17 @@ ast_struct! { } } +impl Default for BoundLifetimes { + fn default() -> Self { + BoundLifetimes { + for_token: Default::default(), + lt_token: Default::default(), + lifetimes: Punctuated::new(), + gt_token: Default::default(), + } + } +} + impl LifetimeDef { pub fn new(lifetime: Lifetime) -> Self { LifetimeDef { @@ -389,8 +477,9 @@ impl From<Ident> for TypeParam { ast_enum_of_structs! { /// A trait or lifetime used as a bound on a type parameter. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum TypeParamBound { Trait(TraitBound), Lifetime(Lifetime), @@ -400,8 +489,9 @@ ast_enum_of_structs! { ast_struct! { /// A trait used as a bound on a type parameter. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TraitBound { pub paren_token: Option<token::Paren>, pub modifier: TraitBoundModifier, @@ -416,9 +506,9 @@ ast_enum! { /// A modifier on a trait bound, currently only used for the `?` in /// `?Sized`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* - #[cfg_attr(feature = "clone-impls", derive(Copy))] + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum TraitBoundModifier { None, Maybe(Token![?]), @@ -429,8 +519,9 @@ ast_struct! { /// A `where` clause in a definition: `where T: Deserialize<'de>, D: /// 'static`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct WhereClause { pub where_token: Token![where], pub predicates: Punctuated<WherePredicate, Token![,]>, @@ -440,17 +531,15 @@ ast_struct! { ast_enum_of_structs! { /// A single predicate in a `where` clause: `T: Deserialize<'de>`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum WherePredicate { /// A type predicate in a `where` clause: `for<'c> Foo<'c>: Trait<'c>`. Type(PredicateType), @@ -466,8 +555,9 @@ ast_enum_of_structs! { ast_struct! { /// A type predicate in a `where` clause: `for<'c> Foo<'c>: Trait<'c>`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct PredicateType { /// Any lifetimes from a `for` binding pub lifetimes: Option<BoundLifetimes>, @@ -482,8 +572,9 @@ ast_struct! { ast_struct! { /// A lifetime predicate in a `where` clause: `'a: 'b + 'c`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct PredicateLifetime { pub lifetime: Lifetime, pub colon_token: Token![:], @@ -494,8 +585,9 @@ ast_struct! { ast_struct! { /// An equality predicate in a `where` clause (unsupported). /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct PredicateEq { pub lhs_ty: Type, pub eq_token: Token![=], @@ -506,9 +598,10 @@ ast_struct! { #[cfg(feature = "parsing")] pub mod parsing { use super::*; - + use crate::ext::IdentExt; use crate::parse::{Parse, ParseStream, Result}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Generics { fn parse(input: ParseStream) -> Result<Self> { if !input.peek(Token![<]) { @@ -518,8 +611,6 @@ pub mod parsing { let lt_token: Token![<] = input.parse()?; let mut params = Punctuated::new(); - let mut allow_lifetime_param = true; - let mut allow_type_param = true; loop { if input.peek(Token![>]) { break; @@ -527,24 +618,30 @@ pub mod parsing { let attrs = input.call(Attribute::parse_outer)?; let lookahead = input.lookahead1(); - if allow_lifetime_param && lookahead.peek(Lifetime) { + if lookahead.peek(Lifetime) { params.push_value(GenericParam::Lifetime(LifetimeDef { attrs, ..input.parse()? })); - } else if allow_type_param && lookahead.peek(Ident) { - allow_lifetime_param = false; + } else if lookahead.peek(Ident) { params.push_value(GenericParam::Type(TypeParam { attrs, ..input.parse()? })); } else if lookahead.peek(Token![const]) { - allow_lifetime_param = false; - allow_type_param = false; params.push_value(GenericParam::Const(ConstParam { attrs, ..input.parse()? })); + } else if input.peek(Token![_]) { + params.push_value(GenericParam::Type(TypeParam { + attrs, + ident: input.call(Ident::parse_any)?, + colon_token: None, + bounds: Punctuated::new(), + eq_token: None, + default: None, + })); } else { return Err(lookahead.error()); } @@ -567,6 +664,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for GenericParam { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -593,6 +691,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for LifetimeDef { fn parse(input: ParseStream) -> Result<Self> { let has_colon; @@ -630,6 +729,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for BoundLifetimes { fn parse(input: ParseStream) -> Result<Self> { Ok(BoundLifetimes { @@ -651,6 +751,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Option<BoundLifetimes> { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Token![for]) { @@ -661,63 +762,61 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeParam { fn parse(input: ParseStream) -> Result<Self> { - let has_colon; - let has_default; - Ok(TypeParam { - attrs: input.call(Attribute::parse_outer)?, - ident: input.parse()?, - colon_token: { - if input.peek(Token![:]) { - has_colon = true; - Some(input.parse()?) - } else { - has_colon = false; - None - } - }, - bounds: { - let mut bounds = Punctuated::new(); - if has_colon { - loop { - if input.peek(Token![,]) - || input.peek(Token![>]) - || input.peek(Token![=]) - { - break; - } - let value = input.parse()?; - bounds.push_value(value); - if !input.peek(Token![+]) { - break; - } - let punct = input.parse()?; - bounds.push_punct(punct); - } + let attrs = input.call(Attribute::parse_outer)?; + let ident: Ident = input.parse()?; + let colon_token: Option<Token![:]> = input.parse()?; + + let begin_bound = input.fork(); + let mut is_maybe_const = false; + let mut bounds = Punctuated::new(); + if colon_token.is_some() { + loop { + if input.peek(Token![,]) || input.peek(Token![>]) || input.peek(Token![=]) { + break; } - bounds - }, - eq_token: { - if input.peek(Token![=]) { - has_default = true; - Some(input.parse()?) - } else { - has_default = false; - None + if input.peek(Token![?]) && input.peek2(Token![const]) { + input.parse::<Token![?]>()?; + input.parse::<Token![const]>()?; + is_maybe_const = true; } - }, - default: { - if has_default { - Some(input.parse()?) - } else { - None + let value: TypeParamBound = input.parse()?; + bounds.push_value(value); + if !input.peek(Token![+]) { + break; } - }, + let punct: Token![+] = input.parse()?; + bounds.push_punct(punct); + } + } + + let mut eq_token: Option<Token![=]> = input.parse()?; + let mut default = if eq_token.is_some() { + Some(input.parse::<Type>()?) + } else { + None + }; + + if is_maybe_const { + bounds.clear(); + eq_token = None; + default = Some(Type::Verbatim(verbatim::between(begin_bound, input))); + } + + Ok(TypeParam { + attrs, + ident, + colon_token, + bounds, + eq_token, + default, }) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeParamBound { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Lifetime) { @@ -736,6 +835,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TraitBound { fn parse(input: ParseStream) -> Result<Self> { let modifier: TraitBoundModifier = input.parse()?; @@ -756,6 +856,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TraitBoundModifier { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Token![?]) { @@ -766,6 +867,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ConstParam { fn parse(input: ParseStream) -> Result<Self> { let mut default = None; @@ -778,7 +880,7 @@ pub mod parsing { eq_token: { if input.peek(Token![=]) { let eq_token = input.parse()?; - default = Some(input.parse::<Expr>()?); + default = Some(path::parsing::const_argument(input)?); Some(eq_token) } else { None @@ -789,6 +891,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for WhereClause { fn parse(input: ParseStream) -> Result<Self> { Ok(WhereClause { @@ -819,6 +922,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Option<WhereClause> { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Token![where]) { @@ -829,6 +933,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for WherePredicate { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Lifetime) && input.peek2(Token![:]) { @@ -894,13 +999,14 @@ pub mod parsing { #[cfg(feature = "printing")] mod printing { use super::*; - - use proc_macro2::TokenStream; - use quote::{ToTokens, TokenStreamExt}; - use crate::attr::FilterAttrs; use crate::print::TokensOrDefault; + use proc_macro2::TokenStream; + #[cfg(feature = "full")] + use proc_macro2::TokenTree; + use quote::{ToTokens, TokenStreamExt}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Generics { fn to_tokens(&self, tokens: &mut TokenStream) { if self.params.is_empty() { @@ -1050,6 +1156,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for BoundLifetimes { fn to_tokens(&self, tokens: &mut TokenStream) { self.for_token.to_tokens(tokens); @@ -1059,6 +1166,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for LifetimeDef { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -1070,6 +1178,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeParam { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -1078,13 +1187,37 @@ mod printing { TokensOrDefault(&self.colon_token).to_tokens(tokens); self.bounds.to_tokens(tokens); } - if self.default.is_some() { + if let Some(default) = &self.default { + #[cfg(feature = "full")] + { + if self.eq_token.is_none() { + if let Type::Verbatim(default) = default { + let mut iter = default.clone().into_iter().peekable(); + while let Some(token) = iter.next() { + if let TokenTree::Punct(q) = token { + if q.as_char() == '?' { + if let Some(TokenTree::Ident(c)) = iter.peek() { + if c == "const" { + if self.bounds.is_empty() { + TokensOrDefault(&self.colon_token) + .to_tokens(tokens); + } + return default.to_tokens(tokens); + } + } + } + } + } + } + } + } TokensOrDefault(&self.eq_token).to_tokens(tokens); - self.default.to_tokens(tokens); + default.to_tokens(tokens); } } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TraitBound { fn to_tokens(&self, tokens: &mut TokenStream) { let to_tokens = |tokens: &mut TokenStream| { @@ -1099,6 +1232,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TraitBoundModifier { fn to_tokens(&self, tokens: &mut TokenStream) { match self { @@ -1108,6 +1242,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ConstParam { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -1115,13 +1250,14 @@ mod printing { self.ident.to_tokens(tokens); self.colon_token.to_tokens(tokens); self.ty.to_tokens(tokens); - if self.default.is_some() { + if let Some(default) = &self.default { TokensOrDefault(&self.eq_token).to_tokens(tokens); - self.default.to_tokens(tokens); + default.to_tokens(tokens); } } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for WhereClause { fn to_tokens(&self, tokens: &mut TokenStream) { if !self.predicates.is_empty() { @@ -1131,6 +1267,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PredicateType { fn to_tokens(&self, tokens: &mut TokenStream) { self.lifetimes.to_tokens(tokens); @@ -1140,6 +1277,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PredicateLifetime { fn to_tokens(&self, tokens: &mut TokenStream) { self.lifetime.to_tokens(tokens); @@ -1148,6 +1286,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PredicateEq { fn to_tokens(&self, tokens: &mut TokenStream) { self.lhs_ty.to_tokens(tokens); diff --git a/1.0.7/src/group.rs b/src/group.rs index ed5b151c..6b057101 100644 --- a/1.0.7/src/group.rs +++ b/src/group.rs @@ -1,8 +1,7 @@ -use proc_macro2::{Delimiter, Span}; - use crate::error::Result; use crate::parse::ParseBuffer; use crate::token; +use proc_macro2::{Delimiter, Span}; // Not public API. #[doc(hidden)] @@ -134,15 +133,16 @@ fn parse_delimited<'a>( /// # } /// ``` #[macro_export] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] macro_rules! parenthesized { ($content:ident in $cursor:expr) => { match $crate::group::parse_parens(&$cursor) { - $crate::export::Ok(parens) => { + $crate::__private::Ok(parens) => { $content = parens.content; parens.token } - $crate::export::Err(error) => { - return $crate::export::Err(error); + $crate::__private::Err(error) => { + return $crate::__private::Err(error); } } }; @@ -211,15 +211,16 @@ macro_rules! parenthesized { /// # } /// ``` #[macro_export] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] macro_rules! braced { ($content:ident in $cursor:expr) => { match $crate::group::parse_braces(&$cursor) { - $crate::export::Ok(braces) => { + $crate::__private::Ok(braces) => { $content = braces.content; braces.token } - $crate::export::Err(error) => { - return $crate::export::Err(error); + $crate::__private::Err(error) => { + return $crate::__private::Err(error); } } }; @@ -265,15 +266,16 @@ macro_rules! braced { /// # } /// ``` #[macro_export] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] macro_rules! bracketed { ($content:ident in $cursor:expr) => { match $crate::group::parse_brackets(&$cursor) { - $crate::export::Ok(brackets) => { + $crate::__private::Ok(brackets) => { $content = brackets.content; brackets.token } - $crate::export::Err(error) => { - return $crate::export::Err(error); + $crate::__private::Err(error) => { + return $crate::__private::Err(error); } } }; diff --git a/1.0.7/src/ident.rs b/src/ident.rs index 4ca7484e..61e08877 100644 --- a/1.0.7/src/ident.rs +++ b/src/ident.rs @@ -36,6 +36,7 @@ fn accept_as_ident(ident: &Ident) -> bool { } #[cfg(feature = "parsing")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Ident { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| { diff --git a/1.0.7/src/item.rs b/src/item.rs index a1ce7bfb..10479ab4 100644 --- a/1.0.7/src/item.rs +++ b/src/item.rs @@ -3,25 +3,21 @@ use crate::derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput}; use crate::punctuated::Punctuated; use proc_macro2::TokenStream; -#[cfg(feature = "extra-traits")] -use crate::tt::TokenStreamHelper; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; +#[cfg(feature = "parsing")] +use std::mem; ast_enum_of_structs! { /// Things that can appear directly inside of a module or scope. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Item #manual_extra_traits { + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub enum Item { /// A constant item: `const MAX: u16 = 65535`. Const(ItemConst), @@ -75,15 +71,39 @@ ast_enum_of_structs! { /// Tokens forming an item not interpreted by Syn. Verbatim(TokenStream), + // The following is the only supported idiom for exhaustive matching of + // this enum. + // + // match expr { + // Item::Const(e) => {...} + // Item::Enum(e) => {...} + // ... + // Item::Verbatim(e) => {...} + // + // #[cfg(test)] + // Item::__TestExhaustive(_) => unimplemented!(), + // #[cfg(not(test))] + // _ => { /* some sane fallback */ } + // } + // + // This way we fail your tests but don't break your library when adding + // a variant. You will be notified by a test failure when a variant is + // added, so that you can add code to handle it, but your library will + // continue to compile and work for downstream users in the interim. + // + // Once `deny(reachable)` is available in rustc, Item will be + // reimplemented as a non_exhaustive enum. + // https://github.com/rust-lang/rust/issues/44109#issuecomment-521781237 #[doc(hidden)] - __Nonexhaustive, + __TestExhaustive(crate::private), } } ast_struct! { /// A constant item: `const MAX: u16 = 65535`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemConst { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -100,7 +120,8 @@ ast_struct! { ast_struct! { /// An enum definition: `enum Foo<A, B> { A(A), B(B) }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemEnum { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -115,7 +136,8 @@ ast_struct! { ast_struct! { /// An `extern crate` item: `extern crate serde`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemExternCrate { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -131,7 +153,8 @@ ast_struct! { /// A free-standing function: `fn process(n: usize) -> Result<()> { ... /// }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemFn { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -143,7 +166,8 @@ ast_struct! { ast_struct! { /// A block of foreign items: `extern "C" { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemForeignMod { pub attrs: Vec<Attribute>, pub abi: Abi, @@ -156,7 +180,8 @@ ast_struct! { /// An impl block providing trait or associated items: `impl<A> Trait /// for Data<A> { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemImpl { pub attrs: Vec<Attribute>, pub defaultness: Option<Token![default]>, @@ -175,7 +200,8 @@ ast_struct! { ast_struct! { /// A macro invocation, which includes `macro_rules!` definitions. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemMacro { pub attrs: Vec<Attribute>, /// The `example` in `macro_rules! example { ... }`. @@ -188,8 +214,9 @@ ast_struct! { ast_struct! { /// A 2.0-style declarative macro introduced by the `macro` keyword. /// - /// *This type is available if Syn is built with the `"full"` feature.* - pub struct ItemMacro2 #manual_extra_traits { + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub struct ItemMacro2 { pub attrs: Vec<Attribute>, pub vis: Visibility, pub macro_token: Token![macro], @@ -201,7 +228,8 @@ ast_struct! { ast_struct! { /// A module or module declaration: `mod m` or `mod m { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemMod { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -215,7 +243,8 @@ ast_struct! { ast_struct! { /// A static item: `static BIKE: Shed = Shed(42)`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemStatic { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -233,7 +262,8 @@ ast_struct! { ast_struct! { /// A struct definition: `struct Foo<A> { x: A }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemStruct { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -248,7 +278,8 @@ ast_struct! { ast_struct! { /// A trait definition: `pub trait Iterator { ... }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemTrait { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -267,7 +298,8 @@ ast_struct! { ast_struct! { /// A trait alias: `pub trait SharableIterator = Iterator + Sync`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemTraitAlias { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -283,7 +315,8 @@ ast_struct! { ast_struct! { /// A type alias: `type Result<T> = std::result::Result<T, MyError>`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemType { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -299,7 +332,8 @@ ast_struct! { ast_struct! { /// A union definition: `union Foo<A, B> { x: A, y: B }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemUnion { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -313,7 +347,8 @@ ast_struct! { ast_struct! { /// A use declaration: `use std::collections::HashMap`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ItemUse { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -324,145 +359,36 @@ ast_struct! { } } -#[cfg(feature = "extra-traits")] -impl Eq for Item {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Item { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Item::Const(this), Item::Const(other)) => this == other, - (Item::Enum(this), Item::Enum(other)) => this == other, - (Item::ExternCrate(this), Item::ExternCrate(other)) => this == other, - (Item::Fn(this), Item::Fn(other)) => this == other, - (Item::ForeignMod(this), Item::ForeignMod(other)) => this == other, - (Item::Impl(this), Item::Impl(other)) => this == other, - (Item::Macro(this), Item::Macro(other)) => this == other, - (Item::Macro2(this), Item::Macro2(other)) => this == other, - (Item::Mod(this), Item::Mod(other)) => this == other, - (Item::Static(this), Item::Static(other)) => this == other, - (Item::Struct(this), Item::Struct(other)) => this == other, - (Item::Trait(this), Item::Trait(other)) => this == other, - (Item::TraitAlias(this), Item::TraitAlias(other)) => this == other, - (Item::Type(this), Item::Type(other)) => this == other, - (Item::Union(this), Item::Union(other)) => this == other, - (Item::Use(this), Item::Use(other)) => this == other, - (Item::Verbatim(this), Item::Verbatim(other)) => { - TokenStreamHelper(this) == TokenStreamHelper(other) - } - _ => false, - } - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Item { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { +impl Item { + #[cfg(feature = "parsing")] + pub(crate) fn replace_attrs(&mut self, new: Vec<Attribute>) -> Vec<Attribute> { match self { - Item::Const(item) => { - state.write_u8(0); - item.hash(state); - } - Item::Enum(item) => { - state.write_u8(1); - item.hash(state); - } - Item::ExternCrate(item) => { - state.write_u8(2); - item.hash(state); - } - Item::Fn(item) => { - state.write_u8(3); - item.hash(state); - } - Item::ForeignMod(item) => { - state.write_u8(4); - item.hash(state); - } - Item::Impl(item) => { - state.write_u8(5); - item.hash(state); - } - Item::Macro(item) => { - state.write_u8(6); - item.hash(state); - } - Item::Macro2(item) => { - state.write_u8(7); - item.hash(state); - } - Item::Mod(item) => { - state.write_u8(8); - item.hash(state); - } - Item::Static(item) => { - state.write_u8(9); - item.hash(state); - } - Item::Struct(item) => { - state.write_u8(10); - item.hash(state); - } - Item::Trait(item) => { - state.write_u8(11); - item.hash(state); - } - Item::TraitAlias(item) => { - state.write_u8(12); - item.hash(state); - } - Item::Type(item) => { - state.write_u8(13); - item.hash(state); - } - Item::Union(item) => { - state.write_u8(14); - item.hash(state); - } - Item::Use(item) => { - state.write_u8(15); - item.hash(state); - } - Item::Verbatim(item) => { - state.write_u8(16); - TokenStreamHelper(item).hash(state); - } - Item::__Nonexhaustive => unreachable!(), + Item::ExternCrate(ItemExternCrate { attrs, .. }) + | Item::Use(ItemUse { attrs, .. }) + | Item::Static(ItemStatic { attrs, .. }) + | Item::Const(ItemConst { attrs, .. }) + | Item::Fn(ItemFn { attrs, .. }) + | Item::Mod(ItemMod { attrs, .. }) + | Item::ForeignMod(ItemForeignMod { attrs, .. }) + | Item::Type(ItemType { attrs, .. }) + | Item::Struct(ItemStruct { attrs, .. }) + | Item::Enum(ItemEnum { attrs, .. }) + | Item::Union(ItemUnion { attrs, .. }) + | Item::Trait(ItemTrait { attrs, .. }) + | Item::TraitAlias(ItemTraitAlias { attrs, .. }) + | Item::Impl(ItemImpl { attrs, .. }) + | Item::Macro(ItemMacro { attrs, .. }) + | Item::Macro2(ItemMacro2 { attrs, .. }) => mem::replace(attrs, new), + Item::Verbatim(_) => Vec::new(), + + #[cfg(test)] + Item::__TestExhaustive(_) => unimplemented!(), + #[cfg(not(test))] + _ => unreachable!(), } } } -#[cfg(feature = "extra-traits")] -impl Eq for ItemMacro2 {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for ItemMacro2 { - fn eq(&self, other: &Self) -> bool { - self.attrs == other.attrs - && self.vis == other.vis - && self.macro_token == other.macro_token - && self.ident == other.ident - && TokenStreamHelper(&self.rules) == TokenStreamHelper(&other.rules) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for ItemMacro2 { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - self.attrs.hash(state); - self.vis.hash(state); - self.macro_token.hash(state); - self.ident.hash(state); - TokenStreamHelper(&self.rules).hash(state); - } -} - impl From<DeriveInput> for Item { fn from(input: DeriveInput) -> Item { match input.data { @@ -546,16 +472,14 @@ impl From<ItemUnion> for DeriveInput { ast_enum_of_structs! { /// A suffix of an import tree in a `use` item: `Type as Renamed` or `*`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub enum UseTree { /// A path prefix of imports in a `use` item: `std::...`. Path(UsePath), @@ -577,7 +501,8 @@ ast_enum_of_structs! { ast_struct! { /// A path prefix of imports in a `use` item: `std::...`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct UsePath { pub ident: Ident, pub colon2_token: Token![::], @@ -588,7 +513,8 @@ ast_struct! { ast_struct! { /// An identifier imported by a `use` item: `HashMap`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct UseName { pub ident: Ident, } @@ -597,7 +523,8 @@ ast_struct! { ast_struct! { /// An renamed identifier imported by a `use` item: `HashMap as Map`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct UseRename { pub ident: Ident, pub as_token: Token![as], @@ -608,7 +535,8 @@ ast_struct! { ast_struct! { /// A glob import in a `use` item: `*`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct UseGlob { pub star_token: Token![*], } @@ -617,7 +545,8 @@ ast_struct! { ast_struct! { /// A braced group of imports in a `use` item: `{A, B, C}`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct UseGroup { pub brace_token: token::Brace, pub items: Punctuated<UseTree, Token![,]>, @@ -627,17 +556,15 @@ ast_struct! { ast_enum_of_structs! { /// An item within an `extern` block. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum ForeignItem #manual_extra_traits { + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub enum ForeignItem { /// A foreign function in an `extern` block. Fn(ForeignItemFn), @@ -653,15 +580,39 @@ ast_enum_of_structs! { /// Tokens in an `extern` block not interpreted by Syn. Verbatim(TokenStream), + // The following is the only supported idiom for exhaustive matching of + // this enum. + // + // match expr { + // ForeignItem::Fn(e) => {...} + // ForeignItem::Static(e) => {...} + // ... + // ForeignItem::Verbatim(e) => {...} + // + // #[cfg(test)] + // ForeignItem::__TestExhaustive(_) => unimplemented!(), + // #[cfg(not(test))] + // _ => { /* some sane fallback */ } + // } + // + // This way we fail your tests but don't break your library when adding + // a variant. You will be notified by a test failure when a variant is + // added, so that you can add code to handle it, but your library will + // continue to compile and work for downstream users in the interim. + // + // Once `deny(reachable)` is available in rustc, ForeignItem will be + // reimplemented as a non_exhaustive enum. + // https://github.com/rust-lang/rust/issues/44109#issuecomment-521781237 #[doc(hidden)] - __Nonexhaustive, + __TestExhaustive(crate::private), } } ast_struct! { /// A foreign function in an `extern` block. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ForeignItemFn { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -673,7 +624,8 @@ ast_struct! { ast_struct! { /// A foreign static item in an `extern` block: `static ext: u8`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ForeignItemStatic { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -689,7 +641,8 @@ ast_struct! { ast_struct! { /// A foreign type in an `extern` block: `type void`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ForeignItemType { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -702,7 +655,8 @@ ast_struct! { ast_struct! { /// A macro invocation within an extern block. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ForeignItemMacro { pub attrs: Vec<Attribute>, pub mac: Macro, @@ -710,71 +664,18 @@ ast_struct! { } } -#[cfg(feature = "extra-traits")] -impl Eq for ForeignItem {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for ForeignItem { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (ForeignItem::Fn(this), ForeignItem::Fn(other)) => this == other, - (ForeignItem::Static(this), ForeignItem::Static(other)) => this == other, - (ForeignItem::Type(this), ForeignItem::Type(other)) => this == other, - (ForeignItem::Macro(this), ForeignItem::Macro(other)) => this == other, - (ForeignItem::Verbatim(this), ForeignItem::Verbatim(other)) => { - TokenStreamHelper(this) == TokenStreamHelper(other) - } - _ => false, - } - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for ForeignItem { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - match self { - ForeignItem::Fn(item) => { - state.write_u8(0); - item.hash(state); - } - ForeignItem::Static(item) => { - state.write_u8(1); - item.hash(state); - } - ForeignItem::Type(item) => { - state.write_u8(2); - item.hash(state); - } - ForeignItem::Macro(item) => { - state.write_u8(3); - item.hash(state); - } - ForeignItem::Verbatim(item) => { - state.write_u8(4); - TokenStreamHelper(item).hash(state); - } - ForeignItem::__Nonexhaustive => unreachable!(), - } - } -} - ast_enum_of_structs! { /// An item declaration within the definition of a trait. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum TraitItem #manual_extra_traits { + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub enum TraitItem { /// An associated constant within the definition of a trait. Const(TraitItemConst), @@ -790,15 +691,39 @@ ast_enum_of_structs! { /// Tokens within the definition of a trait not interpreted by Syn. Verbatim(TokenStream), + // The following is the only supported idiom for exhaustive matching of + // this enum. + // + // match expr { + // TraitItem::Const(e) => {...} + // TraitItem::Method(e) => {...} + // ... + // TraitItem::Verbatim(e) => {...} + // + // #[cfg(test)] + // TraitItem::__TestExhaustive(_) => unimplemented!(), + // #[cfg(not(test))] + // _ => { /* some sane fallback */ } + // } + // + // This way we fail your tests but don't break your library when adding + // a variant. You will be notified by a test failure when a variant is + // added, so that you can add code to handle it, but your library will + // continue to compile and work for downstream users in the interim. + // + // Once `deny(reachable)` is available in rustc, TraitItem will be + // reimplemented as a non_exhaustive enum. + // https://github.com/rust-lang/rust/issues/44109#issuecomment-521781237 #[doc(hidden)] - __Nonexhaustive, + __TestExhaustive(crate::private), } } ast_struct! { /// An associated constant within the definition of a trait. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct TraitItemConst { pub attrs: Vec<Attribute>, pub const_token: Token![const], @@ -813,7 +738,8 @@ ast_struct! { ast_struct! { /// A trait method within the definition of a trait. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct TraitItemMethod { pub attrs: Vec<Attribute>, pub sig: Signature, @@ -825,7 +751,8 @@ ast_struct! { ast_struct! { /// An associated type within the definition of a trait. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct TraitItemType { pub attrs: Vec<Attribute>, pub type_token: Token![type], @@ -841,7 +768,8 @@ ast_struct! { ast_struct! { /// A macro invocation within the definition of a trait. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct TraitItemMacro { pub attrs: Vec<Attribute>, pub mac: Macro, @@ -849,71 +777,18 @@ ast_struct! { } } -#[cfg(feature = "extra-traits")] -impl Eq for TraitItem {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for TraitItem { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (TraitItem::Const(this), TraitItem::Const(other)) => this == other, - (TraitItem::Method(this), TraitItem::Method(other)) => this == other, - (TraitItem::Type(this), TraitItem::Type(other)) => this == other, - (TraitItem::Macro(this), TraitItem::Macro(other)) => this == other, - (TraitItem::Verbatim(this), TraitItem::Verbatim(other)) => { - TokenStreamHelper(this) == TokenStreamHelper(other) - } - _ => false, - } - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for TraitItem { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - match self { - TraitItem::Const(item) => { - state.write_u8(0); - item.hash(state); - } - TraitItem::Method(item) => { - state.write_u8(1); - item.hash(state); - } - TraitItem::Type(item) => { - state.write_u8(2); - item.hash(state); - } - TraitItem::Macro(item) => { - state.write_u8(3); - item.hash(state); - } - TraitItem::Verbatim(item) => { - state.write_u8(4); - TokenStreamHelper(item).hash(state); - } - TraitItem::__Nonexhaustive => unreachable!(), - } - } -} - ast_enum_of_structs! { /// An item within an impl block. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum ImplItem #manual_extra_traits { + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub enum ImplItem { /// An associated constant within an impl block. Const(ImplItemConst), @@ -929,15 +804,39 @@ ast_enum_of_structs! { /// Tokens within an impl block not interpreted by Syn. Verbatim(TokenStream), + // The following is the only supported idiom for exhaustive matching of + // this enum. + // + // match expr { + // ImplItem::Const(e) => {...} + // ImplItem::Method(e) => {...} + // ... + // ImplItem::Verbatim(e) => {...} + // + // #[cfg(test)] + // ImplItem::__TestExhaustive(_) => unimplemented!(), + // #[cfg(not(test))] + // _ => { /* some sane fallback */ } + // } + // + // This way we fail your tests but don't break your library when adding + // a variant. You will be notified by a test failure when a variant is + // added, so that you can add code to handle it, but your library will + // continue to compile and work for downstream users in the interim. + // + // Once `deny(reachable)` is available in rustc, ImplItem will be + // reimplemented as a non_exhaustive enum. + // https://github.com/rust-lang/rust/issues/44109#issuecomment-521781237 #[doc(hidden)] - __Nonexhaustive, + __TestExhaustive(crate::private), } } ast_struct! { /// An associated constant within an impl block. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ImplItemConst { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -955,7 +854,8 @@ ast_struct! { ast_struct! { /// A method within an impl block. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ImplItemMethod { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -968,7 +868,8 @@ ast_struct! { ast_struct! { /// An associated type within an impl block. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ImplItemType { pub attrs: Vec<Attribute>, pub vis: Visibility, @@ -985,7 +886,8 @@ ast_struct! { ast_struct! { /// A macro invocation within an impl block. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct ImplItemMacro { pub attrs: Vec<Attribute>, pub mac: Macro, @@ -993,62 +895,12 @@ ast_struct! { } } -#[cfg(feature = "extra-traits")] -impl Eq for ImplItem {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for ImplItem { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (ImplItem::Const(this), ImplItem::Const(other)) => this == other, - (ImplItem::Method(this), ImplItem::Method(other)) => this == other, - (ImplItem::Type(this), ImplItem::Type(other)) => this == other, - (ImplItem::Macro(this), ImplItem::Macro(other)) => this == other, - (ImplItem::Verbatim(this), ImplItem::Verbatim(other)) => { - TokenStreamHelper(this) == TokenStreamHelper(other) - } - _ => false, - } - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for ImplItem { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - match self { - ImplItem::Const(item) => { - state.write_u8(0); - item.hash(state); - } - ImplItem::Method(item) => { - state.write_u8(1); - item.hash(state); - } - ImplItem::Type(item) => { - state.write_u8(2); - item.hash(state); - } - ImplItem::Macro(item) => { - state.write_u8(3); - item.hash(state); - } - ImplItem::Verbatim(item) => { - state.write_u8(4); - TokenStreamHelper(item).hash(state); - } - ImplItem::__Nonexhaustive => unreachable!(), - } - } -} - ast_struct! { /// A function signature in a trait or implementation: `unsafe fn /// initialize(&self)`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct Signature { pub constness: Option<Token![const]>, pub asyncness: Option<Token![async]>, @@ -1085,7 +937,8 @@ impl Signature { ast_enum_of_structs! { /// An argument in a function signature: the `n: usize` in `fn f(n: usize)`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub enum FnArg { /// The `self` argument of an associated method, whether taken by value /// or by reference. @@ -1106,7 +959,8 @@ ast_struct! { /// Note that `self` receivers with a specified type, such as `self: /// Box<Self>`, are parsed as a `FnArg::Typed`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct Receiver { pub attrs: Vec<Attribute>, pub reference: Option<(Token![&], Option<Lifetime>)>, @@ -1124,29 +978,39 @@ impl Receiver { #[cfg(feature = "parsing")] pub mod parsing { use super::*; - use crate::ext::IdentExt; use crate::parse::discouraged::Speculative; - use crate::parse::{Parse, ParseStream, Result}; + use crate::parse::{Parse, ParseBuffer, ParseStream, Result}; + use crate::token::Brace; use proc_macro2::{Delimiter, Group, Punct, Spacing, TokenTree}; use std::iter::{self, FromIterator}; crate::custom_keyword!(existential); + crate::custom_keyword!(macro_rules); + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Item { fn parse(input: ParseStream) -> Result<Self> { + let begin = input.fork(); let mut attrs = input.call(Attribute::parse_outer)?; let ahead = input.fork(); let vis: Visibility = ahead.parse()?; let lookahead = ahead.lookahead1(); - let mut item = if lookahead.peek(Token![extern]) { + let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { + let vis: Visibility = input.parse()?; + let sig: Signature = input.parse()?; + if input.peek(Token![;]) { + input.parse::<Token![;]>()?; + Ok(Item::Verbatim(verbatim::between(begin, input))) + } else { + parse_rest_of_fn(input, Vec::new(), vis, sig).map(Item::Fn) + } + } else if lookahead.peek(Token![extern]) { ahead.parse::<Token![extern]>()?; let lookahead = ahead.lookahead1(); if lookahead.peek(Token![crate]) { input.parse().map(Item::ExternCrate) - } else if lookahead.peek(Token![fn]) { - input.parse().map(Item::Fn) } else if lookahead.peek(token::Brace) { input.parse().map(Item::ForeignMod) } else if lookahead.peek(LitStr) { @@ -1154,8 +1018,6 @@ pub mod parsing { let lookahead = ahead.lookahead1(); if lookahead.peek(token::Brace) { input.parse().map(Item::ForeignMod) - } else if lookahead.peek(Token![fn]) { - input.parse().map(Item::Fn) } else { Err(lookahead.error()) } @@ -1165,18 +1027,68 @@ pub mod parsing { } else if lookahead.peek(Token![use]) { input.parse().map(Item::Use) } else if lookahead.peek(Token![static]) { - input.parse().map(Item::Static) + let vis = input.parse()?; + let static_token = input.parse()?; + let mutability = input.parse()?; + let ident = input.parse()?; + if input.peek(Token![=]) { + input.parse::<Token![=]>()?; + input.parse::<Expr>()?; + input.parse::<Token![;]>()?; + Ok(Item::Verbatim(verbatim::between(begin, input))) + } else { + let colon_token = input.parse()?; + let ty = input.parse()?; + if input.peek(Token![;]) { + input.parse::<Token![;]>()?; + Ok(Item::Verbatim(verbatim::between(begin, input))) + } else { + Ok(Item::Static(ItemStatic { + attrs: Vec::new(), + vis, + static_token, + mutability, + ident, + colon_token, + ty, + eq_token: input.parse()?, + expr: input.parse()?, + semi_token: input.parse()?, + })) + } + } } else if lookahead.peek(Token![const]) { ahead.parse::<Token![const]>()?; let lookahead = ahead.lookahead1(); if lookahead.peek(Ident) || lookahead.peek(Token![_]) { - input.parse().map(Item::Const) - } else if lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![async]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(Item::Fn) + let vis = input.parse()?; + let const_token = input.parse()?; + let ident = { + let lookahead = input.lookahead1(); + if lookahead.peek(Ident) || lookahead.peek(Token![_]) { + input.call(Ident::parse_any)? + } else { + return Err(lookahead.error()); + } + }; + let colon_token = input.parse()?; + let ty = input.parse()?; + if input.peek(Token![;]) { + input.parse::<Token![;]>()?; + Ok(Item::Verbatim(verbatim::between(begin, input))) + } else { + Ok(Item::Const(ItemConst { + attrs: Vec::new(), + vis, + const_token, + ident, + colon_token, + ty, + eq_token: input.parse()?, + expr: input.parse()?, + semi_token: input.parse()?, + })) + } } else { Err(lookahead.error()) } @@ -1188,21 +1100,29 @@ pub mod parsing { { input.parse().map(Item::Trait) } else if lookahead.peek(Token![impl]) { - input.parse().map(Item::Impl) - } else if lookahead.peek(Token![async]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(Item::Fn) + let allow_const_impl = true; + if let Some(item) = parse_impl(input, allow_const_impl)? { + Ok(Item::Impl(item)) + } else { + Ok(Item::Verbatim(verbatim::between(begin, input))) + } + } else if lookahead.peek(Token![extern]) { + input.parse::<Visibility>()?; + input.parse::<Token![unsafe]>()?; + input.parse::<ItemForeignMod>()?; + Ok(Item::Verbatim(verbatim::between(begin, input))) + } else if lookahead.peek(Token![mod]) { + input.parse::<Visibility>()?; + input.parse::<Token![unsafe]>()?; + input.parse::<ItemMod>()?; + Ok(Item::Verbatim(verbatim::between(begin, input))) } else { Err(lookahead.error()) } - } else if lookahead.peek(Token![async]) || lookahead.peek(Token![fn]) { - input.parse().map(Item::Fn) } else if lookahead.peek(Token![mod]) { input.parse().map(Item::Mod) } else if lookahead.peek(Token![type]) { - input.parse().map(Item::Type) + parse_item_type(begin, input) } else if lookahead.peek(existential) { input.call(item_existential).map(Item::Verbatim) } else if lookahead.peek(Token![struct]) { @@ -1218,51 +1138,92 @@ pub mod parsing { } else if lookahead.peek(Token![impl]) || lookahead.peek(Token![default]) && !ahead.peek2(Token![!]) { - input.parse().map(Item::Impl) + let allow_const_impl = true; + if let Some(item) = parse_impl(input, allow_const_impl)? { + Ok(Item::Impl(item)) + } else { + Ok(Item::Verbatim(verbatim::between(begin, input))) + } } else if lookahead.peek(Token![macro]) { input.parse().map(Item::Macro2) } else if vis.is_inherited() && (lookahead.peek(Ident) || lookahead.peek(Token![self]) || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) || lookahead.peek(Token![crate]) || lookahead.peek(Token![::])) { input.parse().map(Item::Macro) + } else if ahead.peek(macro_rules) { + input.advance_to(&ahead); + input.parse::<ItemMacro>()?; + Ok(Item::Verbatim(verbatim::between(begin, input))) } else { Err(lookahead.error()) }?; - { - let item_attrs = match &mut item { - Item::ExternCrate(item) => &mut item.attrs, - Item::Use(item) => &mut item.attrs, - Item::Static(item) => &mut item.attrs, - Item::Const(item) => &mut item.attrs, - Item::Fn(item) => &mut item.attrs, - Item::Mod(item) => &mut item.attrs, - Item::ForeignMod(item) => &mut item.attrs, - Item::Type(item) => &mut item.attrs, - Item::Struct(item) => &mut item.attrs, - Item::Enum(item) => &mut item.attrs, - Item::Union(item) => &mut item.attrs, - Item::Trait(item) => &mut item.attrs, - Item::TraitAlias(item) => &mut item.attrs, - Item::Impl(item) => &mut item.attrs, - Item::Macro(item) => &mut item.attrs, - Item::Macro2(item) => &mut item.attrs, - Item::Verbatim(_) => return Ok(item), - Item::__Nonexhaustive => unreachable!(), - }; - attrs.extend(item_attrs.drain(..)); - *item_attrs = attrs; + attrs.extend(item.replace_attrs(Vec::new())); + item.replace_attrs(attrs); + Ok(item) + } + } + + struct FlexibleItemType { + vis: Visibility, + defaultness: Option<Token![default]>, + type_token: Token![type], + ident: Ident, + generics: Generics, + colon_token: Option<Token![:]>, + bounds: Punctuated<TypeParamBound, Token![+]>, + ty: Option<(Token![=], Type)>, + semi_token: Token![;], + } + + impl Parse for FlexibleItemType { + fn parse(input: ParseStream) -> Result<Self> { + let vis: Visibility = input.parse()?; + let defaultness: Option<Token![default]> = input.parse()?; + let type_token: Token![type] = input.parse()?; + let ident: Ident = input.parse()?; + let mut generics: Generics = input.parse()?; + let colon_token: Option<Token![:]> = input.parse()?; + let mut bounds = Punctuated::new(); + if colon_token.is_some() { + loop { + if input.peek(Token![where]) || input.peek(Token![=]) || input.peek(Token![;]) { + break; + } + bounds.push_value(input.parse::<TypeParamBound>()?); + if input.peek(Token![where]) || input.peek(Token![=]) || input.peek(Token![;]) { + break; + } + bounds.push_punct(input.parse::<Token![+]>()?); + } } + generics.where_clause = input.parse()?; + let ty = if let Some(eq_token) = input.parse()? { + Some((eq_token, input.parse::<Type>()?)) + } else { + None + }; + let semi_token: Token![;] = input.parse()?; - Ok(item) + Ok(FlexibleItemType { + vis, + defaultness, + type_token, + ident, + generics, + colon_token, + bounds, + ty, + semi_token, + }) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemMacro { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -1289,6 +1250,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemMacro2 { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -1329,6 +1291,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemExternCrate { fn parse(input: ParseStream) -> Result<Self> { Ok(ItemExternCrate { @@ -1361,6 +1324,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemUse { fn parse(input: ParseStream) -> Result<Self> { Ok(ItemUse { @@ -1374,6 +1338,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for UseTree { fn parse(input: ParseStream) -> Result<UseTree> { let lookahead = input.lookahead1(); @@ -1381,7 +1346,6 @@ pub mod parsing { || lookahead.peek(Token![self]) || lookahead.peek(Token![super]) || lookahead.peek(Token![crate]) - || lookahead.peek(Token![extern]) { let ident = input.call(Ident::parse_any)?; if input.peek(Token![::]) { @@ -1423,6 +1387,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemStatic { fn parse(input: ParseStream) -> Result<Self> { Ok(ItemStatic { @@ -1440,6 +1405,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemConst { fn parse(input: ParseStream) -> Result<Self> { Ok(ItemConst { @@ -1463,69 +1429,128 @@ pub mod parsing { } } - impl Parse for ItemFn { + fn pop_variadic(args: &mut Punctuated<FnArg, Token![,]>) -> Option<Variadic> { + let trailing_punct = args.trailing_punct(); + + let last = match args.last_mut()? { + FnArg::Typed(last) => last, + _ => return None, + }; + + let ty = match last.ty.as_ref() { + Type::Verbatim(ty) => ty, + _ => return None, + }; + + let mut variadic = Variadic { + attrs: Vec::new(), + dots: parse2(ty.clone()).ok()?, + }; + + if let Pat::Verbatim(pat) = last.pat.as_ref() { + if pat.to_string() == "..." && !trailing_punct { + variadic.attrs = mem::replace(&mut last.attrs, Vec::new()); + args.pop(); + } + } + + Some(variadic) + } + + fn variadic_to_tokens(dots: &Token![...]) -> TokenStream { + TokenStream::from_iter(vec![ + TokenTree::Punct({ + let mut dot = Punct::new('.', Spacing::Joint); + dot.set_span(dots.spans[0]); + dot + }), + TokenTree::Punct({ + let mut dot = Punct::new('.', Spacing::Joint); + dot.set_span(dots.spans[1]); + dot + }), + TokenTree::Punct({ + let mut dot = Punct::new('.', Spacing::Alone); + dot.set_span(dots.spans[2]); + dot + }), + ]) + } + + fn peek_signature(input: ParseStream) -> bool { + let fork = input.fork(); + fork.parse::<Option<Token![const]>>().is_ok() + && fork.parse::<Option<Token![async]>>().is_ok() + && fork.parse::<Option<Token![unsafe]>>().is_ok() + && fork.parse::<Option<Abi>>().is_ok() + && fork.peek(Token![fn]) + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for Signature { fn parse(input: ParseStream) -> Result<Self> { - let outer_attrs = input.call(Attribute::parse_outer)?; - let vis: Visibility = input.parse()?; let constness: Option<Token![const]> = input.parse()?; let asyncness: Option<Token![async]> = input.parse()?; let unsafety: Option<Token![unsafe]> = input.parse()?; let abi: Option<Abi> = input.parse()?; let fn_token: Token![fn] = input.parse()?; let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; + let mut generics: Generics = input.parse()?; let content; let paren_token = parenthesized!(content in input); - let inputs = content.parse_terminated(FnArg::parse)?; - let variadic = inputs.last().as_ref().and_then(get_variadic); - - fn get_variadic(input: &&FnArg) -> Option<Variadic> { - if let FnArg::Typed(PatType { ty, .. }) = input { - if let Type::Verbatim(tokens) = &**ty { - if let Ok(dots) = parse2(tokens.clone()) { - return Some(Variadic { - attrs: Vec::new(), - dots, - }); - } - } - } - None - } + let mut inputs = parse_fn_args(&content)?; + let variadic = pop_variadic(&mut inputs); let output: ReturnType = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; + generics.where_clause = input.parse()?; - Ok(ItemFn { - attrs: private::attrs(outer_attrs, inner_attrs), - vis, - sig: Signature { - constness, - asyncness, - unsafety, - abi, - fn_token, - ident, - paren_token, - inputs, - output, - variadic, - generics: Generics { - where_clause, - ..generics - }, - }, - block: Box::new(Block { brace_token, stmts }), + Ok(Signature { + constness, + asyncness, + unsafety, + abi, + fn_token, + ident, + generics, + paren_token, + inputs, + variadic, + output, }) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for ItemFn { + fn parse(input: ParseStream) -> Result<Self> { + let outer_attrs = input.call(Attribute::parse_outer)?; + let vis: Visibility = input.parse()?; + let sig: Signature = input.parse()?; + parse_rest_of_fn(input, outer_attrs, vis, sig) + } + } + + fn parse_rest_of_fn( + input: ParseStream, + outer_attrs: Vec<Attribute>, + vis: Visibility, + sig: Signature, + ) -> Result<ItemFn> { + let content; + let brace_token = braced!(content in input); + let inner_attrs = content.call(Attribute::parse_inner)?; + let stmts = content.call(Block::parse_within)?; + + Ok(ItemFn { + attrs: private::attrs(outer_attrs, inner_attrs), + vis, + sig, + block: Box::new(Block { brace_token, stmts }), + }) + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for FnArg { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -1545,6 +1570,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Receiver { fn parse(input: ParseStream) -> Result<Self> { Ok(Receiver { @@ -1562,6 +1588,56 @@ pub mod parsing { } } + fn parse_fn_args(input: ParseStream) -> Result<Punctuated<FnArg, Token![,]>> { + let mut args = Punctuated::new(); + let mut has_receiver = false; + + while !input.is_empty() { + let attrs = input.call(Attribute::parse_outer)?; + + let arg = if let Some(dots) = input.parse::<Option<Token![...]>>()? { + FnArg::Typed(PatType { + attrs, + pat: Box::new(Pat::Verbatim(variadic_to_tokens(&dots))), + colon_token: Token![:](dots.spans[0]), + ty: Box::new(Type::Verbatim(variadic_to_tokens(&dots))), + }) + } else { + let mut arg: FnArg = input.parse()?; + match &mut arg { + FnArg::Receiver(receiver) if has_receiver => { + return Err(Error::new( + receiver.self_token.span, + "unexpected second method receiver", + )); + } + FnArg::Receiver(receiver) if !args.is_empty() => { + return Err(Error::new( + receiver.self_token.span, + "unexpected method receiver", + )); + } + FnArg::Receiver(receiver) => { + has_receiver = true; + receiver.attrs = attrs; + } + FnArg::Typed(arg) => arg.attrs = attrs, + } + arg + }; + args.push_value(arg); + + if input.is_empty() { + break; + } + + let comma: Token![,] = input.parse()?; + args.push_punct(comma); + } + + Ok(args) + } + fn fn_arg_typed(input: ParseStream) -> Result<PatType> { // Hack to parse pre-2018 syntax in // test/ui/rfc-2565-param-attrs/param-attrs-pretty.rs @@ -1581,28 +1657,16 @@ pub mod parsing { Ok(PatType { attrs: Vec::new(), - pat: input.parse()?, + pat: Box::new(pat::parsing::multi_pat(input)?), colon_token: input.parse()?, ty: Box::new(match input.parse::<Option<Token![...]>>()? { - Some(dot3) => { - let args = vec![ - TokenTree::Punct(Punct::new('.', Spacing::Joint)), - TokenTree::Punct(Punct::new('.', Spacing::Joint)), - TokenTree::Punct(Punct::new('.', Spacing::Alone)), - ]; - let tokens = TokenStream::from_iter(args.into_iter().zip(&dot3.spans).map( - |(mut arg, span)| { - arg.set_span(*span); - arg - }, - )); - Type::Verbatim(tokens) - } + Some(dot3) => Type::Verbatim(variadic_to_tokens(&dot3)), None => input.parse()?, }), }) } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemMod { fn parse(input: ParseStream) -> Result<Self> { let outer_attrs = input.call(Attribute::parse_outer)?; @@ -1644,6 +1708,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemForeignMod { fn parse(input: ParseStream) -> Result<Self> { let outer_attrs = input.call(Attribute::parse_outer)?; @@ -1666,24 +1731,63 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ForeignItem { fn parse(input: ParseStream) -> Result<Self> { + let begin = input.fork(); let mut attrs = input.call(Attribute::parse_outer)?; let ahead = input.fork(); let vis: Visibility = ahead.parse()?; let lookahead = ahead.lookahead1(); - let mut item = if lookahead.peek(Token![fn]) { - input.parse().map(ForeignItem::Fn) + let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { + let vis: Visibility = input.parse()?; + let sig: Signature = input.parse()?; + if input.peek(token::Brace) { + let content; + braced!(content in input); + content.call(Attribute::parse_inner)?; + content.call(Block::parse_within)?; + + Ok(ForeignItem::Verbatim(verbatim::between(begin, input))) + } else { + Ok(ForeignItem::Fn(ForeignItemFn { + attrs: Vec::new(), + vis, + sig, + semi_token: input.parse()?, + })) + } } else if lookahead.peek(Token![static]) { - input.parse().map(ForeignItem::Static) + let vis = input.parse()?; + 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![=]) { + input.parse::<Token![=]>()?; + input.parse::<Expr>()?; + input.parse::<Token![;]>()?; + Ok(ForeignItem::Verbatim(verbatim::between(begin, input))) + } else { + Ok(ForeignItem::Static(ForeignItemStatic { + attrs: Vec::new(), + vis, + static_token, + mutability, + ident, + colon_token, + ty, + semi_token: input.parse()?, + })) + } } else if lookahead.peek(Token![type]) { - input.parse().map(ForeignItem::Type) + parse_foreign_item_type(begin, input) } else if vis.is_inherited() && (lookahead.peek(Ident) || lookahead.peek(Token![self]) || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) || lookahead.peek(Token![crate]) || lookahead.peek(Token![::])) { @@ -1692,80 +1796,42 @@ pub mod parsing { Err(lookahead.error()) }?; - { - let item_attrs = match &mut item { - ForeignItem::Fn(item) => &mut item.attrs, - ForeignItem::Static(item) => &mut item.attrs, - ForeignItem::Type(item) => &mut item.attrs, - ForeignItem::Macro(item) => &mut item.attrs, - ForeignItem::Verbatim(_) | ForeignItem::__Nonexhaustive => unreachable!(), - }; - attrs.extend(item_attrs.drain(..)); - *item_attrs = attrs; - } + let item_attrs = match &mut item { + ForeignItem::Fn(item) => &mut item.attrs, + ForeignItem::Static(item) => &mut item.attrs, + ForeignItem::Type(item) => &mut item.attrs, + ForeignItem::Macro(item) => &mut item.attrs, + ForeignItem::Verbatim(_) => return Ok(item), + + #[cfg(test)] + ForeignItem::__TestExhaustive(_) => unimplemented!(), + #[cfg(not(test))] + _ => unreachable!(), + }; + attrs.extend(item_attrs.drain(..)); + *item_attrs = attrs; Ok(item) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ForeignItemFn { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; let vis: Visibility = input.parse()?; - let fn_token: Token![fn] = input.parse()?; - let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; - - let content; - let paren_token = parenthesized!(content in input); - let mut inputs = Punctuated::new(); - let mut variadic = None; - while !content.is_empty() { - let attrs = content.call(Attribute::parse_outer)?; - - if let Some(dots) = content.parse()? { - variadic = Some(Variadic { attrs, dots }); - break; - } - - let mut arg = content.call(fn_arg_typed)?; - arg.attrs = attrs; - inputs.push_value(FnArg::Typed(arg)); - if content.is_empty() { - break; - } - - inputs.push_punct(content.parse()?); - } - - let output: ReturnType = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; + let sig: Signature = input.parse()?; let semi_token: Token![;] = input.parse()?; - Ok(ForeignItemFn { attrs, vis, - sig: Signature { - constness: None, - asyncness: None, - unsafety: None, - abi: None, - fn_token, - ident, - paren_token, - inputs, - output, - variadic, - generics: Generics { - where_clause, - ..generics - }, - }, + sig, semi_token, }) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ForeignItemStatic { fn parse(input: ParseStream) -> Result<Self> { Ok(ForeignItemStatic { @@ -1781,6 +1847,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ForeignItemType { fn parse(input: ParseStream) -> Result<Self> { Ok(ForeignItemType { @@ -1793,6 +1860,38 @@ pub mod parsing { } } + fn parse_foreign_item_type(begin: ParseBuffer, input: ParseStream) -> Result<ForeignItem> { + let FlexibleItemType { + vis, + defaultness, + type_token, + ident, + generics, + colon_token, + bounds: _, + ty, + semi_token, + } = input.parse()?; + + if defaultness.is_some() + || generics.lt_token.is_some() + || generics.where_clause.is_some() + || colon_token.is_some() + || ty.is_some() + { + Ok(ForeignItem::Verbatim(verbatim::between(begin, input))) + } else { + Ok(ForeignItem::Type(ForeignItemType { + attrs: Vec::new(), + vis, + type_token, + ident, + semi_token, + })) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ForeignItemMacro { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -1810,6 +1909,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemType { fn parse(input: ParseStream) -> Result<Self> { Ok(ItemType { @@ -1829,6 +1929,36 @@ pub mod parsing { } } + fn parse_item_type(begin: ParseBuffer, input: ParseStream) -> Result<Item> { + let FlexibleItemType { + vis, + defaultness, + type_token, + ident, + generics, + colon_token, + bounds: _, + ty, + semi_token, + } = input.parse()?; + + if defaultness.is_some() || colon_token.is_some() || ty.is_none() { + Ok(Item::Verbatim(verbatim::between(begin, input))) + } else { + let (eq_token, ty) = ty.unwrap(); + Ok(Item::Type(ItemType { + attrs: Vec::new(), + vis, + type_token, + ident, + generics, + eq_token, + ty: Box::new(ty), + semi_token, + })) + } + } + #[cfg(not(feature = "printing"))] fn item_existential(input: ParseStream) -> Result<TokenStream> { Err(input.error("existential type is not supported")) @@ -1876,6 +2006,7 @@ pub mod parsing { Ok(tokens) } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemStruct { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -1899,6 +2030,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemEnum { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -1922,6 +2054,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemUnion { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -1972,9 +2105,10 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemTrait { fn parse(input: ParseStream) -> Result<Self> { - let attrs = input.call(Attribute::parse_outer)?; + let outer_attrs = input.call(Attribute::parse_outer)?; let vis: Visibility = input.parse()?; let unsafety: Option<Token![unsafe]> = input.parse()?; let auto_token: Option<Token![auto]> = input.parse()?; @@ -1983,7 +2117,7 @@ pub mod parsing { let generics: Generics = input.parse()?; parse_rest_of_trait( input, - attrs, + outer_attrs, vis, unsafety, auto_token, @@ -1996,7 +2130,7 @@ pub mod parsing { fn parse_rest_of_trait( input: ParseStream, - attrs: Vec<Attribute>, + outer_attrs: Vec<Attribute>, vis: Visibility, unsafety: Option<Token![unsafe]>, auto_token: Option<Token![auto]>, @@ -2009,14 +2143,14 @@ pub mod parsing { let mut supertraits = Punctuated::new(); if colon_token.is_some() { loop { - supertraits.push_value(input.parse()?); if input.peek(Token![where]) || input.peek(token::Brace) { break; } - supertraits.push_punct(input.parse()?); + supertraits.push_value(input.parse()?); if input.peek(Token![where]) || input.peek(token::Brace) { break; } + supertraits.push_punct(input.parse()?); } } @@ -2024,13 +2158,14 @@ pub mod parsing { let content; let brace_token = braced!(content in input); + let inner_attrs = content.call(Attribute::parse_inner)?; let mut items = Vec::new(); while !content.is_empty() { items.push(content.parse()?); } Ok(ItemTrait { - attrs, + attrs: private::attrs(outer_attrs, inner_attrs), vis, unsafety, auto_token, @@ -2044,6 +2179,7 @@ pub mod parsing { }) } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemTraitAlias { fn parse(input: ParseStream) -> Result<Self> { let (attrs, vis, trait_token, ident, generics) = parse_start_of_trait_alias(input)?; @@ -2099,16 +2235,22 @@ pub mod parsing { }) } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TraitItem { fn parse(input: ParseStream) -> Result<Self> { + let begin = input.fork(); let mut attrs = input.call(Attribute::parse_outer)?; + let vis: Visibility = input.parse()?; + let defaultness: Option<Token![default]> = input.parse()?; let ahead = input.fork(); let lookahead = ahead.lookahead1(); - let mut item = if lookahead.peek(Token![const]) { + let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { + input.parse().map(TraitItem::Method) + } else if lookahead.peek(Token![const]) { ahead.parse::<Token![const]>()?; let lookahead = ahead.lookahead1(); - if lookahead.peek(Ident) { + if lookahead.peek(Ident) || lookahead.peek(Token![_]) { input.parse().map(TraitItem::Const) } else if lookahead.peek(Token![async]) || lookahead.peek(Token![unsafe]) @@ -2119,18 +2261,11 @@ pub mod parsing { } else { Err(lookahead.error()) } - } else if lookahead.peek(Token![async]) - || lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(TraitItem::Method) } else if lookahead.peek(Token![type]) { - input.parse().map(TraitItem::Type) + parse_trait_item_type(begin.fork(), input) } else if lookahead.peek(Ident) || lookahead.peek(Token![self]) || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) || lookahead.peek(Token![crate]) || lookahead.peek(Token![::]) { @@ -2139,28 +2274,43 @@ pub mod parsing { Err(lookahead.error()) }?; - { - let item_attrs = match &mut item { - TraitItem::Const(item) => &mut item.attrs, - TraitItem::Method(item) => &mut item.attrs, - TraitItem::Type(item) => &mut item.attrs, - TraitItem::Macro(item) => &mut item.attrs, - TraitItem::Verbatim(_) | TraitItem::__Nonexhaustive => unreachable!(), - }; - attrs.extend(item_attrs.drain(..)); - *item_attrs = attrs; + match (vis, defaultness) { + (Visibility::Inherited, None) => {} + _ => return Ok(TraitItem::Verbatim(verbatim::between(begin, input))), } + let item_attrs = match &mut item { + TraitItem::Const(item) => &mut item.attrs, + TraitItem::Method(item) => &mut item.attrs, + TraitItem::Type(item) => &mut item.attrs, + TraitItem::Macro(item) => &mut item.attrs, + TraitItem::Verbatim(_) => unreachable!(), + + #[cfg(test)] + TraitItem::__TestExhaustive(_) => unimplemented!(), + #[cfg(not(test))] + _ => unreachable!(), + }; + attrs.extend(item_attrs.drain(..)); + *item_attrs = attrs; Ok(item) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TraitItemConst { fn parse(input: ParseStream) -> Result<Self> { Ok(TraitItemConst { attrs: input.call(Attribute::parse_outer)?, const_token: input.parse()?, - ident: input.parse()?, + ident: { + let lookahead = input.lookahead1(); + if lookahead.peek(Ident) || lookahead.peek(Token![_]) { + input.call(Ident::parse_any)? + } else { + return Err(lookahead.error()); + } + }, colon_token: input.parse()?, ty: input.parse()?, default: { @@ -2177,23 +2327,11 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TraitItemMethod { fn parse(input: ParseStream) -> Result<Self> { let outer_attrs = input.call(Attribute::parse_outer)?; - let constness: Option<Token![const]> = input.parse()?; - let asyncness: Option<Token![async]> = input.parse()?; - let unsafety: Option<Token![unsafe]> = input.parse()?; - let abi: Option<Abi> = input.parse()?; - let fn_token: Token![fn] = input.parse()?; - let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; - - let content; - let paren_token = parenthesized!(content in input); - let inputs = content.parse_terminated(FnArg::parse)?; - - let output: ReturnType = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; + let sig: Signature = input.parse()?; let lookahead = input.lookahead1(); let (brace_token, inner_attrs, stmts, semi_token) = if lookahead.peek(token::Brace) { @@ -2211,28 +2349,14 @@ pub mod parsing { Ok(TraitItemMethod { attrs: private::attrs(outer_attrs, inner_attrs), - sig: Signature { - constness, - asyncness, - unsafety, - abi, - fn_token, - ident, - paren_token, - inputs, - output, - variadic: None, - generics: Generics { - where_clause, - ..generics - }, - }, + sig, default: brace_token.map(|brace_token| Block { brace_token, stmts }), semi_token, }) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TraitItemType { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -2275,6 +2399,36 @@ pub mod parsing { } } + fn parse_trait_item_type(begin: ParseBuffer, input: ParseStream) -> Result<TraitItem> { + let FlexibleItemType { + vis, + defaultness, + type_token, + ident, + generics, + colon_token, + bounds, + ty, + semi_token, + } = input.parse()?; + + if defaultness.is_some() || vis.is_some() { + Ok(TraitItem::Verbatim(verbatim::between(begin, input))) + } else { + Ok(TraitItem::Type(TraitItemType { + attrs: Vec::new(), + type_token, + ident, + generics, + colon_token, + bounds, + default: ty, + semi_token, + })) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TraitItemMacro { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -2292,72 +2446,113 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemImpl { fn parse(input: ParseStream) -> Result<Self> { - let outer_attrs = input.call(Attribute::parse_outer)?; - let defaultness: Option<Token![default]> = input.parse()?; - let unsafety: Option<Token![unsafe]> = input.parse()?; - let impl_token: Token![impl] = input.parse()?; - - let has_generics = input.peek(Token![<]) - && (input.peek2(Token![>]) - || input.peek2(Token![#]) - || (input.peek2(Ident) || input.peek2(Lifetime)) - && (input.peek3(Token![:]) - || input.peek3(Token![,]) - || input.peek3(Token![>]))); - let generics: Generics = if has_generics { - input.parse()? - } else { - Generics::default() - }; + let allow_const_impl = false; + parse_impl(input, allow_const_impl).map(Option::unwrap) + } + } + + fn parse_impl(input: ParseStream, allow_const_impl: bool) -> Result<Option<ItemImpl>> { + let outer_attrs = input.call(Attribute::parse_outer)?; + let defaultness: Option<Token![default]> = input.parse()?; + let unsafety: Option<Token![unsafe]> = input.parse()?; + let impl_token: Token![impl] = input.parse()?; + + let has_generics = input.peek(Token![<]) + && (input.peek2(Token![>]) + || input.peek2(Token![#]) + || (input.peek2(Ident) || input.peek2(Lifetime)) + && (input.peek3(Token![:]) + || input.peek3(Token![,]) + || input.peek3(Token![>])) + || input.peek2(Token![const])); + let mut generics: Generics = if has_generics { + input.parse()? + } else { + Generics::default() + }; - let trait_ = { - // TODO: optimize using advance_to - let ahead = input.fork(); - if ahead.parse::<Option<Token![!]>>().is_ok() - && ahead.parse::<Path>().is_ok() - && ahead.parse::<Token![for]>().is_ok() - { - let polarity: Option<Token![!]> = input.parse()?; - let path: Path = input.parse()?; - let for_token: Token![for] = input.parse()?; - Some((polarity, path, for_token)) + let is_const_impl = allow_const_impl + && (input.peek(Token![const]) || input.peek(Token![?]) && input.peek2(Token![const])); + if is_const_impl { + input.parse::<Option<Token![?]>>()?; + input.parse::<Token![const]>()?; + } + + let begin = input.fork(); + let polarity = if input.peek(Token![!]) && !input.peek2(token::Brace) { + Some(input.parse::<Token![!]>()?) + } else { + None + }; + + let mut first_ty: Type = input.parse()?; + let self_ty: Type; + let trait_; + + let is_impl_for = input.peek(Token![for]); + if is_impl_for { + let for_token: Token![for] = input.parse()?; + let mut first_ty_ref = &first_ty; + while let Type::Group(ty) = first_ty_ref { + first_ty_ref = &ty.elem; + } + if let Type::Path(_) = first_ty_ref { + while let Type::Group(ty) = first_ty { + first_ty = *ty.elem; + } + if let Type::Path(TypePath { qself: None, path }) = first_ty { + trait_ = Some((polarity, path, for_token)); } else { - None + unreachable!() } + } else { + trait_ = None; + } + self_ty = input.parse()?; + } else { + trait_ = None; + self_ty = if polarity.is_none() { + first_ty + } else { + Type::Verbatim(verbatim::between(begin, input)) }; - let self_ty: Type = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; + } - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; + generics.where_clause = input.parse()?; - let mut items = Vec::new(); - while !content.is_empty() { - items.push(content.parse()?); - } + let content; + let brace_token = braced!(content in input); + let inner_attrs = content.call(Attribute::parse_inner)?; + + let mut items = Vec::new(); + while !content.is_empty() { + items.push(content.parse()?); + } - Ok(ItemImpl { + if is_const_impl || is_impl_for && trait_.is_none() { + Ok(None) + } else { + Ok(Some(ItemImpl { attrs: private::attrs(outer_attrs, inner_attrs), defaultness, unsafety, impl_token, - generics: Generics { - where_clause, - ..generics - }, + generics, trait_, self_ty: Box::new(self_ty), brace_token, items, - }) + })) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ImplItem { fn parse(input: ParseStream) -> Result<Self> { + let begin = input.fork(); let mut attrs = input.call(Attribute::parse_outer)?; let ahead = input.fork(); let vis: Visibility = ahead.parse()?; @@ -2371,28 +2566,38 @@ pub mod parsing { None }; - let mut item = if lookahead.peek(Token![const]) { - ahead.parse::<Token![const]>()?; + let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { + input.parse().map(ImplItem::Method) + } else if lookahead.peek(Token![const]) { + let const_token: Token![const] = ahead.parse()?; let lookahead = ahead.lookahead1(); - if lookahead.peek(Ident) { - input.parse().map(ImplItem::Const) - } else if lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![async]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(ImplItem::Method) + if lookahead.peek(Ident) || lookahead.peek(Token![_]) { + input.advance_to(&ahead); + let ident: Ident = input.call(Ident::parse_any)?; + let colon_token: Token![:] = input.parse()?; + let ty: Type = input.parse()?; + if let Some(eq_token) = input.parse()? { + return Ok(ImplItem::Const(ImplItemConst { + attrs, + vis, + defaultness, + const_token, + ident, + colon_token, + ty, + eq_token, + expr: input.parse()?, + semi_token: input.parse()?, + })); + } else { + input.parse::<Token![;]>()?; + return Ok(ImplItem::Verbatim(verbatim::between(begin, input))); + } } else { Err(lookahead.error()) } - } else if lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![async]) - || lookahead.peek(Token![extern]) - || lookahead.peek(Token![fn]) - { - input.parse().map(ImplItem::Method) } else if lookahead.peek(Token![type]) { - input.parse().map(ImplItem::Type) + parse_impl_item_type(begin, input) } else if vis.is_inherited() && defaultness.is_none() && lookahead.peek(existential) { input.call(item_existential).map(ImplItem::Verbatim) } else if vis.is_inherited() @@ -2400,7 +2605,6 @@ pub mod parsing { && (lookahead.peek(Ident) || lookahead.peek(Token![self]) || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) || lookahead.peek(Token![crate]) || lookahead.peek(Token![::])) { @@ -2416,7 +2620,11 @@ pub mod parsing { ImplItem::Type(item) => &mut item.attrs, ImplItem::Macro(item) => &mut item.attrs, ImplItem::Verbatim(_) => return Ok(item), - ImplItem::__Nonexhaustive => unreachable!(), + + #[cfg(test)] + ImplItem::__TestExhaustive(_) => unimplemented!(), + #[cfg(not(test))] + _ => unreachable!(), }; attrs.extend(item_attrs.drain(..)); *item_attrs = attrs; @@ -2426,6 +2634,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ImplItemConst { fn parse(input: ParseStream) -> Result<Self> { Ok(ImplItemConst { @@ -2433,7 +2642,14 @@ pub mod parsing { vis: input.parse()?, defaultness: input.parse()?, const_token: input.parse()?, - ident: input.parse()?, + ident: { + let lookahead = input.lookahead1(); + if lookahead.peek(Ident) || lookahead.peek(Token![_]) { + input.call(Ident::parse_any)? + } else { + return Err(lookahead.error()); + } + }, colon_token: input.parse()?, ty: input.parse()?, eq_token: input.parse()?, @@ -2443,56 +2659,47 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ImplItemMethod { fn parse(input: ParseStream) -> Result<Self> { - let outer_attrs = input.call(Attribute::parse_outer)?; + let mut attrs = input.call(Attribute::parse_outer)?; let vis: Visibility = input.parse()?; let defaultness: Option<Token![default]> = input.parse()?; - let constness: Option<Token![const]> = input.parse()?; - let asyncness: Option<Token![async]> = input.parse()?; - let unsafety: Option<Token![unsafe]> = input.parse()?; - let abi: Option<Abi> = input.parse()?; - let fn_token: Token![fn] = input.parse()?; - let ident: Ident = input.parse()?; - let generics: Generics = input.parse()?; - - let content; - let paren_token = parenthesized!(content in input); - let inputs = content.parse_terminated(FnArg::parse)?; - - let output: ReturnType = input.parse()?; - let where_clause: Option<WhereClause> = input.parse()?; - - let content; - let brace_token = braced!(content in input); - let inner_attrs = content.call(Attribute::parse_inner)?; - let stmts = content.call(Block::parse_within)?; + let sig: Signature = input.parse()?; + + let block = if let Some(semi) = input.parse::<Option<Token![;]>>()? { + // Accept methods without a body in an impl block because + // rustc's *parser* does not reject them (the compilation error + // is emitted later than parsing) and it can be useful for macro + // DSLs. + let mut punct = Punct::new(';', Spacing::Alone); + punct.set_span(semi.span); + let tokens = TokenStream::from_iter(vec![TokenTree::Punct(punct)]); + Block { + brace_token: Brace::default(), + stmts: vec![Stmt::Item(Item::Verbatim(tokens))], + } + } else { + let content; + let brace_token = braced!(content in input); + attrs.extend(content.call(Attribute::parse_inner)?); + Block { + brace_token, + stmts: content.call(Block::parse_within)?, + } + }; Ok(ImplItemMethod { - attrs: private::attrs(outer_attrs, inner_attrs), + attrs, vis, defaultness, - sig: Signature { - constness, - asyncness, - unsafety, - abi, - fn_token, - ident, - paren_token, - inputs, - output, - variadic: None, - generics: Generics { - where_clause, - ..generics - }, - }, - block: Block { brace_token, stmts }, + sig, + block, }) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ImplItemType { fn parse(input: ParseStream) -> Result<Self> { Ok(ImplItemType { @@ -2513,6 +2720,38 @@ pub mod parsing { } } + fn parse_impl_item_type(begin: ParseBuffer, input: ParseStream) -> Result<ImplItem> { + let FlexibleItemType { + vis, + defaultness, + type_token, + ident, + generics, + colon_token, + bounds: _, + ty, + semi_token, + } = input.parse()?; + + if colon_token.is_some() || ty.is_none() { + Ok(ImplItem::Verbatim(verbatim::between(begin, input))) + } else { + let (eq_token, ty) = ty.unwrap(); + Ok(ImplItem::Type(ImplItemType { + attrs: Vec::new(), + vis, + defaultness, + type_token, + ident, + generics, + eq_token, + ty, + semi_token, + })) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ImplItemMacro { fn parse(input: ParseStream) -> Result<Self> { let attrs = input.call(Attribute::parse_outer)?; @@ -2552,13 +2791,13 @@ pub mod parsing { #[cfg(feature = "printing")] mod printing { use super::*; - - use proc_macro2::TokenStream; - use quote::{ToTokens, TokenStreamExt}; - use crate::attr::FilterAttrs; use crate::print::TokensOrDefault; + use crate::punctuated::Pair; + use proc_macro2::TokenStream; + use quote::{ToTokens, TokenStreamExt}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemExternCrate { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2574,6 +2813,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemUse { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2585,6 +2825,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemStatic { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2600,6 +2841,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemConst { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2614,6 +2856,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemFn { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2626,6 +2869,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemMod { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2643,6 +2887,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemForeignMod { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2654,6 +2899,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemType { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2668,6 +2914,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemEnum { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2682,6 +2929,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemStruct { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2707,6 +2955,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemUnion { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2719,6 +2968,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemTrait { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2734,11 +2984,13 @@ mod printing { } self.generics.where_clause.to_tokens(tokens); self.brace_token.surround(tokens, |tokens| { + tokens.append_all(self.attrs.inner()); tokens.append_all(&self.items); }); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemTraitAlias { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2753,6 +3005,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemImpl { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2774,6 +3027,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemMacro { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2795,6 +3049,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ItemMacro2 { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2805,6 +3060,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for UsePath { fn to_tokens(&self, tokens: &mut TokenStream) { self.ident.to_tokens(tokens); @@ -2813,12 +3069,14 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for UseName { fn to_tokens(&self, tokens: &mut TokenStream) { self.ident.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for UseRename { fn to_tokens(&self, tokens: &mut TokenStream) { self.ident.to_tokens(tokens); @@ -2827,12 +3085,14 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for UseGlob { fn to_tokens(&self, tokens: &mut TokenStream) { self.star_token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for UseGroup { fn to_tokens(&self, tokens: &mut TokenStream) { self.brace_token.surround(tokens, |tokens| { @@ -2841,6 +3101,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TraitItemConst { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2856,6 +3117,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TraitItemMethod { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2874,6 +3136,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TraitItemType { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2893,6 +3156,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TraitItemMacro { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2901,6 +3165,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ImplItemConst { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2916,12 +3181,21 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ImplItemMethod { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); self.vis.to_tokens(tokens); self.defaultness.to_tokens(tokens); self.sig.to_tokens(tokens); + if self.block.stmts.len() == 1 { + if let Stmt::Item(Item::Verbatim(verbatim)) = &self.block.stmts[0] { + if verbatim.to_string() == ";" { + verbatim.to_tokens(tokens); + return; + } + } + } self.block.brace_token.surround(tokens, |tokens| { tokens.append_all(self.attrs.inner()); tokens.append_all(&self.block.stmts); @@ -2929,6 +3203,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ImplItemType { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2944,6 +3219,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ImplItemMacro { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2952,6 +3228,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ForeignItemFn { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2961,6 +3238,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ForeignItemStatic { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2974,6 +3252,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ForeignItemType { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2984,6 +3263,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ForeignItemMacro { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -2992,25 +3272,34 @@ mod printing { } } - fn has_variadic(inputs: &Punctuated<FnArg, Token![,]>) -> bool { - let last = match inputs.last() { - Some(last) => last, - None => return false, - }; - - let pat = match last { - FnArg::Typed(pat) => pat, - FnArg::Receiver(_) => return false, - }; - - let tokens = match pat.ty.as_ref() { - Type::Verbatim(tokens) => tokens, - _ => return false, + fn maybe_variadic_to_tokens(arg: &FnArg, tokens: &mut TokenStream) -> bool { + let arg = match arg { + FnArg::Typed(arg) => arg, + FnArg::Receiver(receiver) => { + receiver.to_tokens(tokens); + return false; + } }; - tokens.to_string() == "..." + match arg.ty.as_ref() { + Type::Verbatim(ty) if ty.to_string() == "..." => { + match arg.pat.as_ref() { + Pat::Verbatim(pat) if pat.to_string() == "..." => { + tokens.append_all(arg.attrs.outer()); + pat.to_tokens(tokens); + } + _ => arg.to_tokens(tokens), + } + true + } + _ => { + arg.to_tokens(tokens); + false + } + } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Signature { fn to_tokens(&self, tokens: &mut TokenStream) { self.constness.to_tokens(tokens); @@ -3021,8 +3310,19 @@ mod printing { self.ident.to_tokens(tokens); self.generics.to_tokens(tokens); self.paren_token.surround(tokens, |tokens| { - self.inputs.to_tokens(tokens); - if self.variadic.is_some() && !has_variadic(&self.inputs) { + let mut last_is_variadic = false; + for input in self.inputs.pairs() { + match input { + Pair::Punctuated(input, comma) => { + maybe_variadic_to_tokens(input, tokens); + comma.to_tokens(tokens); + } + Pair::End(input) => { + last_is_variadic = maybe_variadic_to_tokens(input, tokens); + } + } + } + if self.variadic.is_some() && !last_is_variadic { if !self.inputs.empty_or_trailing() { <Token![,]>::default().to_tokens(tokens); } @@ -3034,6 +3334,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Receiver { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); diff --git a/1.0.7/src/lib.rs b/src/lib.rs index 2a2ff61e..ea0c6dde 100644 --- a/1.0.7/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,11 @@ +//! [![github]](https://github.com/dtolnay/syn) [![crates-io]](https://crates.io/crates/syn) [![docs-rs]](crate) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K +//! +//! <br> +//! //! Syn is a parsing library for parsing a stream of Rust tokens into a syntax //! tree of Rust source code. //! @@ -31,12 +39,12 @@ //! procedural macros enable only what they need, and do not pay in compile //! time for all the rest. //! -//! [`syn::File`]: struct.File.html -//! [`syn::Item`]: enum.Item.html -//! [`syn::Expr`]: enum.Expr.html -//! [`syn::Type`]: enum.Type.html -//! [`syn::DeriveInput`]: struct.DeriveInput.html -//! [parser functions]: parse/index.html +//! [`syn::File`]: File +//! [`syn::Item`]: Item +//! [`syn::Expr`]: Expr +//! [`syn::Type`]: Type +//! [`syn::DeriveInput`]: DeriveInput +//! [parser functions]: mod@parse //! //! <br> //! @@ -50,7 +58,7 @@ //! tokens, then hand some tokens back to the compiler to compile into the //! user's crate. //! -//! [`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html +//! [`TokenStream`]: proc_macro::TokenStream //! //! ```toml //! [dependencies] @@ -62,8 +70,8 @@ //! ``` //! //! ``` -//! extern crate proc_macro; -//! +//! # extern crate proc_macro; +//! # //! use proc_macro::TokenStream; //! use quote::quote; //! use syn::{parse_macro_input, DeriveInput}; @@ -242,38 +250,49 @@ //! 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/1.0.7")] -#![deny(clippy::all, clippy::pedantic)] +#![doc(html_root_url = "https://docs.rs/syn/1.0.69")] +#![cfg_attr(doc_cfg, feature(doc_cfg))] +#![allow(non_camel_case_types)] // Ignored clippy lints. #![allow( - clippy::block_in_if_condition_stmt, - clippy::cognitive_complexity, clippy::doc_markdown, clippy::eval_order_dependence, clippy::inherent_to_string, clippy::large_enum_variant, + clippy::manual_map, // https://github.com/rust-lang/rust-clippy/issues/6795 + clippy::match_on_vec_items, + clippy::missing_panics_doc, clippy::needless_doctest_main, clippy::needless_pass_by_value, clippy::never_loop, - clippy::suspicious_op_assign_impl, clippy::too_many_arguments, - clippy::trivially_copy_pass_by_ref + clippy::trivially_copy_pass_by_ref, + clippy::unnecessary_unwrap, + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6983 + clippy::wrong_self_convention )] // Ignored clippy_pedantic lints. #![allow( clippy::cast_possible_truncation, + clippy::default_trait_access, clippy::empty_enum, + clippy::expl_impl_clone_on_copy, clippy::if_not_else, - clippy::items_after_statements, + clippy::match_same_arms, + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6984 + clippy::match_wildcard_for_single_variants, + clippy::missing_errors_doc, clippy::module_name_repetitions, clippy::must_use_candidate, + clippy::option_if_let_else, + clippy::redundant_else, clippy::shadow_unrelated, clippy::similar_names, clippy::single_match_else, clippy::too_many_lines, clippy::unseparated_literal_suffix, - clippy::use_self, - clippy::used_underscore_binding + clippy::used_underscore_binding, + clippy::wildcard_imports )] #[cfg(all( @@ -287,7 +306,6 @@ extern crate unicode_xid; #[cfg(feature = "printing")] extern crate quote; -#[cfg(any(feature = "full", feature = "derive"))] #[macro_use] mod macros; @@ -310,7 +328,6 @@ pub use crate::attr::{ AttrStyle, Attribute, AttributeArgs, Meta, MetaList, MetaNameValue, NestedMeta, }; -#[cfg(any(feature = "full", feature = "derive"))] mod bigint; #[cfg(any(feature = "full", feature = "derive"))] @@ -367,9 +384,7 @@ pub use crate::file::File; mod lifetime; pub use crate::lifetime::Lifetime; -#[cfg(any(feature = "full", feature = "derive"))] mod lit; -#[cfg(any(feature = "full", feature = "derive"))] pub use crate::lit::{ Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr, StrStyle, }; @@ -420,8 +435,10 @@ pub use crate::path::{ }; #[cfg(feature = "parsing")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub mod buffer; #[cfg(feature = "parsing")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub mod ext; pub mod punctuated; #[cfg(all(any(feature = "full", feature = "derive"), feature = "extra-traits"))] @@ -442,8 +459,12 @@ pub mod parse_quote; pub mod parse_macro_input; #[cfg(all(feature = "parsing", feature = "printing"))] +#[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "printing"))))] pub mod spanned; +#[cfg(all(feature = "parsing", feature = "full"))] +mod whitespace; + mod gen { /// Syntax tree traversal to walk a shared borrow of a syntax tree. /// @@ -485,7 +506,7 @@ mod gen { /// /* ... */ /// ``` /// - /// *This module is available if Syn is built with the `"visit"` feature.* + /// *This module is available only if Syn is built with the `"visit"` feature.* /// /// <br> /// @@ -562,6 +583,7 @@ mod gen { /// } /// ``` #[cfg(feature = "visit")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "visit")))] #[rustfmt::skip] pub mod visit; @@ -606,7 +628,7 @@ mod gen { /// /* ... */ /// ``` /// - /// *This module is available if Syn is built with the `"visit-mut"` + /// *This module is available only if Syn is built with the `"visit-mut"` /// feature.* /// /// <br> @@ -658,6 +680,7 @@ mod gen { /// } /// ``` #[cfg(feature = "visit-mut")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "visit-mut")))] #[rustfmt::skip] pub mod visit_mut; @@ -705,7 +728,7 @@ mod gen { /// /* ... */ /// ``` /// - /// *This module is available if Syn is built with the `"fold"` feature.* + /// *This module is available only if Syn is built with the `"fold"` feature.* /// /// <br> /// @@ -744,9 +767,26 @@ mod gen { /// } /// ``` #[cfg(feature = "fold")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "fold")))] #[rustfmt::skip] pub mod fold; + #[cfg(feature = "clone-impls")] + #[rustfmt::skip] + mod clone; + + #[cfg(feature = "extra-traits")] + #[rustfmt::skip] + mod eq; + + #[cfg(feature = "extra-traits")] + #[rustfmt::skip] + mod hash; + + #[cfg(feature = "extra-traits")] + #[rustfmt::skip] + mod debug; + #[cfg(any(feature = "full", feature = "derive"))] #[path = "../gen_helper.rs"] mod helper; @@ -755,30 +795,35 @@ pub use crate::gen::*; // Not public API. #[doc(hidden)] -pub mod export; +#[path = "export.rs"] +pub mod __private; mod custom_keyword; mod custom_punctuation; mod sealed; +mod span; +mod thread; #[cfg(feature = "parsing")] mod lookahead; #[cfg(feature = "parsing")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub mod parse; -mod span; +#[cfg(feature = "full")] +mod reserved; + +#[cfg(all(any(feature = "full", feature = "derive"), feature = "parsing"))] +mod verbatim; #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] mod print; -mod thread; +use crate::__private::private; //////////////////////////////////////////////////////////////////////////////// -#[allow(dead_code, non_camel_case_types)] -struct private; - // https://github.com/rust-lang/rust/issues/62830 #[cfg(feature = "parsing")] mod rustdoc_workaround { @@ -803,14 +848,14 @@ pub use crate::error::{Error, Result}; /// /// [`syn::parse2`]: parse2 /// -/// *This function is available if Syn is built with both the `"parsing"` and +/// *This function is available only if Syn is built with both the `"parsing"` and /// `"proc-macro"` features.* /// /// # Examples /// /// ``` -/// extern crate proc_macro; -/// +/// # extern crate proc_macro; +/// # /// use proc_macro::TokenStream; /// use quote::quote; /// use syn::DeriveInput; @@ -836,6 +881,7 @@ pub use crate::error::{Error, Result}; feature = "parsing", feature = "proc-macro" ))] +#[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "proc-macro"))))] pub fn parse<T: parse::Parse>(tokens: proc_macro::TokenStream) -> Result<T> { parse::Parser::parse(T::parse, tokens) } @@ -850,15 +896,16 @@ pub fn parse<T: parse::Parse>(tokens: proc_macro::TokenStream) -> Result<T> { /// /// [`syn::parse`]: parse() /// -/// *This function is available if Syn is built with the `"parsing"` feature.* +/// *This function is available only if Syn is built with the `"parsing"` feature.* #[cfg(feature = "parsing")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse2<T: parse::Parse>(tokens: proc_macro2::TokenStream) -> Result<T> { parse::Parser::parse2(T::parse, tokens) } /// Parse a string of Rust code into the chosen syntax tree node. /// -/// *This function is available if Syn is built with the `"parsing"` feature.* +/// *This function is available only if Syn is built with the `"parsing"` feature.* /// /// # Hygiene /// @@ -880,6 +927,7 @@ pub fn parse2<T: parse::Parse>(tokens: proc_macro2::TokenStream) -> Result<T> { /// # run().unwrap(); /// ``` #[cfg(feature = "parsing")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_str<T: parse::Parse>(s: &str) -> Result<T> { parse::Parser::parse_str(T::parse, s) } @@ -895,7 +943,7 @@ pub fn parse_str<T: parse::Parse>(s: &str) -> Result<T> { /// /// If present, either of these would be an error using `from_str`. /// -/// *This function is available if Syn is built with the `"parsing"` and +/// *This function is available only if Syn is built with the `"parsing"` and /// `"full"` features.* /// /// # Examples @@ -922,6 +970,7 @@ pub fn parse_str<T: parse::Parse>(s: &str) -> Result<T> { /// # run().unwrap(); /// ``` #[cfg(all(feature = "parsing", feature = "full"))] +#[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "full"))))] pub fn parse_file(mut content: &str) -> Result<File> { // Strip the BOM if it is present const BOM: &str = "\u{feff}"; @@ -930,13 +979,16 @@ pub fn parse_file(mut content: &str) -> Result<File> { } let mut shebang = None; - if content.starts_with("#!") && !content.starts_with("#![") { - if let Some(idx) = content.find('\n') { - shebang = Some(content[..idx].to_string()); - content = &content[idx..]; - } else { - shebang = Some(content.to_string()); - content = ""; + if content.starts_with("#!") { + let rest = whitespace::skip(&content[2..]); + if !rest.starts_with('[') { + if let Some(idx) = content.find('\n') { + shebang = Some(content[..idx].to_string()); + content = &content[idx..]; + } else { + shebang = Some(content.to_string()); + content = ""; + } } } diff --git a/1.0.7/src/lifetime.rs b/src/lifetime.rs index d51c48e8..28cd7e36 100644 --- a/1.0.7/src/lifetime.rs +++ b/src/lifetime.rs @@ -1,9 +1,8 @@ +use proc_macro2::{Ident, Span}; use std::cmp::Ordering; use std::fmt::{self, Display}; use std::hash::{Hash, Hasher}; -use proc_macro2::{Ident, Span}; - #[cfg(feature = "parsing")] use crate::lookahead; @@ -17,11 +16,6 @@ use crate::lookahead; /// the XID_Start property. /// - All following characters must be Unicode code points with the XID_Continue /// property. -/// -/// *This type is available if Syn is built with the `"derive"` or `"full"` -/// feature.* -#[cfg_attr(feature = "extra-traits", derive(Debug))] -#[derive(Clone)] pub struct Lifetime { pub apostrophe: Span, pub ident: Ident, @@ -63,6 +57,17 @@ impl Lifetime { ident: Ident::new(&symbol[1..], span), } } + + pub fn span(&self) -> Span { + self.apostrophe + .join(self.ident.span()) + .unwrap_or(self.apostrophe) + } + + pub fn set_span(&mut self, span: Span) { + self.apostrophe = span; + self.ident.set_span(span); + } } impl Display for Lifetime { @@ -72,6 +77,15 @@ impl Display for Lifetime { } } +impl Clone for Lifetime { + fn clone(&self) -> Self { + Lifetime { + apostrophe: self.apostrophe, + ident: self.ident.clone(), + } + } +} + impl PartialEq for Lifetime { fn eq(&self, other: &Lifetime) -> bool { self.ident.eq(&other.ident) @@ -108,9 +122,9 @@ pub fn Lifetime(marker: lookahead::TokenMarker) -> Lifetime { #[cfg(feature = "parsing")] pub mod parsing { use super::*; - use crate::parse::{Parse, ParseStream, Result}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Lifetime { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| { @@ -125,10 +139,10 @@ pub mod parsing { #[cfg(feature = "printing")] mod printing { use super::*; - use proc_macro2::{Punct, Spacing, TokenStream}; use quote::{ToTokens, TokenStreamExt}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Lifetime { fn to_tokens(&self, tokens: &mut TokenStream) { let mut apostrophe = Punct::new('\'', Spacing::Joint); diff --git a/1.0.7/src/lit.rs b/src/lit.rs index abc4ec2f..0aa50a59 100644 --- a/1.0.7/src/lit.rs +++ b/src/lit.rs @@ -1,39 +1,28 @@ -use proc_macro2::{Literal, Span}; -use std::fmt::{self, Display}; -use std::str::{self, FromStr}; - +#[cfg(feature = "parsing")] +use crate::lookahead; +#[cfg(feature = "parsing")] +use crate::parse::{Parse, Parser}; +use crate::{Error, Result}; #[cfg(feature = "printing")] use proc_macro2::Ident; - #[cfg(feature = "parsing")] use proc_macro2::TokenStream; - use proc_macro2::TokenTree; - +use proc_macro2::{Literal, Span}; +use std::fmt::{self, Display}; #[cfg(feature = "extra-traits")] use std::hash::{Hash, Hasher}; - -#[cfg(feature = "parsing")] -use crate::lookahead; -#[cfg(feature = "parsing")] -use crate::parse::{Parse, Parser}; -use crate::{Error, Result}; +use std::str::{self, FromStr}; ast_enum_of_structs! { /// A Rust literal such as a string or integer or boolean. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* - /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Lit #manual_extra_traits { + /// [syntax tree enum]: crate::Expr#syntax-tree-enums + pub enum Lit { /// A UTF-8 string literal: `"foo"`. Str(LitStr), @@ -64,61 +53,44 @@ ast_enum_of_structs! { ast_struct! { /// A UTF-8 string literal: `"foo"`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub struct LitStr #manual_extra_traits_debug { - repr: Box<LitStrRepr>, + pub struct LitStr { + repr: Box<LitRepr>, } } -#[cfg_attr(feature = "clone-impls", derive(Clone))] -struct LitStrRepr { - token: Literal, - suffix: Box<str>, -} - ast_struct! { /// A byte string literal: `b"foo"`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub struct LitByteStr #manual_extra_traits_debug { - token: Literal, + pub struct LitByteStr { + repr: Box<LitRepr>, } } ast_struct! { /// A byte literal: `b'f'`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub struct LitByte #manual_extra_traits_debug { - token: Literal, + pub struct LitByte { + repr: Box<LitRepr>, } } ast_struct! { /// A character literal: `'a'`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub struct LitChar #manual_extra_traits_debug { - token: Literal, + pub struct LitChar { + repr: Box<LitRepr>, } } +struct LitRepr { + token: Literal, + suffix: Box<str>, +} + ast_struct! { /// An integer literal: `1` or `1u16`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub struct LitInt #manual_extra_traits_debug { + pub struct LitInt { repr: Box<LitIntRepr>, } } -#[cfg_attr(feature = "clone-impls", derive(Clone))] struct LitIntRepr { token: Literal, digits: Box<str>, @@ -128,16 +100,12 @@ struct LitIntRepr { ast_struct! { /// A floating point literal: `1f64` or `1.0e10f64`. /// - /// Must be finite. May not be infinte or NaN. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub struct LitFloat #manual_extra_traits_debug { + /// Must be finite. May not be infinite or NaN. + pub struct LitFloat { repr: Box<LitFloatRepr>, } } -#[cfg_attr(feature = "clone-impls", derive(Clone))] struct LitFloatRepr { token: Literal, digits: Box<str>, @@ -146,92 +114,27 @@ struct LitFloatRepr { ast_struct! { /// A boolean literal: `true` or `false`. - /// - /// *This type is available if Syn is built with the `"derive"` or - /// `"full"` feature.* - pub struct LitBool #manual_extra_traits_debug { + pub struct LitBool { pub value: bool, pub span: Span, } } -#[cfg(feature = "extra-traits")] -impl Eq for Lit {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Lit { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Lit::Str(this), Lit::Str(other)) => this == other, - (Lit::ByteStr(this), Lit::ByteStr(other)) => this == other, - (Lit::Byte(this), Lit::Byte(other)) => this == other, - (Lit::Char(this), Lit::Char(other)) => this == other, - (Lit::Int(this), Lit::Int(other)) => this == other, - (Lit::Float(this), Lit::Float(other)) => this == other, - (Lit::Bool(this), Lit::Bool(other)) => this == other, - (Lit::Verbatim(this), Lit::Verbatim(other)) => this.to_string() == other.to_string(), - _ => false, - } - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Lit { - fn hash<H>(&self, hash: &mut H) - where - H: Hasher, - { - match self { - Lit::Str(lit) => { - hash.write_u8(0); - lit.hash(hash); - } - Lit::ByteStr(lit) => { - hash.write_u8(1); - lit.hash(hash); - } - Lit::Byte(lit) => { - hash.write_u8(2); - lit.hash(hash); - } - Lit::Char(lit) => { - hash.write_u8(3); - lit.hash(hash); - } - Lit::Int(lit) => { - hash.write_u8(4); - lit.hash(hash); - } - Lit::Float(lit) => { - hash.write_u8(5); - lit.hash(hash); - } - Lit::Bool(lit) => { - hash.write_u8(6); - lit.hash(hash); - } - Lit::Verbatim(lit) => { - hash.write_u8(7); - lit.to_string().hash(hash); - } - } - } -} - impl LitStr { pub fn new(value: &str, span: Span) -> Self { - let mut lit = Literal::string(value); - lit.set_span(span); + let mut token = Literal::string(value); + token.set_span(span); LitStr { - repr: Box::new(LitStrRepr { - token: lit, + repr: Box::new(LitRepr { + token, suffix: Box::<str>::default(), }), } } pub fn value(&self) -> String { - let (value, _) = value::parse_lit_str(&self.repr.token.to_string()); + let repr = self.repr.token.to_string(); + let (value, _suffix) = value::parse_lit_str(&repr); String::from(value) } @@ -267,6 +170,7 @@ impl LitStr { /// } /// ``` #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse<T: Parse>(&self) -> Result<T> { self.parse_with(T::parse) } @@ -296,6 +200,7 @@ impl LitStr { /// # } /// ``` #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_with<F: Parser>(&self, parser: F) -> Result<F::Output> { use proc_macro2::Group; @@ -345,19 +250,30 @@ impl LitByteStr { pub fn new(value: &[u8], span: Span) -> Self { let mut token = Literal::byte_string(value); token.set_span(span); - LitByteStr { token } + LitByteStr { + repr: Box::new(LitRepr { + token, + suffix: Box::<str>::default(), + }), + } } pub fn value(&self) -> Vec<u8> { - value::parse_lit_byte_str(&self.token.to_string()) + let repr = self.repr.token.to_string(); + let (value, _suffix) = value::parse_lit_byte_str(&repr); + value } pub fn span(&self) -> Span { - self.token.span() + self.repr.token.span() } pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) + self.repr.token.set_span(span) + } + + pub fn suffix(&self) -> &str { + &self.repr.suffix } } @@ -365,19 +281,30 @@ impl LitByte { pub fn new(value: u8, span: Span) -> Self { let mut token = Literal::u8_suffixed(value); token.set_span(span); - LitByte { token } + LitByte { + repr: Box::new(LitRepr { + token, + suffix: Box::<str>::default(), + }), + } } pub fn value(&self) -> u8 { - value::parse_lit_byte(&self.token.to_string()) + let repr = self.repr.token.to_string(); + let (value, _suffix) = value::parse_lit_byte(&repr); + value } pub fn span(&self) -> Span { - self.token.span() + self.repr.token.span() } pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) + self.repr.token.set_span(span) + } + + pub fn suffix(&self) -> &str { + &self.repr.suffix } } @@ -385,36 +312,52 @@ impl LitChar { pub fn new(value: char, span: Span) -> Self { let mut token = Literal::character(value); token.set_span(span); - LitChar { token } + LitChar { + repr: Box::new(LitRepr { + token, + suffix: Box::<str>::default(), + }), + } } pub fn value(&self) -> char { - value::parse_lit_char(&self.token.to_string()) + let repr = self.repr.token.to_string(); + let (value, _suffix) = value::parse_lit_char(&repr); + value } pub fn span(&self) -> Span { - self.token.span() + self.repr.token.span() } pub fn set_span(&mut self, span: Span) { - self.token.set_span(span) + self.repr.token.set_span(span) + } + + pub fn suffix(&self) -> &str { + &self.repr.suffix } } impl LitInt { pub fn new(repr: &str, span: Span) -> Self { - if let Some((digits, suffix)) = value::parse_lit_int(repr) { - let mut token = value::to_literal(repr); - token.set_span(span); - LitInt { - repr: Box::new(LitIntRepr { - token, - digits, - suffix, - }), - } - } else { - panic!("Not an integer literal: `{}`", repr); + let (digits, suffix) = match value::parse_lit_int(repr) { + Some(parse) => parse, + None => panic!("Not an integer literal: `{}`", repr), + }; + + let mut token = match value::to_literal(repr, &digits, &suffix) { + Some(token) => token, + None => panic!("Unsupported integer literal: `{}`", repr), + }; + + token.set_span(span); + LitInt { + repr: Box::new(LitIntRepr { + token, + digits, + suffix, + }), } } @@ -492,18 +435,23 @@ impl Display for LitInt { impl LitFloat { pub fn new(repr: &str, span: Span) -> Self { - if let Some((digits, suffix)) = value::parse_lit_float(repr) { - let mut token = value::to_literal(repr); - token.set_span(span); - LitFloat { - repr: Box::new(LitFloatRepr { - token, - digits, - suffix, - }), - } - } else { - panic!("Not a float literal: `{}`", repr); + let (digits, suffix) = match value::parse_lit_float(repr) { + Some(parse) => parse, + None => panic!("Not a float literal: `{}`", repr), + }; + + let mut token = match value::to_literal(repr, &digits, &suffix) { + Some(token) => token, + None => panic!("Unsupported float literal: `{}`", repr), + }; + + token.set_span(span); + LitFloat { + repr: Box::new(LitFloatRepr { + token, + digits, + suffix, + }), } } @@ -557,11 +505,30 @@ impl Display for LitFloat { } } +impl LitBool { + pub fn new(value: bool, span: Span) -> Self { + LitBool { value, span } + } + + pub fn value(&self) -> bool { + self.value + } + + pub fn span(&self) -> Span { + self.span + } + + pub fn set_span(&mut self, span: Span) { + self.span = span; + } +} + #[cfg(feature = "extra-traits")] mod debug_impls { use super::*; use std::fmt::{self, Debug}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for LitStr { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter @@ -571,33 +538,37 @@ mod debug_impls { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for LitByteStr { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter .debug_struct("LitByteStr") - .field("token", &format_args!("{}", self.token)) + .field("token", &format_args!("{}", self.repr.token)) .finish() } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for LitByte { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter .debug_struct("LitByte") - .field("token", &format_args!("{}", self.token)) + .field("token", &format_args!("{}", self.repr.token)) .finish() } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for LitChar { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter .debug_struct("LitChar") - .field("token", &format_args!("{}", self.token)) + .field("token", &format_args!("{}", self.repr.token)) .finish() } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for LitInt { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter @@ -607,6 +578,7 @@ mod debug_impls { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for LitFloat { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter @@ -616,6 +588,7 @@ mod debug_impls { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for LitBool { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter @@ -626,25 +599,69 @@ mod debug_impls { } } +#[cfg(feature = "clone-impls")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for LitRepr { + fn clone(&self) -> Self { + LitRepr { + token: self.token.clone(), + suffix: self.suffix.clone(), + } + } +} + +#[cfg(feature = "clone-impls")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for LitIntRepr { + fn clone(&self) -> Self { + LitIntRepr { + token: self.token.clone(), + digits: self.digits.clone(), + suffix: self.suffix.clone(), + } + } +} + +#[cfg(feature = "clone-impls")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for LitFloatRepr { + fn clone(&self) -> Self { + LitFloatRepr { + token: self.token.clone(), + digits: self.digits.clone(), + suffix: self.suffix.clone(), + } + } +} + macro_rules! lit_extra_traits { - ($ty:ident, $($field:ident).+) => { - #[cfg(feature = "extra-traits")] - impl Eq for $ty {} + ($ty:ident) => { + #[cfg(feature = "clone-impls")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] + impl Clone for $ty { + fn clone(&self) -> Self { + $ty { + repr: self.repr.clone(), + } + } + } #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl PartialEq for $ty { fn eq(&self, other: &Self) -> bool { - self.$($field).+.to_string() == other.$($field).+.to_string() + self.repr.token.to_string() == other.repr.token.to_string() } } #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Hash for $ty { fn hash<H>(&self, state: &mut H) where H: Hasher, { - self.$($field).+.to_string().hash(state); + self.repr.token.to_string().hash(state); } } @@ -657,20 +674,23 @@ macro_rules! lit_extra_traits { }; } -lit_extra_traits!(LitStr, repr.token); -lit_extra_traits!(LitByteStr, token); -lit_extra_traits!(LitByte, token); -lit_extra_traits!(LitChar, token); -lit_extra_traits!(LitInt, repr.token); -lit_extra_traits!(LitFloat, repr.token); -lit_extra_traits!(LitBool, value); +lit_extra_traits!(LitStr); +lit_extra_traits!(LitByteStr); +lit_extra_traits!(LitByte); +lit_extra_traits!(LitChar); +lit_extra_traits!(LitInt); +lit_extra_traits!(LitFloat); + +#[cfg(feature = "parsing")] +#[doc(hidden)] +#[allow(non_snake_case)] +pub fn LitBool(marker: lookahead::TokenMarker) -> LitBool { + match marker {} +} ast_enum! { /// The style of a string literal, either plain quoted or a raw string like /// `r##"data"##`. - /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` - /// feature.* pub enum StrStyle #no_visit { /// An ordinary string like `"data"`. Cooked, @@ -691,98 +711,154 @@ pub fn Lit(marker: lookahead::TokenMarker) -> Lit { #[cfg(feature = "parsing")] pub mod parsing { use super::*; + use crate::buffer::Cursor; use crate::parse::{Parse, ParseStream, Result}; + use proc_macro2::Punct; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Lit { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| { if let Some((lit, rest)) = cursor.literal() { return Ok((Lit::new(lit), rest)); } - while let Some((ident, rest)) = cursor.ident() { - let value = if ident == "true" { - true - } else if ident == "false" { - false - } else { - break; - }; - let lit_bool = LitBool { - value, - span: ident.span(), - }; - return Ok((Lit::Bool(lit_bool), rest)); + + if let Some((ident, rest)) = cursor.ident() { + let value = ident == "true"; + if value || ident == "false" { + let lit_bool = LitBool { + value, + span: ident.span(), + }; + return Ok((Lit::Bool(lit_bool), rest)); + } } + + if let Some((punct, rest)) = cursor.punct() { + if punct.as_char() == '-' { + if let Some((lit, rest)) = parse_negative_lit(punct, rest) { + return Ok((lit, rest)); + } + } + } + Err(cursor.error("expected literal")) }) } } + fn parse_negative_lit(neg: Punct, cursor: Cursor) -> Option<(Lit, Cursor)> { + let (lit, rest) = cursor.literal()?; + + let mut span = neg.span(); + span = span.join(lit.span()).unwrap_or(span); + + let mut repr = lit.to_string(); + repr.insert(0, '-'); + + if let Some((digits, suffix)) = value::parse_lit_int(&repr) { + if let Some(mut token) = value::to_literal(&repr, &digits, &suffix) { + token.set_span(span); + return Some(( + Lit::Int(LitInt { + repr: Box::new(LitIntRepr { + token, + digits, + suffix, + }), + }), + rest, + )); + } + } + + let (digits, suffix) = value::parse_lit_float(&repr)?; + let mut token = value::to_literal(&repr, &digits, &suffix)?; + token.set_span(span); + Some(( + Lit::Float(LitFloat { + repr: Box::new(LitFloatRepr { + token, + digits, + suffix, + }), + }), + rest, + )) + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for LitStr { fn parse(input: ParseStream) -> Result<Self> { let head = input.fork(); - match input.parse()? { - Lit::Str(lit) => Ok(lit), + match input.parse() { + Ok(Lit::Str(lit)) => Ok(lit), _ => Err(head.error("expected string literal")), } } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for LitByteStr { fn parse(input: ParseStream) -> Result<Self> { let head = input.fork(); - match input.parse()? { - Lit::ByteStr(lit) => Ok(lit), + match input.parse() { + Ok(Lit::ByteStr(lit)) => Ok(lit), _ => Err(head.error("expected byte string literal")), } } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for LitByte { fn parse(input: ParseStream) -> Result<Self> { let head = input.fork(); - match input.parse()? { - Lit::Byte(lit) => Ok(lit), + match input.parse() { + Ok(Lit::Byte(lit)) => Ok(lit), _ => Err(head.error("expected byte literal")), } } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for LitChar { fn parse(input: ParseStream) -> Result<Self> { let head = input.fork(); - match input.parse()? { - Lit::Char(lit) => Ok(lit), + match input.parse() { + Ok(Lit::Char(lit)) => Ok(lit), _ => Err(head.error("expected character literal")), } } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for LitInt { fn parse(input: ParseStream) -> Result<Self> { let head = input.fork(); - match input.parse()? { - Lit::Int(lit) => Ok(lit), + match input.parse() { + Ok(Lit::Int(lit)) => Ok(lit), _ => Err(head.error("expected integer literal")), } } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for LitFloat { fn parse(input: ParseStream) -> Result<Self> { let head = input.fork(); - match input.parse()? { - Lit::Float(lit) => Ok(lit), + match input.parse() { + Ok(Lit::Float(lit)) => Ok(lit), _ => Err(head.error("expected floating point literal")), } } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for LitBool { fn parse(input: ParseStream) -> Result<Self> { let head = input.fork(); - match input.parse()? { - Lit::Bool(lit) => Ok(lit), + match input.parse() { + Ok(Lit::Bool(lit)) => Ok(lit), _ => Err(head.error("expected boolean literal")), } } @@ -795,42 +871,49 @@ mod printing { use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for LitStr { fn to_tokens(&self, tokens: &mut TokenStream) { self.repr.token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for LitByteStr { fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); + self.repr.token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for LitByte { fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); + self.repr.token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for LitChar { fn to_tokens(&self, tokens: &mut TokenStream) { - self.token.to_tokens(tokens); + self.repr.token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for LitInt { fn to_tokens(&self, tokens: &mut TokenStream) { self.repr.token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for LitFloat { fn to_tokens(&self, tokens: &mut TokenStream) { self.repr.token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for LitBool { fn to_tokens(&self, tokens: &mut TokenStream) { let s = if self.value { "true" } else { "false" }; @@ -855,32 +938,39 @@ mod value { b'"' | b'r' => { let (_, suffix) = parse_lit_str(&repr); return Lit::Str(LitStr { - repr: Box::new(LitStrRepr { token, suffix }), + repr: Box::new(LitRepr { token, suffix }), }); } b'b' => match byte(&repr, 1) { b'"' | b'r' => { - return Lit::ByteStr(LitByteStr { token }); + let (_, suffix) = parse_lit_byte_str(&repr); + return Lit::ByteStr(LitByteStr { + repr: Box::new(LitRepr { token, suffix }), + }); } b'\'' => { - return Lit::Byte(LitByte { token }); + let (_, suffix) = parse_lit_byte(&repr); + return Lit::Byte(LitByte { + repr: Box::new(LitRepr { token, suffix }), + }); } _ => {} }, b'\'' => { - return Lit::Char(LitChar { token }); + let (_, suffix) = parse_lit_char(&repr); + return Lit::Char(LitChar { + repr: Box::new(LitRepr { token, suffix }), + }); } b'0'..=b'9' | b'-' => { - if !(repr.ends_with("f32") || repr.ends_with("f64")) { - if let Some((digits, suffix)) = parse_lit_int(&repr) { - return Lit::Int(LitInt { - repr: Box::new(LitIntRepr { - token, - digits, - suffix, - }), - }); - } + if let Some((digits, suffix)) = parse_lit_int(&repr) { + return Lit::Int(LitInt { + repr: Box::new(LitIntRepr { + token, + digits, + suffix, + }), + }); } if let Some((digits, suffix)) = parse_lit_float(&repr) { return Lit::Float(LitFloat { @@ -905,6 +995,44 @@ mod value { panic!("Unrecognized literal: `{}`", repr); } + + pub fn suffix(&self) -> &str { + match self { + Lit::Str(lit) => lit.suffix(), + Lit::ByteStr(lit) => lit.suffix(), + Lit::Byte(lit) => lit.suffix(), + Lit::Char(lit) => lit.suffix(), + Lit::Int(lit) => lit.suffix(), + Lit::Float(lit) => lit.suffix(), + Lit::Bool(_) | Lit::Verbatim(_) => "", + } + } + + pub fn span(&self) -> Span { + match self { + Lit::Str(lit) => lit.span(), + Lit::ByteStr(lit) => lit.span(), + Lit::Byte(lit) => lit.span(), + Lit::Char(lit) => lit.span(), + Lit::Int(lit) => lit.span(), + Lit::Float(lit) => lit.span(), + Lit::Bool(lit) => lit.span, + Lit::Verbatim(lit) => lit.span(), + } + } + + pub fn set_span(&mut self, span: Span) { + match self { + Lit::Str(lit) => lit.set_span(span), + Lit::ByteStr(lit) => lit.set_span(span), + Lit::Byte(lit) => lit.set_span(span), + Lit::Char(lit) => lit.set_span(span), + Lit::Int(lit) => lit.set_span(span), + Lit::Float(lit) => lit.set_span(span), + Lit::Bool(lit) => lit.span = span, + Lit::Verbatim(lit) => lit.set_span(span), + } + } } /// Get the byte at offset idx, or a default of `b'\0'` if we're looking @@ -1004,19 +1132,18 @@ mod value { pounds += 1; } assert_eq!(byte(s, pounds), b'"'); - assert_eq!(byte(s, s.len() - pounds - 1), b'"'); - for end in s[s.len() - pounds..].bytes() { + let close = s.rfind('"').unwrap(); + for end in s[close + 1..close + 1 + pounds].bytes() { assert_eq!(end, b'#'); } - let content = s[pounds + 1..s.len() - pounds - 1] - .to_owned() - .into_boxed_str(); - let suffix = Box::<str>::default(); // todo + let content = s[pounds + 1..close].to_owned().into_boxed_str(); + let suffix = s[close + 1 + pounds..].to_owned().into_boxed_str(); (content, suffix) } - pub fn parse_lit_byte_str(s: &str) -> Vec<u8> { + // Returns (content, suffix). + pub fn parse_lit_byte_str(s: &str) -> (Vec<u8>, Box<str>) { assert_eq!(byte(s, 0), b'b'); match byte(s, 1) { b'"' => parse_lit_byte_str_cooked(s), @@ -1028,25 +1155,25 @@ mod value { // Clippy false positive // https://github.com/rust-lang-nursery/rust-clippy/issues/2329 #[allow(clippy::needless_continue)] - fn parse_lit_byte_str_cooked(mut s: &str) -> Vec<u8> { + fn parse_lit_byte_str_cooked(mut s: &str) -> (Vec<u8>, Box<str>) { assert_eq!(byte(s, 0), b'b'); assert_eq!(byte(s, 1), b'"'); s = &s[2..]; // We're going to want to have slices which don't respect codepoint boundaries. - let mut s = s.as_bytes(); + let mut v = s.as_bytes(); let mut out = Vec::new(); 'outer: loop { - let byte = match byte(s, 0) { + let byte = match byte(v, 0) { b'"' => break, b'\\' => { - let b = byte(s, 1); - s = &s[2..]; + let b = byte(v, 1); + v = &v[2..]; match b { b'x' => { - let (b, rest) = backslash_x(s); - s = rest; + let (b, rest) = backslash_x(v); + v = rest; b } b'n' => b'\n', @@ -1057,10 +1184,10 @@ mod value { b'\'' => b'\'', b'"' => b'"', b'\r' | b'\n' => loop { - let byte = byte(s, 0); + let byte = byte(v, 0); let ch = char::from_u32(u32::from(byte)).unwrap(); if ch.is_whitespace() { - s = &s[1..]; + v = &v[1..]; } else { continue 'outer; } @@ -1069,42 +1196,45 @@ mod value { } } b'\r' => { - assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string"); - s = &s[2..]; + assert_eq!(byte(v, 1), b'\n', "Bare CR not allowed in string"); + v = &v[2..]; b'\n' } b => { - s = &s[1..]; + v = &v[1..]; b } }; out.push(byte); } - assert_eq!(s, b"\""); - out + assert_eq!(byte(v, 0), b'"'); + let suffix = s[s.len() - v.len() + 1..].to_owned().into_boxed_str(); + (out, suffix) } - fn parse_lit_byte_str_raw(s: &str) -> Vec<u8> { + fn parse_lit_byte_str_raw(s: &str) -> (Vec<u8>, Box<str>) { assert_eq!(byte(s, 0), b'b'); - String::from(parse_lit_str_raw(&s[1..]).0).into_bytes() + let (value, suffix) = parse_lit_str_raw(&s[1..]); + (String::from(value).into_bytes(), suffix) } - pub fn parse_lit_byte(s: &str) -> u8 { + // Returns (value, suffix). + pub fn parse_lit_byte(s: &str) -> (u8, Box<str>) { assert_eq!(byte(s, 0), b'b'); assert_eq!(byte(s, 1), b'\''); // We're going to want to have slices which don't respect codepoint boundaries. - let mut s = s[2..].as_bytes(); + let mut v = s[2..].as_bytes(); - let b = match byte(s, 0) { + let b = match byte(v, 0) { b'\\' => { - let b = byte(s, 1); - s = &s[2..]; + let b = byte(v, 1); + v = &v[2..]; match b { b'x' => { - let (b, rest) = backslash_x(s); - s = rest; + let (b, rest) = backslash_x(v); + v = rest; b } b'n' => b'\n', @@ -1118,16 +1248,18 @@ mod value { } } b => { - s = &s[1..]; + v = &v[1..]; b } }; - assert_eq!(byte(s, 0), b'\''); - b + assert_eq!(byte(v, 0), b'\''); + let suffix = s[s.len() - v.len() + 1..].to_owned().into_boxed_str(); + (b, suffix) } - pub fn parse_lit_char(mut s: &str) -> char { + // Returns (value, suffix). + pub fn parse_lit_char(mut s: &str) -> (char, Box<str>) { assert_eq!(byte(s, 0), b'\''); s = &s[1..]; @@ -1163,8 +1295,9 @@ mod value { ch } }; - assert_eq!(s, "\'", "Expected end of char literal"); - ch + assert_eq!(byte(s, 0), b'\''); + let suffix = s[1..].to_owned().into_boxed_str(); + (ch, suffix) } fn backslash_x<S>(s: &S) -> (u8, &S) @@ -1192,32 +1325,33 @@ mod value { fn backslash_u(mut s: &str) -> (char, &str) { if byte(s, 0) != b'{' { - panic!("expected {{ after \\u"); + panic!("{}", "expected { after \\u"); } s = &s[1..]; let mut ch = 0; - for _ in 0..6 { + let mut digits = 0; + loop { let b = byte(s, 0); - match b { - b'0'..=b'9' => { - ch *= 0x10; - ch += u32::from(b - b'0'); - s = &s[1..]; - } - b'a'..=b'f' => { - ch *= 0x10; - ch += u32::from(10 + b - b'a'); - s = &s[1..]; - } - b'A'..=b'F' => { - ch *= 0x10; - ch += u32::from(10 + b - b'A'); + let digit = match b { + b'0'..=b'9' => b - b'0', + b'a'..=b'f' => 10 + b - b'a', + b'A'..=b'F' => 10 + b - b'A', + b'_' if digits > 0 => { s = &s[1..]; + continue; } + b'}' if digits == 0 => panic!("invalid empty unicode escape"), b'}' => break, _ => panic!("unexpected non-hex character after \\u"), + }; + if digits == 6 { + panic!("overlong unicode escape (must have at most 6 hex digits)"); } + ch *= 0x10; + ch += u32::from(digit); + digits += 1; + s = &s[1..]; } assert!(byte(s, 0) == b'}'); s = &s[1..]; @@ -1254,7 +1388,7 @@ mod value { }; let mut value = BigInt::new(); - loop { + 'outer: loop { let b = byte(s, 0); let digit = match b { b'0'..=b'9' => b - b'0', @@ -1264,10 +1398,32 @@ mod value { s = &s[1..]; continue; } - // NOTE: Looking at a floating point literal, we don't want to - // consider these integers. + // If looking at a floating point literal, we don't want to + // consider it an integer. b'.' if base == 10 => return None, - b'e' | b'E' if base == 10 => return None, + b'e' | b'E' if base == 10 => { + let mut has_exp = false; + for (i, b) in s[1..].bytes().enumerate() { + match b { + b'_' => {} + b'-' | b'+' => return None, + b'0'..=b'9' => has_exp = true, + _ => { + let suffix = &s[1 + i..]; + if has_exp && crate::ident::xid_ok(suffix) { + return None; + } else { + break 'outer; + } + } + } + } + if has_exp { + return None; + } else { + break; + } + } _ => break, }; @@ -1333,8 +1489,20 @@ mod value { bytes[write] = b'.'; } b'e' | b'E' => { + match bytes[read + 1..] + .iter() + .find(|b| **b != b'_') + .unwrap_or(&b'\0') + { + b'-' | b'+' | b'0'..=b'9' => {} + _ => break, + } if has_e { - return None; + if has_exponent { + break; + } else { + return None; + } } has_e = true; bytes[write] = b'e'; @@ -1372,11 +1540,35 @@ mod value { } } - pub fn to_literal(s: &str) -> Literal { - let stream = s.parse::<TokenStream>().unwrap(); - match stream.into_iter().next().unwrap() { - TokenTree::Literal(l) => l, - _ => unreachable!(), + pub fn to_literal(repr: &str, digits: &str, suffix: &str) -> Option<Literal> { + if repr.starts_with('-') { + let f64_parse_finite = || digits.parse().ok().filter(|x: &f64| x.is_finite()); + let f32_parse_finite = || digits.parse().ok().filter(|x: &f32| x.is_finite()); + if suffix == "f64" { + f64_parse_finite().map(Literal::f64_suffixed) + } else if suffix == "f32" { + f32_parse_finite().map(Literal::f32_suffixed) + } else if suffix == "i64" { + digits.parse().ok().map(Literal::i64_suffixed) + } else if suffix == "i32" { + digits.parse().ok().map(Literal::i32_suffixed) + } else if suffix == "i16" { + digits.parse().ok().map(Literal::i16_suffixed) + } else if suffix == "i8" { + digits.parse().ok().map(Literal::i8_suffixed) + } else if !suffix.is_empty() { + None + } else if digits.contains('.') { + f64_parse_finite().map(Literal::f64_unsuffixed) + } else { + digits.parse().ok().map(Literal::i64_unsuffixed) + } + } else { + let stream = repr.parse::<TokenStream>().unwrap(); + match stream.into_iter().next().unwrap() { + TokenTree::Literal(l) => Some(l), + _ => unreachable!(), + } } } } diff --git a/1.0.7/src/lookahead.rs b/src/lookahead.rs index 6a67909f..f0ed628e 100644 --- a/1.0.7/src/lookahead.rs +++ b/src/lookahead.rs @@ -1,12 +1,10 @@ -use std::cell::RefCell; - -use proc_macro2::{Delimiter, Span}; - 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::{Delimiter, Span}; +use std::cell::RefCell; /// Support for checking the next token in a stream to decide how to parse. /// diff --git a/1.0.7/src/mac.rs b/src/mac.rs index 6c3dcae9..3d84f8e4 100644 --- a/1.0.7/src/mac.rs +++ b/src/mac.rs @@ -2,21 +2,18 @@ use super::*; use crate::token::{Brace, Bracket, Paren}; use proc_macro2::TokenStream; #[cfg(feature = "parsing")] -use proc_macro2::{Delimiter, Span, TokenTree}; +use proc_macro2::{Delimiter, Group, Span, TokenTree}; #[cfg(feature = "parsing")] use crate::parse::{Parse, ParseStream, Parser, Result}; -#[cfg(feature = "extra-traits")] -use crate::tt::TokenStreamHelper; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; ast_struct! { /// A macro invocation: `println!("{}", mac)`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* - pub struct Macro #manual_extra_traits { + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct Macro { pub path: Path, pub bang_token: Token![!], pub delimiter: MacroDelimiter, @@ -27,8 +24,9 @@ ast_struct! { ast_enum! { /// A grouping token that surrounds a macro body: `m!(...)` or `m!{...}` or `m![...]`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum MacroDelimiter { Paren(Paren), Brace(Brace), @@ -36,39 +34,20 @@ ast_enum! { } } -#[cfg(feature = "extra-traits")] -impl Eq for Macro {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Macro { - fn eq(&self, other: &Self) -> bool { - self.path == other.path - && self.bang_token == other.bang_token - && self.delimiter == other.delimiter - && TokenStreamHelper(&self.tokens) == TokenStreamHelper(&other.tokens) - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Macro { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - self.path.hash(state); - self.bang_token.hash(state); - self.delimiter.hash(state); - TokenStreamHelper(&self.tokens).hash(state); - } -} - #[cfg(feature = "parsing")] -fn delimiter_span(delimiter: &MacroDelimiter) -> Span { - match delimiter { +fn delimiter_span_close(macro_delimiter: &MacroDelimiter) -> Span { + let delimiter = match macro_delimiter { + MacroDelimiter::Paren(_) => Delimiter::Parenthesis, + MacroDelimiter::Brace(_) => Delimiter::Brace, + MacroDelimiter::Bracket(_) => Delimiter::Bracket, + }; + let mut group = Group::new(delimiter, TokenStream::new()); + group.set_span(match macro_delimiter { MacroDelimiter::Paren(token) => token.span, MacroDelimiter::Brace(token) => token.span, MacroDelimiter::Bracket(token) => token.span, - } + }); + group.span_close() } impl Macro { @@ -155,6 +134,7 @@ impl Macro { /// } /// ``` #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_body<T: Parse>(&self) -> Result<T> { self.parse_body_with(T::parse) } @@ -162,10 +142,9 @@ impl Macro { /// Parse the tokens within the macro invocation's delimiters using the /// given parser. #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_body_with<F: Parser>(&self, parser: F) -> Result<F::Output> { - // TODO: see if we can get a group.span_close() span in here as the - // scope, rather than the span of the whole group. - let scope = delimiter_span(&self.delimiter); + let scope = delimiter_span_close(&self.delimiter); crate::parse::parse_scoped(parser, scope, self.tokens.clone()) } } @@ -193,9 +172,9 @@ pub fn parse_delimiter(input: ParseStream) -> Result<(MacroDelimiter, TokenStrea #[cfg(feature = "parsing")] pub mod parsing { use super::*; - use crate::parse::{Parse, ParseStream, Result}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Macro { fn parse(input: ParseStream) -> Result<Self> { let tokens; @@ -219,6 +198,7 @@ mod printing { use proc_macro2::TokenStream; use quote::ToTokens; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Macro { fn to_tokens(&self, tokens: &mut TokenStream) { self.path.to_tokens(tokens); diff --git a/1.0.7/src/macros.rs b/src/macros.rs index 57091c09..5097da94 100644 --- a/1.0.7/src/macros.rs +++ b/src/macros.rs @@ -4,15 +4,11 @@ macro_rules! ast_struct { struct $name:ident #full $($rest:tt)* ) => { #[cfg(feature = "full")] - #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] $($attrs_pub)* struct $name $($rest)* #[cfg(not(feature = "full"))] - #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] $($attrs_pub)* struct $name { - _noconstruct: (), + _noconstruct: ::std::marker::PhantomData<::proc_macro2::Span>, } #[cfg(all(not(feature = "full"), feature = "printing"))] @@ -25,27 +21,8 @@ macro_rules! ast_struct { ( [$($attrs_pub:tt)*] - struct $name:ident #manual_extra_traits $($rest:tt)* - ) => { - #[cfg_attr(feature = "extra-traits", derive(Debug))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] - $($attrs_pub)* struct $name $($rest)* - }; - - ( - [$($attrs_pub:tt)*] - struct $name:ident #manual_extra_traits_debug $($rest:tt)* - ) => { - #[cfg_attr(feature = "clone-impls", derive(Clone))] - $($attrs_pub)* struct $name $($rest)* - }; - - ( - [$($attrs_pub:tt)*] struct $name:ident $($rest:tt)* ) => { - #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] $($attrs_pub)* struct $name $($rest)* }; @@ -65,19 +42,8 @@ macro_rules! ast_enum { ( [$($attrs_pub:tt)*] - enum $name:ident #manual_extra_traits $($rest:tt)* - ) => ( - #[cfg_attr(feature = "extra-traits", derive(Debug))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] - $($attrs_pub)* enum $name $($rest)* - ); - - ( - [$($attrs_pub:tt)*] enum $name:ident $($rest:tt)* ) => ( - #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] - #[cfg_attr(feature = "clone-impls", derive(Clone))] $($attrs_pub)* enum $name $($rest)* ); @@ -111,7 +77,7 @@ macro_rules! ast_enum_of_structs_impl { $pub:ident $enum:ident $name:ident { $( $(#[$variant_attr:meta])* - $variant:ident $( ($member:ident) )*, + $variant:ident $( ($($member:ident)::+) )*, )* } @@ -121,7 +87,7 @@ macro_rules! ast_enum_of_structs_impl { check_keyword_matches!(enum $enum); $($( - ast_enum_from_struct!($name::$variant, $member); + ast_enum_from_struct!($name::$variant, $($member)::+); )*)* #[cfg(feature = "printing")] @@ -129,7 +95,7 @@ macro_rules! ast_enum_of_structs_impl { $($remaining)* () tokens - $name { $($variant $($member)*,)* } + $name { $($variant $($($member)::+)*,)* } } }; } @@ -138,6 +104,9 @@ macro_rules! ast_enum_from_struct { // No From<TokenStream> for verbatim variants. ($name:ident::Verbatim, $member:ident) => {}; + // No From<TokenStream> for private variants. + ($name:ident::$variant:ident, crate::private) => {}; + ($name:ident::$variant:ident, $member:ident) => { impl From<$member> for $name { fn from(e: $member) -> $name { @@ -165,7 +134,15 @@ macro_rules! generate_to_tokens { ); }; + (($($arms:tt)*) $tokens:ident $name:ident { $variant:ident crate::private, $($next:tt)*}) => { + generate_to_tokens!( + ($($arms)* $name::$variant(_) => unreachable!(),) + $tokens $name { $($next)* } + ); + }; + (($($arms:tt)*) $tokens:ident $name:ident {}) => { + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ::quote::ToTokens for $name { fn to_tokens(&self, $tokens: &mut ::proc_macro2::TokenStream) { match self { diff --git a/1.0.7/src/op.rs b/src/op.rs index 49fb853c..b8ef9a7f 100644 --- a/1.0.7/src/op.rs +++ b/src/op.rs @@ -1,9 +1,9 @@ ast_enum! { /// A binary operator: `+`, `+=`, `&`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* - #[cfg_attr(feature = "clone-impls", derive(Copy))] + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum BinOp { /// The `+` operator (addition) Add(Token![+]), @@ -67,9 +67,9 @@ ast_enum! { ast_enum! { /// A unary operator: `*`, `!`, `-`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* - #[cfg_attr(feature = "clone-impls", derive(Copy))] + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum UnOp { /// The `*` operator for dereferencing Deref(Token![*]), @@ -83,7 +83,6 @@ ast_enum! { #[cfg(feature = "parsing")] pub mod parsing { use super::*; - use crate::parse::{Parse, ParseStream, Result}; fn parse_binop(input: ParseStream) -> Result<BinOp> { @@ -128,6 +127,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for BinOp { #[cfg(not(feature = "full"))] fn parse(input: ParseStream) -> Result<Self> { @@ -162,6 +162,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for UnOp { fn parse(input: ParseStream) -> Result<Self> { let lookahead = input.lookahead1(); @@ -184,6 +185,7 @@ mod printing { use proc_macro2::TokenStream; use quote::ToTokens; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for BinOp { fn to_tokens(&self, tokens: &mut TokenStream) { match self { @@ -219,6 +221,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for UnOp { fn to_tokens(&self, tokens: &mut TokenStream) { match self { diff --git a/1.0.7/src/parse.rs b/src/parse.rs index 0dd698ba..d85968bd 100644 --- a/1.0.7/src/parse.rs +++ b/src/parse.rs @@ -6,9 +6,8 @@ //! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of //! tokens in a token stream. //! -//! [`ParseStream`]: type.ParseStream.html -//! [`Result<T>`]: type.Result.html -//! [`Cursor`]: ../buffer/index.html +//! [`Result<T>`]: Result +//! [`Cursor`]: crate::buffer::Cursor //! //! # Example //! @@ -23,11 +22,11 @@ //! procedural macro, they will receive a helpful compiler error message //! pointing out the exact token that triggered the failure to parse. //! -//! [`parse_macro_input!`]: ../macro.parse_macro_input.html +//! [`parse_macro_input!`]: crate::parse_macro_input! //! //! ``` -//! extern crate proc_macro; -//! +//! # extern crate proc_macro; +//! # //! use proc_macro::TokenStream; //! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token}; //! use syn::parse::{Parse, ParseStream}; @@ -96,10 +95,9 @@ //! obvious default way. These functions can return any syntax tree node that //! implements the [`Parse`] trait, which includes most types in Syn. //! -//! [`syn::parse`]: ../fn.parse.html -//! [`syn::parse2`]: ../fn.parse2.html -//! [`syn::parse_str`]: ../fn.parse_str.html -//! [`Parse`]: trait.Parse.html +//! [`syn::parse`]: crate::parse() +//! [`syn::parse2`]: crate::parse2() +//! [`syn::parse_str`]: crate::parse_str() //! //! ``` //! use syn::Type; @@ -114,7 +112,7 @@ //! //! The [`parse_quote!`] macro also uses this approach. //! -//! [`parse_quote!`]: ../macro.parse_quote.html +//! [`parse_quote!`]: crate::parse_quote! //! //! # The `Parser` trait //! @@ -124,8 +122,8 @@ //! may or may not allow trailing punctuation, and parsing it the wrong way //! would either reject valid input or accept invalid input. //! -//! [`Attribute`]: ../struct.Attribute.html -//! [`Punctuated`]: ../punctuated/index.html +//! [`Attribute`]: crate::Attribute +//! [`Punctuated`]: crate::punctuated //! //! The `Parse` trait is not implemented in these cases because there is no good //! behavior to consider the default. @@ -150,11 +148,10 @@ //! single `Parse` implementation, and those parser functions can be invoked //! through the [`Parser`] trait. //! -//! [`Parser`]: trait.Parser.html //! //! ``` -//! extern crate proc_macro; -//! +//! # extern crate proc_macro; +//! # //! use proc_macro::TokenStream; //! use syn::parse::Parser; //! use syn::punctuated::Punctuated; @@ -184,37 +181,40 @@ //! //! --- //! -//! *This module is available if Syn is built with the `"parsing"` feature.* +//! *This module is available only if Syn is built with the `"parsing"` feature.* #[path = "discouraged.rs"] pub mod discouraged; -use std::cell::Cell; -use std::fmt::{self, Debug, Display}; -use std::marker::PhantomData; -use std::mem; -use std::ops::Deref; -use std::rc::Rc; -use std::str::FromStr; - +use crate::buffer::{Cursor, TokenBuffer}; +use crate::error; +use crate::lookahead; #[cfg(all( not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), feature = "proc-macro" ))] use crate::proc_macro; -use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree}; - -use crate::buffer::{Cursor, TokenBuffer}; -use crate::error; -use crate::lookahead; use crate::punctuated::Punctuated; use crate::token::Token; +use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree}; +use std::cell::Cell; +use std::fmt::{self, Debug, Display}; +use std::marker::PhantomData; +use std::mem; +use std::ops::Deref; +use std::rc::Rc; +use std::str::FromStr; pub use crate::error::{Error, Result}; pub use crate::lookahead::{Lookahead1, Peek}; /// Parsing interface implemented by all types that can be parsed in a default /// way from a token stream. +/// +/// Refer to the [module documentation] for details about implementing and using +/// the `Parse` trait. +/// +/// [module documentation]: self pub trait Parse: Sized { fn parse(input: ParseStream) -> Result<Self>; } @@ -245,7 +245,7 @@ pub type ParseStream<'a> = &'a ParseBuffer<'a>; /// - One of [the `syn::parse*` functions][syn-parse]; or /// - A method of the [`Parser`] trait. /// -/// [syn-parse]: index.html#the-synparse-functions +/// [syn-parse]: self#the-synparse-functions pub struct ParseBuffer<'a> { scope: Span, // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a. @@ -261,13 +261,16 @@ pub struct ParseBuffer<'a> { // the cell. cell: Cell<Cursor<'static>>, marker: PhantomData<Cursor<'a>>, - unexpected: Rc<Cell<Option<Span>>>, + unexpected: Cell<Option<Rc<Cell<Unexpected>>>>, } impl<'a> Drop for ParseBuffer<'a> { fn drop(&mut self) { - if !self.is_empty() && self.unexpected.get().is_none() { - self.unexpected.set(Some(self.cursor().span())); + if let Some(unexpected_span) = span_of_unexpected_ignoring_nones(self.cursor()) { + let (inner, old_span) = inner_unexpected(self); + if old_span.is_none() { + inner.set(Unexpected::Some(unexpected_span)); + } } } } @@ -328,7 +331,6 @@ impl<'a> Debug for ParseBuffer<'a> { /// # .unwrap(); /// # assert_eq!(remainder.to_string(), "b c"); /// ``` -#[derive(Copy, Clone)] pub struct StepCursor<'c, 'a> { scope: Span, // This field is covariant in 'c. @@ -352,6 +354,14 @@ impl<'c, 'a> Deref for StepCursor<'c, 'a> { } } +impl<'c, 'a> Copy for StepCursor<'c, 'a> {} + +impl<'c, 'a> Clone for StepCursor<'c, 'a> { + fn clone(&self) -> Self { + *self + } +} + impl<'c, 'a> StepCursor<'c, 'a> { /// Triggers an error at the current position of the parse stream. /// @@ -371,36 +381,81 @@ pub(crate) fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor< unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) } } -fn skip(input: ParseStream) -> bool { - input - .step(|cursor| { - if let Some((_lifetime, rest)) = cursor.lifetime() { - Ok((true, rest)) - } else if let Some((_token, rest)) = cursor.token_tree() { - Ok((true, rest)) - } else { - Ok((false, *cursor)) - } - }) - .unwrap() -} - pub(crate) fn new_parse_buffer( scope: Span, cursor: Cursor, - unexpected: Rc<Cell<Option<Span>>>, + unexpected: Rc<Cell<Unexpected>>, ) -> ParseBuffer { ParseBuffer { scope, // See comment on `cell` in the struct definition. cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }), marker: PhantomData, - unexpected, + unexpected: Cell::new(Some(unexpected)), } } -pub(crate) fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> { - buffer.unexpected.clone() +pub(crate) enum Unexpected { + None, + Some(Span), + Chain(Rc<Cell<Unexpected>>), +} + +impl Default for Unexpected { + fn default() -> Self { + Unexpected::None + } +} + +impl Clone for Unexpected { + fn clone(&self) -> Self { + match self { + Unexpected::None => Unexpected::None, + Unexpected::Some(span) => Unexpected::Some(*span), + Unexpected::Chain(next) => Unexpected::Chain(next.clone()), + } + } +} + +// We call this on Cell<Unexpected> and Cell<Option<T>> where temporarily +// swapping in a None is cheap. +fn cell_clone<T: Default + Clone>(cell: &Cell<T>) -> T { + let prev = cell.take(); + let ret = prev.clone(); + cell.set(prev); + ret +} + +fn inner_unexpected(buffer: &ParseBuffer) -> (Rc<Cell<Unexpected>>, Option<Span>) { + let mut unexpected = get_unexpected(buffer); + loop { + match cell_clone(&unexpected) { + Unexpected::None => return (unexpected, None), + Unexpected::Some(span) => return (unexpected, Some(span)), + Unexpected::Chain(next) => unexpected = next, + } + } +} + +pub(crate) fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Unexpected>> { + cell_clone(&buffer.unexpected).unwrap() +} + +fn span_of_unexpected_ignoring_nones(mut cursor: Cursor) -> Option<Span> { + if cursor.eof() { + return None; + } + while let Some((inner, _span, rest)) = cursor.group(Delimiter::None) { + if let Some(unexpected) = span_of_unexpected_ignoring_nones(inner) { + return Some(unexpected); + } + cursor = rest; + } + if cursor.eof() { + None + } else { + Some(cursor.span()) + } } impl<'a> ParseBuffer<'a> { @@ -562,14 +617,36 @@ impl<'a> ParseBuffer<'a> { /// } /// ``` pub fn peek2<T: Peek>(&self, token: T) -> bool { - let ahead = self.fork(); - skip(&ahead) && ahead.peek(token) + fn peek2(buffer: &ParseBuffer, peek: fn(Cursor) -> bool) -> bool { + if let Some(group) = buffer.cursor().group(Delimiter::None) { + if group.0.skip().map_or(false, peek) { + return true; + } + } + buffer.cursor().skip().map_or(false, peek) + } + + let _ = token; + peek2(self, T::Token::peek) } /// Looks at the third-next token in the parse stream. pub fn peek3<T: Peek>(&self, token: T) -> bool { - let ahead = self.fork(); - skip(&ahead) && skip(&ahead) && ahead.peek(token) + fn peek3(buffer: &ParseBuffer, peek: fn(Cursor) -> bool) -> bool { + if let Some(group) = buffer.cursor().group(Delimiter::None) { + if group.0.skip().and_then(Cursor::skip).map_or(false, peek) { + return true; + } + } + buffer + .cursor() + .skip() + .and_then(Cursor::skip) + .map_or(false, peek) + } + + let _ = token; + peek3(self, T::Token::peek) } /// Parses zero or more occurrences of `T` separated by punctuation of type @@ -841,8 +918,8 @@ impl<'a> ParseBuffer<'a> { cell: self.cell.clone(), marker: PhantomData, // Not the parent's unexpected. Nothing cares whether the clone - // parses all the way. - unexpected: Rc::new(Cell::new(None)), + // parses all the way unless we `advance_to`. + unexpected: Cell::new(Some(Rc::new(Cell::new(Unexpected::None)))), } } @@ -953,6 +1030,18 @@ impl<'a> ParseBuffer<'a> { Ok(node) } + /// Returns the `Span` of the next token in the parse stream, or + /// `Span::call_site()` if this parse stream has completely exhausted its + /// input `TokenStream`. + pub fn span(&self) -> Span { + let cursor = self.cursor(); + if cursor.eof() { + self.scope + } else { + crate::buffer::open_span_of_group(cursor) + } + } + /// Provides low-level access to the token representation underlying this /// parse stream. /// @@ -963,19 +1052,21 @@ impl<'a> ParseBuffer<'a> { } fn check_unexpected(&self) -> Result<()> { - match self.unexpected.get() { + match inner_unexpected(self).1 { Some(span) => Err(Error::new(span, "unexpected token")), None => Ok(()), } } } +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl<T: Parse> Parse for Box<T> { fn parse(input: ParseStream) -> Result<Self> { input.parse().map(Box::new) } } +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl<T: Parse + Token> Parse for Option<T> { fn parse(input: ParseStream) -> Result<Self> { if T::peek(input.cursor()) { @@ -986,12 +1077,14 @@ impl<T: Parse + Token> Parse for Option<T> { } } +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TokenStream { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty()))) } } +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TokenTree { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| match cursor.token_tree() { @@ -1001,6 +1094,7 @@ impl Parse for TokenTree { } } +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Group { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| { @@ -1016,6 +1110,7 @@ impl Parse for Group { } } +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Punct { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| match cursor.punct() { @@ -1025,6 +1120,7 @@ impl Parse for Punct { } } +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Literal { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| match cursor.literal() { @@ -1040,7 +1136,7 @@ impl Parse for Literal { /// /// [module documentation]: self /// -/// *This trait is available if Syn is built with the `"parsing"` feature.* +/// *This trait is available only if Syn is built with the `"parsing"` feature.* pub trait Parser: Sized { type Output; @@ -1055,7 +1151,7 @@ pub trait Parser: Sized { /// 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 method is available if Syn is built with both the `"parsing"` and + /// *This method is available only if Syn is built with both the `"parsing"` and /// `"proc-macro"` features.* #[cfg(all( not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), @@ -1080,6 +1176,7 @@ pub trait Parser: Sized { // Not public API. #[doc(hidden)] + #[cfg(any(feature = "full", feature = "derive"))] fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> { let _ = scope; self.parse2(tokens) @@ -1087,6 +1184,7 @@ pub trait Parser: Sized { // Not public API. #[doc(hidden)] + #[cfg(any(feature = "full", feature = "derive"))] fn __parse_stream(self, input: ParseStream) -> Result<Self::Output> { input.parse().and_then(|tokens| self.parse2(tokens)) } @@ -1095,7 +1193,7 @@ pub trait Parser: Sized { fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer { let scope = Span::call_site(); let cursor = tokens.begin(); - let unexpected = Rc::new(Cell::new(None)); + let unexpected = Rc::new(Cell::new(Unexpected::None)); new_parse_buffer(scope, cursor, unexpected) } @@ -1110,38 +1208,42 @@ where let state = tokens_to_parse_buffer(&buf); let node = self(&state)?; state.check_unexpected()?; - if state.is_empty() { - Ok(node) + if let Some(unexpected_span) = span_of_unexpected_ignoring_nones(state.cursor()) { + Err(Error::new(unexpected_span, "unexpected token")) } else { - Err(state.error("unexpected token")) + Ok(node) } } #[doc(hidden)] + #[cfg(any(feature = "full", feature = "derive"))] fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> { let buf = TokenBuffer::new2(tokens); let cursor = buf.begin(); - let unexpected = Rc::new(Cell::new(None)); + let unexpected = Rc::new(Cell::new(Unexpected::None)); let state = new_parse_buffer(scope, cursor, unexpected); let node = self(&state)?; state.check_unexpected()?; - if state.is_empty() { - Ok(node) + if let Some(unexpected_span) = span_of_unexpected_ignoring_nones(state.cursor()) { + Err(Error::new(unexpected_span, "unexpected token")) } else { - Err(state.error("unexpected token")) + Ok(node) } } #[doc(hidden)] + #[cfg(any(feature = "full", feature = "derive"))] fn __parse_stream(self, input: ParseStream) -> Result<Self::Output> { self(input) } } +#[cfg(any(feature = "full", feature = "derive"))] pub(crate) fn parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output> { f.__parse_scoped(scope, tokens) } +#[cfg(any(feature = "full", feature = "derive"))] pub(crate) fn parse_stream<F: Parser>(f: F, input: ParseStream) -> Result<F::Output> { f.__parse_stream(input) } @@ -1152,8 +1254,8 @@ pub(crate) fn parse_stream<F: Parser>(f: F, input: ParseStream) -> Result<F::Out /// provided any attribute args. /// /// ``` -/// extern crate proc_macro; -/// +/// # extern crate proc_macro; +/// # /// use proc_macro::TokenStream; /// use syn::parse_macro_input; /// use syn::parse::Nothing; diff --git a/1.0.7/src/parse_macro_input.rs b/src/parse_macro_input.rs index d6e0725c..8e1a5ec6 100644 --- a/1.0.7/src/parse_macro_input.rs +++ b/src/parse_macro_input.rs @@ -16,8 +16,8 @@ /// #\[proc_macro_attribute\] attribute. /// /// ``` -/// extern crate proc_macro; -/// +/// # extern crate proc_macro; +/// # /// use proc_macro::TokenStream; /// use syn::{parse_macro_input, Result}; /// use syn::parse::{Parse, ParseStream}; @@ -43,18 +43,87 @@ /// # "".parse().unwrap() /// } /// ``` -#[macro_export(local_inner_macros)] +/// +/// <br> +/// +/// # Usage with Parser +/// +/// This macro can also be used with the [`Parser` trait] for types that have +/// multiple ways that they can be parsed. +/// +/// [`Parser` trait]: crate::rustdoc_workaround::parse_module::Parser +/// +/// ``` +/// # extern crate proc_macro; +/// # +/// # use proc_macro::TokenStream; +/// # use syn::{parse_macro_input, Result}; +/// # use syn::parse::ParseStream; +/// # +/// # struct MyMacroInput {} +/// # +/// impl MyMacroInput { +/// fn parse_alternate(input: ParseStream) -> Result<Self> { +/// /* ... */ +/// # Ok(MyMacroInput {}) +/// } +/// } +/// +/// # const IGNORE: &str = stringify! { +/// #[proc_macro] +/// # }; +/// pub fn my_macro(tokens: TokenStream) -> TokenStream { +/// let input = parse_macro_input!(tokens with MyMacroInput::parse_alternate); +/// +/// /* ... */ +/// # "".parse().unwrap() +/// } +/// ``` +/// +/// <br> +/// +/// # Expansion +/// +/// `parse_macro_input!($variable as $Type)` expands to something like: +/// +/// ```no_run +/// # extern crate proc_macro; +/// # +/// # macro_rules! doc_test { +/// # ($variable:ident as $Type:ty) => { +/// match syn::parse::<$Type>($variable) { +/// Ok(syntax_tree) => syntax_tree, +/// Err(err) => return proc_macro::TokenStream::from(err.to_compile_error()), +/// } +/// # }; +/// # } +/// # +/// # fn test(input: proc_macro::TokenStream) -> proc_macro::TokenStream { +/// # let _ = doc_test!(input as syn::Ident); +/// # proc_macro::TokenStream::new() +/// # } +/// ``` +#[macro_export] +#[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "proc-macro"))))] macro_rules! parse_macro_input { ($tokenstream:ident as $ty:ty) => { match $crate::parse_macro_input::parse::<$ty>($tokenstream) { - $crate::export::Ok(data) => data, - $crate::export::Err(err) => { - return $crate::export::TokenStream::from(err.to_compile_error()); + $crate::__private::Ok(data) => data, + $crate::__private::Err(err) => { + return $crate::__private::TokenStream::from(err.to_compile_error()); + } + } + }; + ($tokenstream:ident with $parser:path) => { + match $crate::parse::Parser::parse($parser, $tokenstream) { + $crate::__private::Ok(data) => data, + $crate::__private::Err(err) => { + return $crate::__private::TokenStream::from(err.to_compile_error()); } } }; ($tokenstream:ident) => { - parse_macro_input!($tokenstream as _) + $crate::parse_macro_input!($tokenstream as _) }; } diff --git a/1.0.7/src/parse_quote.rs b/src/parse_quote.rs index 18a47b95..ec551ef9 100644 --- a/1.0.7/src/parse_quote.rs +++ b/src/parse_quote.rs @@ -6,7 +6,7 @@ /// The return type can be any syntax tree node that implements the [`Parse`] /// trait. /// -/// [`Parse`]: parse::Parse +/// [`Parse`]: crate::parse::Parse /// /// ``` /// use quote::quote; @@ -24,7 +24,7 @@ /// } /// ``` /// -/// *This macro is available if Syn is built with the `"parsing"` feature, +/// *This macro is available only if Syn is built with the `"parsing"` feature, /// although interpolation of syntax tree nodes into the quoted tokens is only /// supported if Syn is built with the `"printing"` feature as well.* /// @@ -56,8 +56,10 @@ /// or inner like `#![...]` /// - [`Punctuated<T, P>`] — parses zero or more `T` separated by punctuation /// `P` with optional trailing punctuation +/// - [`Vec<Stmt>`] — parses the same as `Block::parse_within` /// -/// [`Punctuated<T, P>`]: punctuated::Punctuated +/// [`Punctuated<T, P>`]: crate::punctuated::Punctuated +/// [`Vec<Stmt>`]: Block::parse_within /// /// # Panics /// @@ -67,12 +69,13 @@ // // TODO: allow Punctuated to be inferred as intra doc link, currently blocked on // https://github.com/rust-lang/rust/issues/62834 -#[macro_export(local_inner_macros)] +#[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "printing"))))] +#[macro_export] macro_rules! parse_quote { ($($tt:tt)*) => { $crate::parse_quote::parse( - $crate::export::From::from( - $crate::export::quote::quote!($($tt)*) + $crate::__private::From::from( + $crate::__private::quote::quote!($($tt)*) ) ) }; @@ -112,6 +115,8 @@ impl<T: Parse> ParseQuote for T { use crate::punctuated::Punctuated; #[cfg(any(feature = "full", feature = "derive"))] use crate::{attr, Attribute}; +#[cfg(feature = "full")] +use crate::{Block, Stmt}; #[cfg(any(feature = "full", feature = "derive"))] impl ParseQuote for Attribute { @@ -129,3 +134,10 @@ impl<T: Parse, P: Parse> ParseQuote for Punctuated<T, P> { Self::parse_terminated(input) } } + +#[cfg(feature = "full")] +impl ParseQuote for Vec<Stmt> { + fn parse(input: ParseStream) -> Result<Self> { + Block::parse_within(input) + } +} diff --git a/1.0.7/src/pat.rs b/src/pat.rs index 262129b5..d25843fc 100644 --- a/1.0.7/src/pat.rs +++ b/src/pat.rs @@ -1,26 +1,20 @@ use super::*; use crate::punctuated::Punctuated; -#[cfg(feature = "extra-traits")] -use crate::tt::TokenStreamHelper; use proc_macro2::TokenStream; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; ast_enum_of_structs! { /// A pattern in a local binding, function signature, match expression, or /// various other places. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Pat #manual_extra_traits { + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub enum Pat { /// A box pattern: `box v`. Box(PatBox), @@ -78,15 +72,39 @@ ast_enum_of_structs! { /// A pattern that matches any value: `_`. Wild(PatWild), + // The following is the only supported idiom for exhaustive matching of + // this enum. + // + // match expr { + // Pat::Box(e) => {...} + // Pat::Ident(e) => {...} + // ... + // Pat::Wild(e) => {...} + // + // #[cfg(test)] + // Pat::__TestExhaustive(_) => unimplemented!(), + // #[cfg(not(test))] + // _ => { /* some sane fallback */ } + // } + // + // This way we fail your tests but don't break your library when adding + // a variant. You will be notified by a test failure when a variant is + // added, so that you can add code to handle it, but your library will + // continue to compile and work for downstream users in the interim. + // + // Once `deny(reachable)` is available in rustc, Pat will be + // reimplemented as a non_exhaustive enum. + // https://github.com/rust-lang/rust/issues/44109#issuecomment-521781237 #[doc(hidden)] - __Nonexhaustive, + __TestExhaustive(crate::private), } } ast_struct! { /// A box pattern: `box v`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatBox { pub attrs: Vec<Attribute>, pub box_token: Token![box], @@ -97,7 +115,11 @@ ast_struct! { ast_struct! { /// A pattern that binds a new variable: `ref mut binding @ SUBPATTERN`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// It may also be a unit struct or struct variant (e.g. `None`), or a + /// constant; these cannot be distinguished syntactically. + /// + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatIdent { pub attrs: Vec<Attribute>, pub by_ref: Option<Token![ref]>, @@ -113,7 +135,8 @@ ast_struct! { /// This holds an `Expr` rather than a `Lit` because negative numbers /// are represented as an `Expr::Unary`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatLit { pub attrs: Vec<Attribute>, pub expr: Box<Expr>, @@ -123,7 +146,8 @@ ast_struct! { ast_struct! { /// A macro in pattern position. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatMacro { pub attrs: Vec<Attribute>, pub mac: Macro, @@ -133,7 +157,8 @@ ast_struct! { ast_struct! { /// A pattern that matches any one of a set of cases. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatOr { pub attrs: Vec<Attribute>, pub leading_vert: Option<Token![|]>, @@ -150,7 +175,8 @@ ast_struct! { /// `<A>::B::C` and `<A as Trait>::B::C` can only legally refer to /// associated constants. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatPath { pub attrs: Vec<Attribute>, pub qself: Option<QSelf>, @@ -161,7 +187,8 @@ ast_struct! { ast_struct! { /// A range pattern: `1..=2`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatRange { pub attrs: Vec<Attribute>, pub lo: Box<Expr>, @@ -173,7 +200,8 @@ ast_struct! { ast_struct! { /// A reference pattern: `&mut var`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatReference { pub attrs: Vec<Attribute>, pub and_token: Token![&], @@ -185,7 +213,8 @@ ast_struct! { ast_struct! { /// The dots in a tuple or slice pattern: `[0, 1, ..]` /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatRest { pub attrs: Vec<Attribute>, pub dot2_token: Token![..], @@ -195,7 +224,8 @@ ast_struct! { ast_struct! { /// A dynamically sized slice pattern: `[a, b, ref i @ .., y, z]`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatSlice { pub attrs: Vec<Attribute>, pub bracket_token: token::Bracket, @@ -206,7 +236,8 @@ ast_struct! { ast_struct! { /// A struct or struct variant pattern: `Variant { x, y, .. }`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatStruct { pub attrs: Vec<Attribute>, pub path: Path, @@ -219,7 +250,8 @@ ast_struct! { ast_struct! { /// A tuple pattern: `(a, b)`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatTuple { pub attrs: Vec<Attribute>, pub paren_token: token::Paren, @@ -230,7 +262,8 @@ ast_struct! { ast_struct! { /// A tuple struct or tuple variant pattern: `Variant(x, y, .., z)`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatTupleStruct { pub attrs: Vec<Attribute>, pub path: Path, @@ -241,7 +274,8 @@ ast_struct! { ast_struct! { /// A type ascription pattern: `foo: f64`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatType { pub attrs: Vec<Attribute>, pub pat: Box<Pat>, @@ -253,7 +287,8 @@ ast_struct! { ast_struct! { /// A pattern that matches any value: `_`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct PatWild { pub attrs: Vec<Attribute>, pub underscore_token: Token![_], @@ -266,7 +301,8 @@ ast_struct! { /// Patterns like the fields of Foo `{ x, ref y, ref mut z }` are treated /// the same as `x: x, y: ref y, z: ref mut z` but there is no colon token. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct FieldPat { pub attrs: Vec<Attribute>, pub member: Member, @@ -275,143 +311,35 @@ ast_struct! { } } -#[cfg(feature = "extra-traits")] -impl Eq for Pat {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Pat { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Pat::Box(this), Pat::Box(other)) => this == other, - (Pat::Ident(this), Pat::Ident(other)) => this == other, - (Pat::Lit(this), Pat::Lit(other)) => this == other, - (Pat::Macro(this), Pat::Macro(other)) => this == other, - (Pat::Or(this), Pat::Or(other)) => this == other, - (Pat::Path(this), Pat::Path(other)) => this == other, - (Pat::Range(this), Pat::Range(other)) => this == other, - (Pat::Reference(this), Pat::Reference(other)) => this == other, - (Pat::Rest(this), Pat::Rest(other)) => this == other, - (Pat::Slice(this), Pat::Slice(other)) => this == other, - (Pat::Struct(this), Pat::Struct(other)) => this == other, - (Pat::Tuple(this), Pat::Tuple(other)) => this == other, - (Pat::TupleStruct(this), Pat::TupleStruct(other)) => this == other, - (Pat::Type(this), Pat::Type(other)) => this == other, - (Pat::Verbatim(this), Pat::Verbatim(other)) => { - TokenStreamHelper(this) == TokenStreamHelper(other) - } - (Pat::Wild(this), Pat::Wild(other)) => this == other, - _ => false, - } - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Pat { - fn hash<H>(&self, hash: &mut H) - where - H: Hasher, - { - match self { - Pat::Box(pat) => { - hash.write_u8(0); - pat.hash(hash); - } - Pat::Ident(pat) => { - hash.write_u8(1); - pat.hash(hash); - } - Pat::Lit(pat) => { - hash.write_u8(2); - pat.hash(hash); - } - Pat::Macro(pat) => { - hash.write_u8(3); - pat.hash(hash); - } - Pat::Or(pat) => { - hash.write_u8(4); - pat.hash(hash); - } - Pat::Path(pat) => { - hash.write_u8(5); - pat.hash(hash); - } - Pat::Range(pat) => { - hash.write_u8(6); - pat.hash(hash); - } - Pat::Reference(pat) => { - hash.write_u8(7); - pat.hash(hash); - } - Pat::Rest(pat) => { - hash.write_u8(8); - pat.hash(hash); - } - Pat::Slice(pat) => { - hash.write_u8(9); - pat.hash(hash); - } - Pat::Struct(pat) => { - hash.write_u8(10); - pat.hash(hash); - } - Pat::Tuple(pat) => { - hash.write_u8(11); - pat.hash(hash); - } - Pat::TupleStruct(pat) => { - hash.write_u8(12); - pat.hash(hash); - } - Pat::Type(pat) => { - hash.write_u8(13); - pat.hash(hash); - } - Pat::Verbatim(pat) => { - hash.write_u8(14); - TokenStreamHelper(pat).hash(hash); - } - Pat::Wild(pat) => { - hash.write_u8(15); - pat.hash(hash); - } - Pat::__Nonexhaustive => unreachable!(), - } - } -} - #[cfg(feature = "parsing")] -mod parsing { +pub mod parsing { use super::*; - use crate::ext::IdentExt; - use crate::parse::{Parse, ParseStream, Result}; + use crate::parse::{Parse, ParseBuffer, ParseStream, Result}; use crate::path; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Pat { fn parse(input: ParseStream) -> Result<Self> { + let begin = input.fork(); let lookahead = input.lookahead1(); - if lookahead.peek(Ident) - && ({ - input.peek2(Token![::]) - || input.peek2(Token![!]) - || input.peek2(token::Brace) - || input.peek2(token::Paren) - || input.peek2(Token![..]) - && !{ - let ahead = input.fork(); - ahead.parse::<Ident>()?; - ahead.parse::<RangeLimits>()?; - ahead.is_empty() || ahead.peek(Token![,]) - } - }) - || input.peek(Token![self]) && input.peek2(Token![::]) - || lookahead.peek(Token![::]) + if { + let ahead = input.fork(); + ahead.parse::<Option<Ident>>()?.is_some() + && (ahead.peek(Token![::]) + || ahead.peek(Token![!]) + || ahead.peek(token::Brace) + || ahead.peek(token::Paren) + || ahead.peek(Token![..]) + && ahead.parse::<RangeLimits>().is_ok() + && !(ahead.is_empty() || ahead.peek(Token![,]))) + } || { + let ahead = input.fork(); + ahead.parse::<Option<Token![self]>>()?.is_some() && ahead.peek(Token![::]) + } || lookahead.peek(Token![::]) || lookahead.peek(Token![<]) || input.peek(Token![Self]) || input.peek(Token![super]) - || input.peek(Token![extern]) || input.peek(Token![crate]) { pat_path_or_macro_or_struct_or_range(input) @@ -419,7 +347,8 @@ mod parsing { input.call(pat_wild).map(Pat::Wild) } else if input.peek(Token![box]) { input.call(pat_box).map(Pat::Box) - } else if input.peek(Token![-]) || lookahead.peek(Lit) { + } else if input.peek(Token![-]) || lookahead.peek(Lit) || lookahead.peek(Token![const]) + { pat_lit_or_range(input) } else if lookahead.peek(Token![ref]) || lookahead.peek(Token![mut]) @@ -434,7 +363,9 @@ mod parsing { } else if lookahead.peek(token::Bracket) { input.call(pat_slice).map(Pat::Slice) } else if lookahead.peek(Token![..]) && !input.peek(Token![...]) { - input.call(pat_rest).map(Pat::Rest) + pat_range_half_open(input, begin) + } else if lookahead.peek(Token![const]) { + input.call(pat_const).map(Pat::Verbatim) } else { Err(lookahead.error()) } @@ -442,10 +373,11 @@ mod parsing { } fn pat_path_or_macro_or_struct_or_range(input: ParseStream) -> Result<Pat> { + let begin = input.fork(); let (qself, path) = path::parsing::qpath(input, true)?; if input.peek(Token![..]) { - return pat_range(input, qself, path).map(Pat::Range); + return pat_range(input, begin, qself, path); } if qself.is_some() { @@ -487,7 +419,7 @@ mod parsing { } else if input.peek(token::Paren) { pat_tuple_struct(input, path).map(Pat::TupleStruct) } else if input.peek(Token![..]) { - pat_range(input, qself, path).map(Pat::Range) + pat_range(input, begin, qself, path) } else { Ok(Pat::Path(PatPath { attrs: Vec::new(), @@ -546,7 +478,7 @@ mod parsing { while !content.is_empty() && !content.peek(Token![..]) { let value = content.call(field_pat)?; fields.push_value(value); - if !content.peek(Token![,]) { + if content.is_empty() { break; } let punct: Token![,] = content.parse()?; @@ -591,7 +523,7 @@ mod parsing { attrs, member, colon_token: input.parse()?, - pat: input.parse()?, + pat: Box::new(multi_pat_with_leading_vert(input)?), }); } @@ -624,17 +556,44 @@ mod parsing { }) } - fn pat_range(input: ParseStream, qself: Option<QSelf>, path: Path) -> Result<PatRange> { - Ok(PatRange { - attrs: Vec::new(), - lo: Box::new(Expr::Path(ExprPath { + fn pat_range( + input: ParseStream, + begin: ParseBuffer, + qself: Option<QSelf>, + path: Path, + ) -> Result<Pat> { + let limits: RangeLimits = input.parse()?; + let hi = input.call(pat_lit_expr)?; + if let Some(hi) = hi { + Ok(Pat::Range(PatRange { attrs: Vec::new(), - qself, - path, - })), - limits: input.parse()?, - hi: input.call(pat_lit_expr)?, - }) + lo: Box::new(Expr::Path(ExprPath { + attrs: Vec::new(), + qself, + path, + })), + limits, + hi, + })) + } else { + Ok(Pat::Verbatim(verbatim::between(begin, input))) + } + } + + fn pat_range_half_open(input: ParseStream, begin: ParseBuffer) -> Result<Pat> { + let limits: RangeLimits = input.parse()?; + let hi = input.call(pat_lit_expr)?; + if hi.is_some() { + Ok(Pat::Verbatim(verbatim::between(begin, input))) + } else { + match limits { + RangeLimits::HalfOpen(dot2_token) => Ok(Pat::Rest(PatRest { + attrs: Vec::new(), + dot2_token, + })), + RangeLimits::Closed(_) => Err(input.error("expected range upper bound")), + } + } } fn pat_tuple(input: ParseStream) -> Result<PatTuple> { @@ -643,7 +602,7 @@ mod parsing { let mut elems = Punctuated::new(); while !content.is_empty() { - let value: Pat = content.parse()?; + let value = multi_pat_with_leading_vert(&content)?; elems.push_value(value); if content.is_empty() { break; @@ -669,14 +628,23 @@ mod parsing { } fn pat_lit_or_range(input: ParseStream) -> Result<Pat> { - let lo = input.call(pat_lit_expr)?; + let begin = input.fork(); + let lo = input.call(pat_lit_expr)?.unwrap(); if input.peek(Token![..]) { - Ok(Pat::Range(PatRange { - attrs: Vec::new(), - lo, - limits: input.parse()?, - hi: input.call(pat_lit_expr)?, - })) + let limits: RangeLimits = input.parse()?; + let hi = input.call(pat_lit_expr)?; + if let Some(hi) = hi { + Ok(Pat::Range(PatRange { + attrs: Vec::new(), + lo, + limits, + hi, + })) + } else { + Ok(Pat::Verbatim(verbatim::between(begin, input))) + } + } else if let Expr::Verbatim(verbatim) = *lo { + Ok(Pat::Verbatim(verbatim)) } else { Ok(Pat::Lit(PatLit { attrs: Vec::new(), @@ -685,7 +653,17 @@ mod parsing { } } - fn pat_lit_expr(input: ParseStream) -> Result<Box<Expr>> { + fn pat_lit_expr(input: ParseStream) -> Result<Option<Box<Expr>>> { + if input.is_empty() + || input.peek(Token![|]) + || input.peek(Token![=>]) + || input.peek(Token![:]) && !input.peek(Token![::]) + || input.peek(Token![,]) + || input.peek(Token![;]) + { + return Ok(None); + } + let neg: Option<Token![-]> = input.parse()?; let lookahead = input.lookahead1(); @@ -697,15 +675,16 @@ mod parsing { || lookahead.peek(Token![self]) || lookahead.peek(Token![Self]) || lookahead.peek(Token![super]) - || lookahead.peek(Token![extern]) || lookahead.peek(Token![crate]) { Expr::Path(input.parse()?) + } else if lookahead.peek(Token![const]) { + Expr::Verbatim(input.call(expr::parsing::expr_const)?) } else { return Err(lookahead.error()); }; - Ok(Box::new(if let Some(neg) = neg { + Ok(Some(Box::new(if let Some(neg) = neg { Expr::Unary(ExprUnary { attrs: Vec::new(), op: UnOp::Neg(neg), @@ -713,7 +692,7 @@ mod parsing { }) } else { expr - })) + }))) } fn pat_slice(input: ParseStream) -> Result<PatSlice> { @@ -722,7 +701,7 @@ mod parsing { let mut elems = Punctuated::new(); while !content.is_empty() { - let value: Pat = content.parse()?; + let value = multi_pat_with_leading_vert(&content)?; elems.push_value(value); if content.is_empty() { break; @@ -738,23 +717,58 @@ mod parsing { }) } - fn pat_rest(input: ParseStream) -> Result<PatRest> { - Ok(PatRest { - attrs: Vec::new(), - dot2_token: input.parse()?, - }) + fn pat_const(input: ParseStream) -> Result<TokenStream> { + let begin = input.fork(); + input.parse::<Token![const]>()?; + + let content; + braced!(content in input); + content.call(Attribute::parse_inner)?; + content.call(Block::parse_within)?; + + Ok(verbatim::between(begin, input)) + } + + pub fn multi_pat(input: ParseStream) -> Result<Pat> { + multi_pat_impl(input, None) + } + + pub fn multi_pat_with_leading_vert(input: ParseStream) -> Result<Pat> { + let leading_vert: Option<Token![|]> = input.parse()?; + multi_pat_impl(input, leading_vert) + } + + fn multi_pat_impl(input: ParseStream, leading_vert: Option<Token![|]>) -> Result<Pat> { + let mut pat: Pat = input.parse()?; + if leading_vert.is_some() + || input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=]) + { + let mut cases = Punctuated::new(); + cases.push_value(pat); + while input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=]) { + let punct = input.parse()?; + cases.push_punct(punct); + let pat: Pat = input.parse()?; + cases.push_value(pat); + } + pat = Pat::Or(PatOr { + attrs: Vec::new(), + leading_vert, + cases, + }); + } + Ok(pat) } } #[cfg(feature = "printing")] mod printing { use super::*; - + use crate::attr::FilterAttrs; use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; - use crate::attr::FilterAttrs; - + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatWild { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -762,6 +776,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatIdent { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -775,6 +790,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatStruct { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -790,6 +806,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatTupleStruct { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -798,6 +815,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatType { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -807,6 +825,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatPath { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -814,6 +833,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatTuple { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -823,6 +843,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatBox { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -831,6 +852,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatReference { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -840,6 +862,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatRest { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -847,6 +870,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatLit { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -854,6 +878,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatRange { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -866,6 +891,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatSlice { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -875,6 +901,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatMacro { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -882,6 +909,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatOr { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -890,6 +918,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for FieldPat { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); diff --git a/1.0.7/src/path.rs b/src/path.rs index 8dda43ee..df1788db 100644 --- a/1.0.7/src/path.rs +++ b/src/path.rs @@ -2,10 +2,11 @@ use super::*; use crate::punctuated::Punctuated; ast_struct! { - /// A path at which a named item is exported: `std::collections::HashMap`. + /// A path at which a named item is exported (e.g. `std::collections::HashMap`). /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct Path { pub leading_colon: Option<Token![::]>, pub segments: Punctuated<PathSegment, Token![::]>, @@ -29,8 +30,9 @@ where ast_struct! { /// A segment of a path together with any path arguments on that segment. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct PathSegment { pub ident: Ident, pub arguments: PathArguments, @@ -52,7 +54,7 @@ where ast_enum! { /// Angle bracketed or parenthesized arguments of a path segment. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* /// /// ## Angle bracketed @@ -62,6 +64,7 @@ ast_enum! { /// ## Parenthesized /// /// The `(A, B) -> C` in `Fn(A, B) -> C`. + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum PathArguments { None, /// The `<'a, T>` in `std::slice::iter<'a, T>`. @@ -98,8 +101,9 @@ impl PathArguments { ast_enum! { /// An individual generic argument, like `'a`, `T`, or `Item = T`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum GenericArgument { /// A lifetime argument. Lifetime(Lifetime), @@ -122,8 +126,9 @@ ast_struct! { /// Angle bracketed arguments of a path segment: the `<K, V>` in `HashMap<K, /// V>`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct AngleBracketedGenericArguments { pub colon2_token: Option<Token![::]>, pub lt_token: Token![<], @@ -135,8 +140,9 @@ ast_struct! { ast_struct! { /// A binding (equality constraint) on an associated type: `Item = u8`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct Binding { pub ident: Ident, pub eq_token: Token![=], @@ -147,8 +153,9 @@ ast_struct! { ast_struct! { /// An associated type bound: `Iterator<Item: Display>`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct Constraint { pub ident: Ident, pub colon_token: Token![:], @@ -160,8 +167,9 @@ ast_struct! { /// Arguments of a function path segment: the `(A, B) -> C` in `Fn(A,B) -> /// C`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct ParenthesizedGenericArguments { pub paren_token: token::Paren, /// `(A, B)` @@ -189,8 +197,9 @@ ast_struct! { /// ty position = 0 /// ``` /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct QSelf { pub lt_token: Token![<], pub ty: Box<Type>, @@ -204,17 +213,17 @@ ast_struct! { pub mod parsing { use super::*; - #[cfg(feature = "full")] - use crate::expr; use crate::ext::IdentExt; use crate::parse::{Parse, ParseStream, Result}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Path { fn parse(input: ParseStream) -> Result<Self> { Self::parse_helper(input, false) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for GenericArgument { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Lifetime) && !input.peek2(Token![+]) { @@ -230,22 +239,81 @@ pub mod parsing { if input.peek(Ident) && input.peek2(Token![:]) && !input.peek2(Token![::]) { return Ok(GenericArgument::Constraint(input.parse()?)); } + } - if input.peek(Lit) { - let lit = input.parse()?; - return Ok(GenericArgument::Const(Expr::Lit(lit))); - } + if input.peek(Lit) || input.peek(token::Brace) { + return const_argument(input).map(GenericArgument::Const); + } - if input.peek(token::Brace) { - let block = input.call(expr::parsing::expr_block)?; - return Ok(GenericArgument::Const(Expr::Block(block))); + #[cfg(feature = "full")] + let begin = input.fork(); + + let argument: Type = input.parse()?; + + #[cfg(feature = "full")] + { + if match &argument { + Type::Path(argument) + if argument.qself.is_none() + && argument.path.leading_colon.is_none() + && argument.path.segments.len() == 1 => + { + match argument.path.segments[0].arguments { + PathArguments::AngleBracketed(_) => true, + _ => false, + } + } + _ => false, + } && if input.peek(Token![=]) { + input.parse::<Token![=]>()?; + input.parse::<Type>()?; + true + } else if input.peek(Token![:]) { + input.parse::<Token![:]>()?; + input.call(constraint_bounds)?; + true + } else { + false + } { + let verbatim = verbatim::between(begin, input); + return Ok(GenericArgument::Type(Type::Verbatim(verbatim))); } } - input.parse().map(GenericArgument::Type) + Ok(GenericArgument::Type(argument)) } } + pub fn const_argument(input: ParseStream) -> Result<Expr> { + let lookahead = input.lookahead1(); + + if input.peek(Lit) { + let lit = input.parse()?; + return Ok(Expr::Lit(lit)); + } + + if input.peek(token::Brace) { + #[cfg(feature = "full")] + { + let block: ExprBlock = input.parse()?; + return Ok(Expr::Block(block)); + } + + #[cfg(not(feature = "full"))] + { + let begin = input.fork(); + let content; + braced!(content in input); + content.parse::<Expr>()?; + let verbatim = verbatim::between(begin, input); + return Ok(Expr::Verbatim(verbatim)); + } + } + + Err(lookahead.error()) + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for AngleBracketedGenericArguments { fn parse(input: ParseStream) -> Result<Self> { Ok(AngleBracketedGenericArguments { @@ -272,6 +340,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ParenthesizedGenericArguments { fn parse(input: ParseStream) -> Result<Self> { let content; @@ -283,6 +352,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for PathSegment { fn parse(input: ParseStream) -> Result<Self> { Self::parse_helper(input, false) @@ -291,11 +361,7 @@ pub mod parsing { impl PathSegment { fn parse_helper(input: ParseStream, expr_style: bool) -> Result<Self> { - if input.peek(Token![super]) - || input.peek(Token![self]) - || input.peek(Token![crate]) - || input.peek(Token![extern]) - { + if input.peek(Token![super]) || input.peek(Token![self]) || input.peek(Token![crate]) { let ident = input.call(Ident::parse_any)?; return Ok(PathSegment::from(ident)); } @@ -319,6 +385,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Binding { fn parse(input: ParseStream) -> Result<Self> { Ok(Binding { @@ -330,35 +397,39 @@ pub mod parsing { } #[cfg(feature = "full")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Constraint { fn parse(input: ParseStream) -> Result<Self> { Ok(Constraint { ident: input.parse()?, colon_token: input.parse()?, - bounds: { - let mut bounds = Punctuated::new(); - loop { - if input.peek(Token![,]) || input.peek(Token![>]) { - break; - } - let value = input.parse()?; - bounds.push_value(value); - if !input.peek(Token![+]) { - break; - } - let punct = input.parse()?; - bounds.push_punct(punct); - } - bounds - }, + bounds: constraint_bounds(input)?, }) } } + #[cfg(feature = "full")] + fn constraint_bounds(input: ParseStream) -> Result<Punctuated<TypeParamBound, Token![+]>> { + let mut bounds = Punctuated::new(); + loop { + if input.peek(Token![,]) || input.peek(Token![>]) { + break; + } + let value = input.parse()?; + bounds.push_value(value); + if !input.peek(Token![+]) { + break; + } + let punct = input.parse()?; + bounds.push_punct(punct); + } + Ok(bounds) + } + impl Path { /// Parse a `Path` containing no path arguments on any of its segments. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* /// /// # Example @@ -389,6 +460,7 @@ pub mod parsing { /// } /// } /// ``` + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_mod_style(input: ParseStream) -> Result<Self> { Ok(Path { leading_colon: input.parse()?, @@ -400,7 +472,6 @@ pub mod parsing { && !input.peek(Token![self]) && !input.peek(Token![Self]) && !input.peek(Token![crate]) - && !input.peek(Token![extern]) { break; } @@ -433,7 +504,7 @@ pub mod parsing { /// path arguments, and /// - the ident of the first path segment is equal to the given one. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* /// /// # Example @@ -453,6 +524,7 @@ pub mod parsing { /// } /// } /// ``` + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn is_ident<I: ?Sized>(&self, ident: &I) -> bool where Ident: PartialEq<I>, @@ -472,8 +544,9 @@ pub mod parsing { /// - the first path segment has no angle bracketed or parenthesized /// path arguments. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn get_ident(&self) -> Option<&Ident> { if self.leading_colon.is_none() && self.segments.len() == 1 @@ -485,22 +558,32 @@ pub mod parsing { } } - fn parse_helper(input: ParseStream, expr_style: bool) -> Result<Self> { - Ok(Path { + pub(crate) fn parse_helper(input: ParseStream, expr_style: bool) -> Result<Self> { + let mut path = Path { leading_colon: input.parse()?, segments: { let mut segments = Punctuated::new(); let value = PathSegment::parse_helper(input, expr_style)?; segments.push_value(value); - while input.peek(Token![::]) { - let punct: Token![::] = input.parse()?; - segments.push_punct(punct); - let value = PathSegment::parse_helper(input, expr_style)?; - segments.push_value(value); - } segments }, - }) + }; + Path::parse_rest(input, &mut path, expr_style)?; + Ok(path) + } + + pub(crate) fn parse_rest( + input: ParseStream, + path: &mut Self, + expr_style: bool, + ) -> Result<()> { + while input.peek(Token![::]) { + let punct: Token![::] = input.parse()?; + path.segments.push_punct(punct); + let value = PathSegment::parse_helper(input, expr_style)?; + path.segments.push_value(value); + } + Ok(()) } } @@ -560,12 +643,12 @@ pub mod parsing { #[cfg(feature = "printing")] mod printing { use super::*; - + use crate::print::TokensOrDefault; use proc_macro2::TokenStream; use quote::ToTokens; + use std::cmp; - use crate::print::TokensOrDefault; - + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Path { fn to_tokens(&self, tokens: &mut TokenStream) { self.leading_colon.to_tokens(tokens); @@ -573,6 +656,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PathSegment { fn to_tokens(&self, tokens: &mut TokenStream) { self.ident.to_tokens(tokens); @@ -580,6 +664,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PathArguments { fn to_tokens(&self, tokens: &mut TokenStream) { match self { @@ -594,6 +679,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for GenericArgument { #[allow(clippy::match_same_arms)] fn to_tokens(&self, tokens: &mut TokenStream) { @@ -621,6 +707,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for AngleBracketedGenericArguments { fn to_tokens(&self, tokens: &mut TokenStream) { self.colon2_token.to_tokens(tokens); @@ -663,9 +750,9 @@ mod printing { GenericArgument::Binding(_) | GenericArgument::Constraint(_) => { if !trailing_or_empty { <Token![,]>::default().to_tokens(tokens); - trailing_or_empty = true; } param.to_tokens(tokens); + trailing_or_empty = param.punct().is_some(); } GenericArgument::Lifetime(_) | GenericArgument::Type(_) @@ -677,6 +764,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Binding { fn to_tokens(&self, tokens: &mut TokenStream) { self.ident.to_tokens(tokens); @@ -685,6 +773,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Constraint { fn to_tokens(&self, tokens: &mut TokenStream) { self.ident.to_tokens(tokens); @@ -693,6 +782,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ParenthesizedGenericArguments { fn to_tokens(&self, tokens: &mut TokenStream) { self.paren_token.surround(tokens, |tokens| { @@ -703,7 +793,7 @@ mod printing { } impl private { - pub fn print_path(tokens: &mut TokenStream, qself: &Option<QSelf>, path: &Path) { + pub(crate) fn print_path(tokens: &mut TokenStream, qself: &Option<QSelf>, path: &Path) { let qself = match qself { Some(qself) => qself, None => { @@ -714,11 +804,7 @@ mod printing { qself.lt_token.to_tokens(tokens); qself.ty.to_tokens(tokens); - let pos = if qself.position > 0 && qself.position >= path.segments.len() { - path.segments.len() - 1 - } else { - qself.position - }; + let pos = cmp::min(qself.position, path.segments.len()); let mut segments = path.segments.pairs(); if pos > 0 { TokensOrDefault(&qself.as_token).to_tokens(tokens); diff --git a/1.0.7/src/print.rs b/src/print.rs index da4e07e3..da4e07e3 100644 --- a/1.0.7/src/print.rs +++ b/src/print.rs diff --git a/1.0.7/src/punctuated.rs b/src/punctuated.rs index 38c7bf4e..f94edc29 100644 --- a/1.0.7/src/punctuated.rs +++ b/src/punctuated.rs @@ -13,7 +13,7 @@ //! syntax tree node + punctuation, where every node in the sequence is followed //! by punctuation except for possibly the final one. //! -//! [`Punctuated<T, P>`]: struct.Punctuated.html +//! [`Punctuated<T, P>`]: Punctuated //! //! ```text //! a_function_call(arg1, arg2, arg3); @@ -22,6 +22,8 @@ #[cfg(feature = "extra-traits")] use std::fmt::{self, Debug}; +#[cfg(feature = "extra-traits")] +use std::hash::{Hash, Hasher}; #[cfg(any(feature = "full", feature = "derive"))] use std::iter; use std::iter::FromIterator; @@ -41,8 +43,6 @@ use crate::token::Token; /// Refer to the [module documentation] for details about punctuated sequences. /// /// [module documentation]: self -#[cfg_attr(feature = "extra-traits", derive(Eq, PartialEq, Hash))] -#[cfg_attr(feature = "clone-impls", derive(Clone))] pub struct Punctuated<T, P> { inner: Vec<(T, P)>, last: Option<Box<T>>, @@ -50,7 +50,17 @@ pub struct Punctuated<T, P> { impl<T, P> Punctuated<T, P> { /// Creates an empty punctuated sequence. - pub fn new() -> Punctuated<T, P> { + #[cfg(not(syn_no_const_vec_new))] + pub const fn new() -> Self { + Punctuated { + inner: Vec::new(), + last: None, + } + } + + /// Creates an empty punctuated sequence. + #[cfg(syn_no_const_vec_new)] + pub fn new() -> Self { Punctuated { inner: Vec::new(), last: None, @@ -76,22 +86,19 @@ impl<T, P> Punctuated<T, P> { self.iter().next() } + /// Mutably borrows the first element in this sequence. + pub fn first_mut(&mut self) -> Option<&mut T> { + self.iter_mut().next() + } + /// Borrows the last element in this sequence. pub fn last(&self) -> Option<&T> { - if self.last.is_some() { - self.last.as_ref().map(Box::as_ref) - } else { - self.inner.last().map(|pair| &pair.0) - } + self.iter().next_back() } /// Mutably borrows the last element in this sequence. pub fn last_mut(&mut self) -> Option<&mut T> { - if self.last.is_some() { - self.last.as_mut().map(Box::as_mut) - } else { - self.inner.last_mut().map(|pair| &mut pair.0) - } + self.iter_mut().next_back() } /// Returns an iterator over borrowed syntax tree nodes of type `&T`. @@ -155,7 +162,11 @@ impl<T, P> Punctuated<T, P> { /// Panics if the sequence does not already have a trailing punctuation when /// this method is called. pub fn push_value(&mut self, value: T) { - assert!(self.empty_or_trailing()); + assert!( + self.empty_or_trailing(), + "Punctuated::push_value: cannot push value if Punctuated is missing trailing punctuation", + ); + self.last = Some(Box::new(value)); } @@ -167,7 +178,11 @@ impl<T, P> Punctuated<T, P> { /// /// Panics if the sequence is empty or already has a trailing punctuation. pub fn push_punct(&mut self, punctuation: P) { - assert!(self.last.is_some()); + assert!( + self.last.is_some(), + "Punctuated::push_punct: cannot push punctuation if Punctuated is empty or already has trailing punctuation", + ); + let last = self.last.take().unwrap(); self.inner.push((*last, punctuation)); } @@ -221,7 +236,10 @@ impl<T, P> Punctuated<T, P> { where P: Default, { - assert!(index <= self.len()); + assert!( + index <= self.len(), + "Punctuated::insert: index out of range", + ); if index == self.len() { self.push(value); @@ -230,15 +248,22 @@ impl<T, P> Punctuated<T, P> { } } + /// Clears the sequence of all values and punctuation, making it empty. + pub fn clear(&mut self) { + self.inner.clear(); + self.last = None; + } + /// Parses zero or more occurrences of `T` separated by punctuation of type /// `P`, with optional trailing punctuation. /// /// Parsing continues until the end of this parse stream. The entire content /// of this parse stream must consist of `T` and `P`. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_terminated(input: ParseStream) -> Result<Self> where T: Parse, @@ -256,9 +281,10 @@ impl<T, P> Punctuated<T, P> { /// /// [`parse_terminated`]: Punctuated::parse_terminated /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_terminated_with( input: ParseStream, parser: fn(ParseStream) -> Result<T>, @@ -292,9 +318,10 @@ impl<T, P> Punctuated<T, P> { /// is not followed by a `P`, even if there are remaining tokens in the /// stream. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_separated_nonempty(input: ParseStream) -> Result<Self> where T: Parse, @@ -312,9 +339,10 @@ impl<T, P> Punctuated<T, P> { /// /// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_separated_nonempty_with( input: ParseStream, parser: fn(ParseStream) -> Result<T>, @@ -338,7 +366,59 @@ impl<T, P> Punctuated<T, P> { } } +#[cfg(feature = "clone-impls")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl<T, P> Clone for Punctuated<T, P> +where + T: Clone, + P: Clone, +{ + fn clone(&self) -> Self { + Punctuated { + inner: self.inner.clone(), + last: self.last.clone(), + } + } +} + #[cfg(feature = "extra-traits")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl<T, P> Eq for Punctuated<T, P> +where + T: Eq, + P: Eq, +{ +} + +#[cfg(feature = "extra-traits")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl<T, P> PartialEq for Punctuated<T, P> +where + T: PartialEq, + P: PartialEq, +{ + fn eq(&self, other: &Self) -> bool { + let Punctuated { inner, last } = self; + *inner == other.inner && *last == other.last + } +} + +#[cfg(feature = "extra-traits")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl<T, P> Hash for Punctuated<T, P> +where + T: Hash, + P: Hash, +{ + fn hash<H: Hasher>(&self, state: &mut H) { + let Punctuated { inner, last } = self; + inner.hash(state); + last.hash(state); + } +} + +#[cfg(feature = "extra-traits")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl<T: Debug, P: Debug> Debug for Punctuated<T, P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut list = f.debug_list(); @@ -385,7 +465,11 @@ impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P> { impl<T, P> Extend<Pair<T, P>> for Punctuated<T, P> { fn extend<I: IntoIterator<Item = Pair<T, P>>>(&mut self, i: I) { - assert!(self.empty_or_trailing()); + assert!( + self.empty_or_trailing(), + "Punctuated::extend: Punctuated is not empty or does not have a trailing punctuation", + ); + let mut nomore = false; for pair in i { if nomore { @@ -536,7 +620,6 @@ impl<'a, T, P> ExactSizeIterator for PairsMut<'a, T, P> { /// Refer to the [module documentation] for details about punctuated sequences. /// /// [module documentation]: self -#[derive(Clone)] pub struct IntoPairs<T, P> { inner: vec::IntoIter<(T, P)>, last: option::IntoIter<T>, @@ -572,12 +655,24 @@ impl<T, P> ExactSizeIterator for IntoPairs<T, P> { } } +impl<T, P> Clone for IntoPairs<T, P> +where + T: Clone, + P: Clone, +{ + fn clone(&self) -> Self { + IntoPairs { + inner: self.inner.clone(), + last: self.last.clone(), + } + } +} + /// An iterator over owned values of type `T`. /// /// Refer to the [module documentation] for details about punctuated sequences. /// /// [module documentation]: self -#[derive(Clone)] pub struct IntoIter<T> { inner: vec::IntoIter<T>, } @@ -606,6 +701,17 @@ impl<T> ExactSizeIterator for IntoIter<T> { } } +impl<T> Clone for IntoIter<T> +where + T: Clone, +{ + fn clone(&self) -> Self { + IntoIter { + inner: self.inner.clone(), + } + } +} + /// An iterator over borrowed values of type `&T`. /// /// Refer to the [module documentation] for details about punctuated sequences. @@ -799,7 +905,6 @@ impl<'a, T: 'a, I: 'a> IterMutTrait<'a, T> for I where /// Refer to the [module documentation] for details about punctuated sequences. /// /// [module documentation]: self -#[cfg_attr(feature = "clone-impls", derive(Clone))] pub enum Pair<T, P> { Punctuated(T, P), End(T), @@ -856,6 +961,21 @@ impl<T, P> Pair<T, P> { } } +#[cfg(feature = "clone-impls")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl<T, P> Clone for Pair<T, P> +where + T: Clone, + P: Clone, +{ + fn clone(&self) -> Self { + match self { + Pair::Punctuated(t, p) => Pair::Punctuated(t.clone(), p.clone()), + Pair::End(t) => Pair::End(t.clone()), + } + } +} + impl<T, P> Index<usize> for Punctuated<T, P> { type Output = T; @@ -890,6 +1010,7 @@ mod printing { use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl<T, P> ToTokens for Punctuated<T, P> where T: ToTokens, @@ -900,6 +1021,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl<T, P> ToTokens for Pair<T, P> where T: ToTokens, diff --git a/src/reserved.rs b/src/reserved.rs new file mode 100644 index 00000000..abfdf43a --- /dev/null +++ b/src/reserved.rs @@ -0,0 +1,44 @@ +// Type for a syntax tree node that is reserved for future use. +// +// For example ExprReference contains a field `raw` of type Reserved. If `&raw +// place` syntax becomes a thing as per https://github.com/rust-lang/rfcs/pull/2582, +// we can backward compatibly change `raw`'s type to Option<Token![raw]> without +// the possibility of breaking any code. + +use proc_macro2::Span; +use std::marker::PhantomData; + +#[cfg(feature = "extra-traits")] +use std::fmt::{self, Debug}; + +ast_struct! { + pub struct Reserved { + _private: PhantomData<Span>, + } +} + +impl Default for Reserved { + fn default() -> Self { + Reserved { + _private: PhantomData, + } + } +} + +#[cfg(feature = "clone-impls")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for Reserved { + fn clone(&self) -> Self { + Reserved { + _private: self._private, + } + } +} + +#[cfg(feature = "extra-traits")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for Reserved { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.debug_struct("Reserved").finish() + } +} diff --git a/0.15.42/src/sealed.rs b/src/sealed.rs index 0b11bc99..0b11bc99 100644 --- a/0.15.42/src/sealed.rs +++ b/src/sealed.rs diff --git a/0.15.42/src/span.rs b/src/span.rs index 27a7fe84..27a7fe84 100644 --- a/0.15.42/src/span.rs +++ b/src/span.rs diff --git a/1.0.7/src/spanned.rs b/src/spanned.rs index 71ffe26b..d51ffb3f 100644 --- a/1.0.7/src/spanned.rs +++ b/src/spanned.rs @@ -1,7 +1,7 @@ //! A trait that can provide the `Span` of the complete contents of a syntax //! tree node. //! -//! *This module is available if Syn is built with both the `"parsing"` and +//! *This module is available only if Syn is built with both the `"parsing"` and //! `"printing"` features.* //! //! <br> @@ -13,8 +13,8 @@ //! of a struct for which we are deriving a trait implementation, and we need to //! be able to pass a reference to one of those fields across threads. //! -//! [`Type`]: ../enum.Type.html -//! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html +//! [`Type`]: crate::Type +//! [`Sync`]: std::marker::Sync //! //! If the field type does *not* implement `Sync` as required, we want the //! compiler to report an error pointing out exactly which type it was. @@ -97,7 +97,7 @@ use quote::spanned::Spanned as ToTokens; /// /// [module documentation]: self /// -/// *This trait is available if Syn is built with both the `"parsing"` and +/// *This trait is available only if Syn is built with both the `"parsing"` and /// `"printing"` features.* pub trait Spanned { /// Returns a `Span` covering the complete contents of this syntax tree diff --git a/1.0.7/src/stmt.rs b/src/stmt.rs index e4277fdb..ba2b22e5 100644 --- a/1.0.7/src/stmt.rs +++ b/src/stmt.rs @@ -3,7 +3,8 @@ use super::*; ast_struct! { /// A braced block containing Rust statements. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct Block { pub brace_token: token::Brace, /// Statements in a block @@ -14,7 +15,8 @@ ast_struct! { ast_enum! { /// A statement, usually ending in a semicolon. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub enum Stmt { /// A local (let) binding. Local(Local), @@ -33,7 +35,8 @@ ast_enum! { ast_struct! { /// A local `let` binding: `let x: u64 = s.parse()?`. /// - /// *This type is available if Syn is built with the `"full"` feature.* + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] pub struct Local { pub attrs: Vec<Attribute>, pub let_token: Token![let], @@ -46,15 +49,15 @@ ast_struct! { #[cfg(feature = "parsing")] pub mod parsing { use super::*; - + use crate::parse::discouraged::Speculative; use crate::parse::{Parse, ParseStream, Result}; - use crate::punctuated::Punctuated; + use proc_macro2::TokenStream; impl Block { /// Parse the body of a block as zero or more statements, possibly /// including one trailing expression. /// - /// *This function is available if Syn is built with the `"parsing"` + /// *This function is available only if Syn is built with the `"parsing"` /// feature.* /// /// # Example @@ -103,11 +106,12 @@ pub mod parsing { /// } /// } /// ``` + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_within(input: ParseStream) -> Result<Vec<Stmt>> { let mut stmts = Vec::new(); loop { - while input.peek(Token![;]) { - input.parse::<Token![;]>()?; + while let Some(semi) = input.parse::<Option<Token![;]>>()? { + stmts.push(Stmt::Semi(Expr::Verbatim(TokenStream::new()), semi)); } if input.is_empty() { break; @@ -129,6 +133,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Block { fn parse(input: ParseStream) -> Result<Self> { let content; @@ -139,6 +144,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Stmt { fn parse(input: ParseStream) -> Result<Self> { parse_stmt(input, false) @@ -146,55 +152,55 @@ pub mod parsing { } fn parse_stmt(input: ParseStream, allow_nosemi: bool) -> Result<Stmt> { - // TODO: optimize using advance_to + let mut attrs = input.call(Attribute::parse_outer)?; + + // brace-style macros; paren and bracket macros get parsed as + // expression statements. let ahead = input.fork(); - ahead.call(Attribute::parse_outer)?; + if let Ok(path) = ahead.call(Path::parse_mod_style) { + if ahead.peek(Token![!]) && (ahead.peek2(token::Brace) || ahead.peek2(Ident)) { + input.advance_to(&ahead); + return stmt_mac(input, attrs, path); + } + } - if { - let ahead = ahead.fork(); - // Only parse braces here; paren and bracket will get parsed as - // expression statements - ahead.call(Path::parse_mod_style).is_ok() - && ahead.parse::<Token![!]>().is_ok() - && (ahead.peek(token::Brace) || ahead.peek(Ident)) - } { - stmt_mac(input) - } else if ahead.peek(Token![let]) { - stmt_local(input).map(Stmt::Local) - } else if ahead.peek(Token![pub]) - || ahead.peek(Token![crate]) && !ahead.peek2(Token![::]) - || ahead.peek(Token![extern]) && !ahead.peek2(Token![::]) - || ahead.peek(Token![use]) - || ahead.peek(Token![static]) && (ahead.peek2(Token![mut]) || ahead.peek2(Ident)) - || ahead.peek(Token![const]) - || ahead.peek(Token![unsafe]) && !ahead.peek2(token::Brace) - || ahead.peek(Token![async]) - && (ahead.peek2(Token![unsafe]) - || ahead.peek2(Token![extern]) - || ahead.peek2(Token![fn])) - || ahead.peek(Token![fn]) - || ahead.peek(Token![mod]) - || ahead.peek(Token![type]) - || ahead.peek(item::parsing::existential) && ahead.peek2(Token![type]) - || ahead.peek(Token![struct]) - || ahead.peek(Token![enum]) - || ahead.peek(Token![union]) && ahead.peek2(Ident) - || ahead.peek(Token![auto]) && ahead.peek2(Token![trait]) - || ahead.peek(Token![trait]) - || ahead.peek(Token![default]) - && (ahead.peek2(Token![unsafe]) || ahead.peek2(Token![impl])) - || ahead.peek(Token![impl]) - || ahead.peek(Token![macro]) + if input.peek(Token![let]) { + stmt_local(input, attrs).map(Stmt::Local) + } else if input.peek(Token![pub]) + || input.peek(Token![crate]) && !input.peek2(Token![::]) + || input.peek(Token![extern]) + || input.peek(Token![use]) + || input.peek(Token![static]) && (input.peek2(Token![mut]) || input.peek2(Ident)) + || input.peek(Token![const]) && !input.peek2(token::Brace) + || input.peek(Token![unsafe]) && !input.peek2(token::Brace) + || input.peek(Token![async]) + && (input.peek2(Token![unsafe]) + || input.peek2(Token![extern]) + || input.peek2(Token![fn])) + || input.peek(Token![fn]) + || input.peek(Token![mod]) + || input.peek(Token![type]) + || input.peek(item::parsing::existential) && input.peek2(Token![type]) + || input.peek(Token![struct]) + || input.peek(Token![enum]) + || input.peek(Token![union]) && input.peek2(Ident) + || input.peek(Token![auto]) && input.peek2(Token![trait]) + || input.peek(Token![trait]) + || input.peek(Token![default]) + && (input.peek2(Token![unsafe]) || input.peek2(Token![impl])) + || input.peek(Token![impl]) + || input.peek(Token![macro]) { - input.parse().map(Stmt::Item) + let mut item: Item = input.parse()?; + attrs.extend(item.replace_attrs(Vec::new())); + item.replace_attrs(attrs); + Ok(Stmt::Item(item)) } else { - stmt_expr(input, allow_nosemi) + stmt_expr(input, allow_nosemi, attrs) } } - fn stmt_mac(input: ParseStream) -> Result<Stmt> { - let attrs = input.call(Attribute::parse_outer)?; - let path = input.call(Path::parse_mod_style)?; + fn stmt_mac(input: ParseStream, attrs: Vec<Attribute>, path: Path) -> Result<Stmt> { let bang_token: Token![!] = input.parse()?; let ident: Option<Ident> = input.parse()?; let (delimiter, tokens) = mac::parse_delimiter(input)?; @@ -213,33 +219,12 @@ pub mod parsing { }))) } - fn stmt_local(input: ParseStream) -> Result<Local> { + fn stmt_local(input: ParseStream, attrs: Vec<Attribute>) -> Result<Local> { Ok(Local { - attrs: input.call(Attribute::parse_outer)?, + attrs, let_token: input.parse()?, pat: { - let leading_vert: Option<Token![|]> = input.parse()?; - let mut pat: Pat = input.parse()?; - if leading_vert.is_some() - || input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=]) - { - let mut cases = Punctuated::new(); - cases.push_value(pat); - while input.peek(Token![|]) - && !input.peek(Token![||]) - && !input.peek(Token![|=]) - { - let punct = input.parse()?; - cases.push_punct(punct); - let pat: Pat = input.parse()?; - cases.push_value(pat); - } - pat = Pat::Or(PatOr { - attrs: Vec::new(), - leading_vert, - cases, - }); - } + let mut pat: Pat = pat::parsing::multi_pat_with_leading_vert(input)?; if input.peek(Token![:]) { let colon_token: Token![:] = input.parse()?; let ty: Type = input.parse()?; @@ -265,12 +250,19 @@ pub mod parsing { }) } - fn stmt_expr(input: ParseStream, allow_nosemi: bool) -> Result<Stmt> { - let mut attrs = input.call(Attribute::parse_outer)?; + fn stmt_expr( + input: ParseStream, + allow_nosemi: bool, + mut attrs: Vec<Attribute>, + ) -> Result<Stmt> { let mut e = expr::parsing::expr_early(input)?; - attrs.extend(e.replace_attrs(Vec::new())); - e.replace_attrs(attrs); + let mut attr_target = &mut e; + while let Expr::Binary(e) = attr_target { + attr_target = &mut e.left; + } + attrs.extend(attr_target.replace_attrs(Vec::new())); + attr_target.replace_attrs(attrs); if input.peek(Token![;]) { return Ok(Stmt::Semi(e, input.parse()?)); @@ -287,10 +279,10 @@ pub mod parsing { #[cfg(feature = "printing")] mod printing { use super::*; - use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Block { fn to_tokens(&self, tokens: &mut TokenStream) { self.brace_token.surround(tokens, |tokens| { @@ -299,6 +291,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Stmt { fn to_tokens(&self, tokens: &mut TokenStream) { match self { @@ -313,6 +306,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Local { fn to_tokens(&self, tokens: &mut TokenStream) { expr::printing::outer_attrs_to_tokens(&self.attrs, tokens); diff --git a/1.0.7/src/thread.rs b/src/thread.rs index 9e5d8ad8..9e5d8ad8 100644 --- a/1.0.7/src/thread.rs +++ b/src/thread.rs diff --git a/1.0.7/src/token.rs b/src/token.rs index 0b8c1819..2208b07d 100644 --- a/1.0.7/src/token.rs +++ b/src/token.rs @@ -4,13 +4,13 @@ //! prefer to use the [`Token!`] macro instead. This is a type-macro that //! expands to the token type of the given token. //! -//! [`Token!`]: ../macro.Token.html +//! [`Token!`]: crate::Token //! //! # Example //! //! The [`ItemStatic`] syntax tree node is defined like this. //! -//! [`ItemStatic`]: ../struct.ItemStatic.html +//! [`ItemStatic`]: crate::ItemStatic //! //! ``` //! # use syn::{Attribute, Expr, Ident, Token, Type, Visibility}; @@ -35,10 +35,10 @@ //! method. Delimiter tokens are parsed using the [`parenthesized!`], //! [`bracketed!`] and [`braced!`] macros. //! -//! [`ParseStream::parse`]: ../parse/struct.ParseBuffer.html#method.parse -//! [`parenthesized!`]: ../macro.parenthesized.html -//! [`bracketed!`]: ../macro.bracketed.html -//! [`braced!`]: ../macro.braced.html +//! [`ParseStream::parse`]: crate::parse::ParseBuffer::parse() +//! [`parenthesized!`]: crate::parenthesized! +//! [`bracketed!`]: crate::bracketed! +//! [`braced!`]: crate::braced! //! //! ``` //! use syn::{Attribute, Result}; @@ -83,39 +83,18 @@ //! //! - Field access to its span — `let sp = the_token.span` //! -//! [Peeking]: ../parse/struct.ParseBuffer.html#method.peek -//! [Parsing]: ../parse/struct.ParseBuffer.html#method.parse +//! [Peeking]: crate::parse::ParseBuffer::peek() +//! [Parsing]: crate::parse::ParseBuffer::parse() //! [Printing]: https://docs.rs/quote/1.0/quote/trait.ToTokens.html //! [`Span`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.Span.html -use std; -#[cfg(feature = "extra-traits")] -use std::cmp; -#[cfg(feature = "extra-traits")] -use std::fmt::{self, Debug}; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; -use std::ops::{Deref, DerefMut}; - -#[cfg(feature = "parsing")] -use proc_macro2::Delimiter; -#[cfg(any(feature = "parsing", feature = "printing"))] -use proc_macro2::Ident; -use proc_macro2::Span; -#[cfg(feature = "printing")] -use proc_macro2::TokenStream; -#[cfg(feature = "printing")] -use quote::{ToTokens, TokenStreamExt}; - use self::private::WithSpan; #[cfg(feature = "parsing")] use crate::buffer::Cursor; #[cfg(feature = "parsing")] use crate::error::Result; -#[cfg(any(feature = "full", feature = "derive"))] #[cfg(feature = "parsing")] use crate::lifetime::Lifetime; -#[cfg(any(feature = "full", feature = "derive"))] #[cfg(feature = "parsing")] use crate::lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr}; #[cfg(feature = "parsing")] @@ -123,6 +102,22 @@ use crate::lookahead; #[cfg(feature = "parsing")] use crate::parse::{Parse, ParseStream}; use crate::span::IntoSpans; +#[cfg(any(feature = "parsing", feature = "printing"))] +use proc_macro2::Ident; +use proc_macro2::Span; +#[cfg(feature = "printing")] +use proc_macro2::TokenStream; +#[cfg(feature = "parsing")] +use proc_macro2::{Delimiter, Literal, Punct, TokenTree}; +#[cfg(feature = "printing")] +use quote::{ToTokens, TokenStreamExt}; +#[cfg(feature = "extra-traits")] +use std::cmp; +#[cfg(feature = "extra-traits")] +use std::fmt::{self, Debug}; +#[cfg(feature = "extra-traits")] +use std::hash::{Hash, Hasher}; +use std::ops::{Deref, DerefMut}; /// Marker trait for types that represent single tokens. /// @@ -155,21 +150,20 @@ mod private { #[cfg(feature = "parsing")] impl private::Sealed for Ident {} -#[cfg(any(feature = "full", feature = "derive"))] #[cfg(feature = "parsing")] fn peek_impl(cursor: Cursor, peek: fn(ParseStream) -> bool) -> bool { + use crate::parse::Unexpected; use std::cell::Cell; use std::rc::Rc; let scope = Span::call_site(); - let unexpected = Rc::new(Cell::new(None)); + let unexpected = Rc::new(Cell::new(Unexpected::None)); let buffer = crate::parse::new_parse_buffer(scope, cursor, unexpected); peek(&buffer) } -#[cfg(any(feature = "full", feature = "derive"))] macro_rules! impl_token { - ($name:ident $display:expr) => { + ($display:tt $name:ty) => { #[cfg(feature = "parsing")] impl Token for $name { fn peek(cursor: Cursor) -> bool { @@ -189,24 +183,38 @@ macro_rules! impl_token { }; } -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(Lifetime "lifetime"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(Lit "literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitStr "string literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitByteStr "byte string literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitByte "byte literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitChar "character literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitInt "integer literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitFloat "floating point literal"); -#[cfg(any(feature = "full", feature = "derive"))] -impl_token!(LitBool "boolean literal"); +impl_token!("lifetime" Lifetime); +impl_token!("literal" Lit); +impl_token!("string literal" LitStr); +impl_token!("byte string literal" LitByteStr); +impl_token!("byte literal" LitByte); +impl_token!("character literal" LitChar); +impl_token!("integer literal" LitInt); +impl_token!("floating point literal" LitFloat); +impl_token!("boolean literal" LitBool); +impl_token!("group token" proc_macro2::Group); + +macro_rules! impl_low_level_token { + ($display:tt $ty:ident $get:ident) => { + #[cfg(feature = "parsing")] + impl Token for $ty { + fn peek(cursor: Cursor) -> bool { + cursor.$get().is_some() + } + + fn display() -> &'static str { + $display + } + } + + #[cfg(feature = "parsing")] + impl private::Sealed for $ty {} + }; +} + +impl_low_level_token!("punctuation token" Punct punct); +impl_low_level_token!("literal" Literal literal); +impl_low_level_token!("token" TokenTree token_tree); // Not public API. #[doc(hidden)] @@ -233,7 +241,6 @@ impl<T: CustomToken> Token for T { macro_rules! define_keywords { ($($token:tt pub struct $name:ident #[$doc:meta])*) => { $( - #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))] #[$doc] /// /// Don't try to remember the name of this type — use the @@ -260,7 +267,20 @@ macro_rules! define_keywords { } } + #[cfg(feature = "clone-impls")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] + impl Copy for $name {} + + #[cfg(feature = "clone-impls")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] + impl Clone for $name { + fn clone(&self) -> Self { + *self + } + } + #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for $name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(stringify!($name)) @@ -268,9 +288,11 @@ macro_rules! define_keywords { } #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl cmp::Eq for $name {} #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl PartialEq for $name { fn eq(&self, _other: &$name) -> bool { true @@ -278,11 +300,13 @@ macro_rules! define_keywords { } #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Hash for $name { fn hash<H: Hasher>(&self, _state: &mut H) {} } #[cfg(feature = "printing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for $name { fn to_tokens(&self, tokens: &mut TokenStream) { printing::keyword($token, self.span, tokens); @@ -290,6 +314,7 @@ macro_rules! define_keywords { } #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for $name { fn parse(input: ParseStream) -> Result<Self> { Ok($name { @@ -338,7 +363,6 @@ macro_rules! impl_deref_if_len_is_1 { macro_rules! define_punctuation_structs { ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => { $( - #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))] #[repr(C)] #[$doc] /// @@ -366,7 +390,20 @@ macro_rules! define_punctuation_structs { } } + #[cfg(feature = "clone-impls")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] + impl Copy for $name {} + + #[cfg(feature = "clone-impls")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] + impl Clone for $name { + fn clone(&self) -> Self { + *self + } + } + #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for $name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(stringify!($name)) @@ -374,9 +411,11 @@ macro_rules! define_punctuation_structs { } #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl cmp::Eq for $name {} #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl PartialEq for $name { fn eq(&self, _other: &$name) -> bool { true @@ -384,6 +423,7 @@ macro_rules! define_punctuation_structs { } #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Hash for $name { fn hash<H: Hasher>(&self, _state: &mut H) {} } @@ -401,6 +441,7 @@ macro_rules! define_punctuation { } #[cfg(feature = "printing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for $name { fn to_tokens(&self, tokens: &mut TokenStream) { printing::punct($token, &self.spans, tokens); @@ -408,6 +449,7 @@ macro_rules! define_punctuation { } #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for $name { fn parse(input: ParseStream) -> Result<Self> { Ok($name { @@ -436,7 +478,6 @@ macro_rules! define_punctuation { macro_rules! define_delimiters { ($($token:tt pub struct $name:ident #[$doc:meta])*) => { $( - #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))] #[$doc] pub struct $name { pub span: Span, @@ -458,7 +499,20 @@ macro_rules! define_delimiters { } } + #[cfg(feature = "clone-impls")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] + impl Copy for $name {} + + #[cfg(feature = "clone-impls")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] + impl Clone for $name { + fn clone(&self) -> Self { + *self + } + } + #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for $name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(stringify!($name)) @@ -466,9 +520,11 @@ macro_rules! define_delimiters { } #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl cmp::Eq for $name {} #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl PartialEq for $name { fn eq(&self, _other: &$name) -> bool { true @@ -476,6 +532,7 @@ macro_rules! define_delimiters { } #[cfg(feature = "extra-traits")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Hash for $name { fn hash<H: Hasher>(&self, _state: &mut H) {} } @@ -501,6 +558,7 @@ define_punctuation_structs! { } #[cfg(feature = "printing")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Underscore { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append(Ident::new("_", self.span)); @@ -508,6 +566,7 @@ impl ToTokens for Underscore { } #[cfg(feature = "parsing")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Underscore { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| { @@ -713,105 +772,105 @@ macro_rules! export_token_macro { // https://github.com/rust-lang/rust/issues/45939 #[macro_export] macro_rules! Token { - (abstract) => { $crate::token::Abstract }; - (as) => { $crate::token::As }; - (async) => { $crate::token::Async }; - (auto) => { $crate::token::Auto }; + [abstract] => { $crate::token::Abstract }; + [as] => { $crate::token::As }; + [async] => { $crate::token::Async }; + [auto] => { $crate::token::Auto }; $($await_rule => { $crate::token::Await };)* - (become) => { $crate::token::Become }; - (box) => { $crate::token::Box }; - (break) => { $crate::token::Break }; - (const) => { $crate::token::Const }; - (continue) => { $crate::token::Continue }; - (crate) => { $crate::token::Crate }; - (default) => { $crate::token::Default }; - (do) => { $crate::token::Do }; - (dyn) => { $crate::token::Dyn }; - (else) => { $crate::token::Else }; - (enum) => { $crate::token::Enum }; - (extern) => { $crate::token::Extern }; - (final) => { $crate::token::Final }; - (fn) => { $crate::token::Fn }; - (for) => { $crate::token::For }; - (if) => { $crate::token::If }; - (impl) => { $crate::token::Impl }; - (in) => { $crate::token::In }; - (let) => { $crate::token::Let }; - (loop) => { $crate::token::Loop }; - (macro) => { $crate::token::Macro }; - (match) => { $crate::token::Match }; - (mod) => { $crate::token::Mod }; - (move) => { $crate::token::Move }; - (mut) => { $crate::token::Mut }; - (override) => { $crate::token::Override }; - (priv) => { $crate::token::Priv }; - (pub) => { $crate::token::Pub }; - (ref) => { $crate::token::Ref }; - (return) => { $crate::token::Return }; - (Self) => { $crate::token::SelfType }; - (self) => { $crate::token::SelfValue }; - (static) => { $crate::token::Static }; - (struct) => { $crate::token::Struct }; - (super) => { $crate::token::Super }; - (trait) => { $crate::token::Trait }; - (try) => { $crate::token::Try }; - (type) => { $crate::token::Type }; - (typeof) => { $crate::token::Typeof }; - (union) => { $crate::token::Union }; - (unsafe) => { $crate::token::Unsafe }; - (unsized) => { $crate::token::Unsized }; - (use) => { $crate::token::Use }; - (virtual) => { $crate::token::Virtual }; - (where) => { $crate::token::Where }; - (while) => { $crate::token::While }; - (yield) => { $crate::token::Yield }; - (+) => { $crate::token::Add }; - (+=) => { $crate::token::AddEq }; - (&) => { $crate::token::And }; - (&&) => { $crate::token::AndAnd }; - (&=) => { $crate::token::AndEq }; - (@) => { $crate::token::At }; - (!) => { $crate::token::Bang }; - (^) => { $crate::token::Caret }; - (^=) => { $crate::token::CaretEq }; - (:) => { $crate::token::Colon }; - (::) => { $crate::token::Colon2 }; - (,) => { $crate::token::Comma }; - (/) => { $crate::token::Div }; - (/=) => { $crate::token::DivEq }; - ($) => { $crate::token::Dollar }; - (.) => { $crate::token::Dot }; - (..) => { $crate::token::Dot2 }; - (...) => { $crate::token::Dot3 }; - (..=) => { $crate::token::DotDotEq }; - (=) => { $crate::token::Eq }; - (==) => { $crate::token::EqEq }; - (>=) => { $crate::token::Ge }; - (>) => { $crate::token::Gt }; - (<=) => { $crate::token::Le }; - (<) => { $crate::token::Lt }; - (*=) => { $crate::token::MulEq }; - (!=) => { $crate::token::Ne }; - (|) => { $crate::token::Or }; - (|=) => { $crate::token::OrEq }; - (||) => { $crate::token::OrOr }; - (#) => { $crate::token::Pound }; - (?) => { $crate::token::Question }; - (->) => { $crate::token::RArrow }; - (<-) => { $crate::token::LArrow }; - (%) => { $crate::token::Rem }; - (%=) => { $crate::token::RemEq }; - (=>) => { $crate::token::FatArrow }; - (;) => { $crate::token::Semi }; - (<<) => { $crate::token::Shl }; - (<<=) => { $crate::token::ShlEq }; - (>>) => { $crate::token::Shr }; - (>>=) => { $crate::token::ShrEq }; - (*) => { $crate::token::Star }; - (-) => { $crate::token::Sub }; - (-=) => { $crate::token::SubEq }; - (~) => { $crate::token::Tilde }; - (_) => { $crate::token::Underscore }; + [become] => { $crate::token::Become }; + [box] => { $crate::token::Box }; + [break] => { $crate::token::Break }; + [const] => { $crate::token::Const }; + [continue] => { $crate::token::Continue }; + [crate] => { $crate::token::Crate }; + [default] => { $crate::token::Default }; + [do] => { $crate::token::Do }; + [dyn] => { $crate::token::Dyn }; + [else] => { $crate::token::Else }; + [enum] => { $crate::token::Enum }; + [extern] => { $crate::token::Extern }; + [final] => { $crate::token::Final }; + [fn] => { $crate::token::Fn }; + [for] => { $crate::token::For }; + [if] => { $crate::token::If }; + [impl] => { $crate::token::Impl }; + [in] => { $crate::token::In }; + [let] => { $crate::token::Let }; + [loop] => { $crate::token::Loop }; + [macro] => { $crate::token::Macro }; + [match] => { $crate::token::Match }; + [mod] => { $crate::token::Mod }; + [move] => { $crate::token::Move }; + [mut] => { $crate::token::Mut }; + [override] => { $crate::token::Override }; + [priv] => { $crate::token::Priv }; + [pub] => { $crate::token::Pub }; + [ref] => { $crate::token::Ref }; + [return] => { $crate::token::Return }; + [Self] => { $crate::token::SelfType }; + [self] => { $crate::token::SelfValue }; + [static] => { $crate::token::Static }; + [struct] => { $crate::token::Struct }; + [super] => { $crate::token::Super }; + [trait] => { $crate::token::Trait }; + [try] => { $crate::token::Try }; + [type] => { $crate::token::Type }; + [typeof] => { $crate::token::Typeof }; + [union] => { $crate::token::Union }; + [unsafe] => { $crate::token::Unsafe }; + [unsized] => { $crate::token::Unsized }; + [use] => { $crate::token::Use }; + [virtual] => { $crate::token::Virtual }; + [where] => { $crate::token::Where }; + [while] => { $crate::token::While }; + [yield] => { $crate::token::Yield }; + [+] => { $crate::token::Add }; + [+=] => { $crate::token::AddEq }; + [&] => { $crate::token::And }; + [&&] => { $crate::token::AndAnd }; + [&=] => { $crate::token::AndEq }; + [@] => { $crate::token::At }; + [!] => { $crate::token::Bang }; + [^] => { $crate::token::Caret }; + [^=] => { $crate::token::CaretEq }; + [:] => { $crate::token::Colon }; + [::] => { $crate::token::Colon2 }; + [,] => { $crate::token::Comma }; + [/] => { $crate::token::Div }; + [/=] => { $crate::token::DivEq }; + [$] => { $crate::token::Dollar }; + [.] => { $crate::token::Dot }; + [..] => { $crate::token::Dot2 }; + [...] => { $crate::token::Dot3 }; + [..=] => { $crate::token::DotDotEq }; + [=] => { $crate::token::Eq }; + [==] => { $crate::token::EqEq }; + [>=] => { $crate::token::Ge }; + [>] => { $crate::token::Gt }; + [<=] => { $crate::token::Le }; + [<] => { $crate::token::Lt }; + [*=] => { $crate::token::MulEq }; + [!=] => { $crate::token::Ne }; + [|] => { $crate::token::Or }; + [|=] => { $crate::token::OrEq }; + [||] => { $crate::token::OrOr }; + [#] => { $crate::token::Pound }; + [?] => { $crate::token::Question }; + [->] => { $crate::token::RArrow }; + [<-] => { $crate::token::LArrow }; + [%] => { $crate::token::Rem }; + [%=] => { $crate::token::RemEq }; + [=>] => { $crate::token::FatArrow }; + [;] => { $crate::token::Semi }; + [<<] => { $crate::token::Shl }; + [<<=] => { $crate::token::ShlEq }; + [>>] => { $crate::token::Shr }; + [>>=] => { $crate::token::ShrEq }; + [*] => { $crate::token::Star }; + [-] => { $crate::token::Sub }; + [-=] => { $crate::token::SubEq }; + [~] => { $crate::token::Tilde }; + [_] => { $crate::token::Underscore }; } }; } @@ -820,20 +879,19 @@ macro_rules! export_token_macro { // https://github.com/rust-lang/rust/issues/57919 // We put the Token![await] rule in a place that is not lexed by old rustc. #[cfg(not(syn_omit_await_from_token_macro))] -include!("await.rs"); // export_token_macro![(await)]; +include!("await.rs"); // export_token_macro! {[await]} #[cfg(syn_omit_await_from_token_macro)] -export_token_macro![]; +export_token_macro! {} // Not public API. #[doc(hidden)] #[cfg(feature = "parsing")] pub mod parsing { - use proc_macro2::{Spacing, Span}; - use crate::buffer::Cursor; use crate::error::{Error, Result}; use crate::parse::ParseStream; use crate::span::FromSpans; + use proc_macro2::{Spacing, Span}; pub fn keyword(input: ParseStream, token: &str) -> Result<Span> { input.step(|cursor| { @@ -855,7 +913,7 @@ pub mod parsing { } pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> { - let mut spans = [input.cursor().span(); 3]; + let mut spans = [input.span(); 3]; punct_helper(input, token, &mut spans)?; Ok(S::from_spans(&spans)) } diff --git a/1.0.7/src/tt.rs b/src/tt.rs index 8dba0627..d87c0ed4 100644 --- a/1.0.7/src/tt.rs +++ b/src/tt.rs @@ -1,6 +1,5 @@ -use std::hash::{Hash, Hasher}; - use proc_macro2::{Delimiter, TokenStream, TokenTree}; +use std::hash::{Hash, Hasher}; pub struct TokenTreeHelper<'a>(pub &'a TokenTree); diff --git a/1.0.7/src/ty.rs b/src/ty.rs index 1e5b51f3..b60109f9 100644 --- a/1.0.7/src/ty.rs +++ b/src/ty.rs @@ -1,26 +1,20 @@ use super::*; use crate::punctuated::Punctuated; -#[cfg(feature = "extra-traits")] -use crate::tt::TokenStreamHelper; use proc_macro2::TokenStream; -#[cfg(feature = "extra-traits")] -use std::hash::{Hash, Hasher}; ast_enum_of_structs! { /// The possible types that a Rust value could have. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// - /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums - // - // TODO: change syntax-tree-enum link to an intra rustdoc link, currently - // blocked on https://github.com/rust-lang/rust/issues/62833 - pub enum Type #manual_extra_traits { + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub enum Type { /// A fixed size array type: `[T; n]`. Array(TypeArray), @@ -69,16 +63,40 @@ ast_enum_of_structs! { /// Tokens in type position not interpreted by Syn. Verbatim(TokenStream), + // The following is the only supported idiom for exhaustive matching of + // this enum. + // + // match expr { + // Type::Array(e) => {...} + // Type::BareFn(e) => {...} + // ... + // Type::Verbatim(e) => {...} + // + // #[cfg(test)] + // Type::__TestExhaustive(_) => unimplemented!(), + // #[cfg(not(test))] + // _ => { /* some sane fallback */ } + // } + // + // This way we fail your tests but don't break your library when adding + // a variant. You will be notified by a test failure when a variant is + // added, so that you can add code to handle it, but your library will + // continue to compile and work for downstream users in the interim. + // + // Once `deny(reachable)` is available in rustc, Type will be + // reimplemented as a non_exhaustive enum. + // https://github.com/rust-lang/rust/issues/44109#issuecomment-521781237 #[doc(hidden)] - __Nonexhaustive, + __TestExhaustive(crate::private), } } ast_struct! { /// A fixed size array type: `[T; n]`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeArray { pub bracket_token: token::Bracket, pub elem: Box<Type>, @@ -90,8 +108,9 @@ ast_struct! { ast_struct! { /// A bare function type: `fn(usize) -> bool`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeBareFn { pub lifetimes: Option<BoundLifetimes>, pub unsafety: Option<Token![unsafe]>, @@ -107,8 +126,9 @@ ast_struct! { ast_struct! { /// A type contained within invisible delimiters. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeGroup { pub group_token: token::Group, pub elem: Box<Type>, @@ -119,8 +139,9 @@ ast_struct! { /// An `impl Bound1 + Bound2 + Bound3` type where `Bound` is a trait or /// a lifetime. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeImplTrait { pub impl_token: Token![impl], pub bounds: Punctuated<TypeParamBound, Token![+]>, @@ -130,8 +151,9 @@ ast_struct! { ast_struct! { /// Indication that a type should be inferred by the compiler: `_`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeInfer { pub underscore_token: Token![_], } @@ -140,8 +162,9 @@ ast_struct! { ast_struct! { /// A macro in the type position. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeMacro { pub mac: Macro, } @@ -150,8 +173,9 @@ ast_struct! { ast_struct! { /// The never type: `!`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeNever { pub bang_token: Token![!], } @@ -160,8 +184,9 @@ ast_struct! { ast_struct! { /// A parenthesized type equivalent to the inner type. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeParen { pub paren_token: token::Paren, pub elem: Box<Type>, @@ -172,8 +197,9 @@ ast_struct! { /// A path like `std::slice::Iter`, optionally qualified with a /// self-type as in `<Vec<T> as SomeTrait>::Associated`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypePath { pub qself: Option<QSelf>, pub path: Path, @@ -183,8 +209,9 @@ ast_struct! { ast_struct! { /// A raw pointer type: `*const T` or `*mut T`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypePtr { pub star_token: Token![*], pub const_token: Option<Token![const]>, @@ -196,8 +223,9 @@ ast_struct! { ast_struct! { /// A reference type: `&'a T` or `&'a mut T`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeReference { pub and_token: Token![&], pub lifetime: Option<Lifetime>, @@ -209,8 +237,9 @@ ast_struct! { ast_struct! { /// A dynamically sized slice type: `[T]`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeSlice { pub bracket_token: token::Bracket, pub elem: Box<Type>, @@ -221,8 +250,9 @@ ast_struct! { /// A trait object type `Bound1 + Bound2 + Bound3` where `Bound` is a /// trait or a lifetime. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeTraitObject { pub dyn_token: Option<Token![dyn]>, pub bounds: Punctuated<TypeParamBound, Token![+]>, @@ -232,120 +262,21 @@ ast_struct! { ast_struct! { /// A tuple type: `(A, B, C, String)`. /// - /// *This type is available if Syn is built with the `"derive"` or + /// *This type is available only if Syn is built with the `"derive"` or /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct TypeTuple { pub paren_token: token::Paren, pub elems: Punctuated<Type, Token![,]>, } } -#[cfg(feature = "extra-traits")] -impl Eq for Type {} - -#[cfg(feature = "extra-traits")] -impl PartialEq for Type { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Type::Array(this), Type::Array(other)) => this == other, - (Type::BareFn(this), Type::BareFn(other)) => this == other, - (Type::Group(this), Type::Group(other)) => this == other, - (Type::ImplTrait(this), Type::ImplTrait(other)) => this == other, - (Type::Infer(this), Type::Infer(other)) => this == other, - (Type::Macro(this), Type::Macro(other)) => this == other, - (Type::Never(this), Type::Never(other)) => this == other, - (Type::Paren(this), Type::Paren(other)) => this == other, - (Type::Path(this), Type::Path(other)) => this == other, - (Type::Ptr(this), Type::Ptr(other)) => this == other, - (Type::Reference(this), Type::Reference(other)) => this == other, - (Type::Slice(this), Type::Slice(other)) => this == other, - (Type::TraitObject(this), Type::TraitObject(other)) => this == other, - (Type::Tuple(this), Type::Tuple(other)) => this == other, - (Type::Verbatim(this), Type::Verbatim(other)) => { - TokenStreamHelper(this) == TokenStreamHelper(other) - } - _ => false, - } - } -} - -#[cfg(feature = "extra-traits")] -impl Hash for Type { - fn hash<H>(&self, hash: &mut H) - where - H: Hasher, - { - match self { - Type::Array(ty) => { - hash.write_u8(0); - ty.hash(hash); - } - Type::BareFn(ty) => { - hash.write_u8(1); - ty.hash(hash); - } - Type::Group(ty) => { - hash.write_u8(2); - ty.hash(hash); - } - Type::ImplTrait(ty) => { - hash.write_u8(3); - ty.hash(hash); - } - Type::Infer(ty) => { - hash.write_u8(4); - ty.hash(hash); - } - Type::Macro(ty) => { - hash.write_u8(5); - ty.hash(hash); - } - Type::Never(ty) => { - hash.write_u8(6); - ty.hash(hash); - } - Type::Paren(ty) => { - hash.write_u8(7); - ty.hash(hash); - } - Type::Path(ty) => { - hash.write_u8(8); - ty.hash(hash); - } - Type::Ptr(ty) => { - hash.write_u8(9); - ty.hash(hash); - } - Type::Reference(ty) => { - hash.write_u8(10); - ty.hash(hash); - } - Type::Slice(ty) => { - hash.write_u8(11); - ty.hash(hash); - } - Type::TraitObject(ty) => { - hash.write_u8(12); - ty.hash(hash); - } - Type::Tuple(ty) => { - hash.write_u8(13); - ty.hash(hash); - } - Type::Verbatim(ty) => { - hash.write_u8(14); - TokenStreamHelper(ty).hash(hash); - } - Type::__Nonexhaustive => unreachable!(), - } - } -} - ast_struct! { /// The binary interface of a function: `extern "C"`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct Abi { pub extern_token: Token![extern], pub name: Option<LitStr>, @@ -355,8 +286,9 @@ ast_struct! { ast_struct! { /// An argument in a function type: the `usize` in `fn(usize) -> bool`. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct BareFnArg { pub attrs: Vec<Attribute>, pub name: Option<(Ident, Token![:])>, @@ -377,8 +309,9 @@ ast_struct! { /// } /// ``` /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub struct Variadic { pub attrs: Vec<Attribute>, pub dots: Token![...], @@ -388,8 +321,9 @@ ast_struct! { ast_enum! { /// Return type of a function signature. /// - /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// *This type is available only if Syn is built with the `"derive"` or `"full"` /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] pub enum ReturnType { /// Return type is not specified. /// @@ -403,16 +337,17 @@ ast_enum! { #[cfg(feature = "parsing")] pub mod parsing { use super::*; - use crate::ext::IdentExt; use crate::parse::{Parse, ParseStream, Result}; use crate::path; use proc_macro2::{Punct, Spacing, TokenTree}; use std::iter::FromIterator; + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Type { fn parse(input: ParseStream) -> Result<Self> { - ambig_ty(input, true) + let allow_plus = true; + ambig_ty(input, allow_plus) } } @@ -422,14 +357,47 @@ pub mod parsing { /// contain a `+` character. /// /// This parser does not allow a `+`, while the default parser does. + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn without_plus(input: ParseStream) -> Result<Self> { - ambig_ty(input, false) + let allow_plus = false; + ambig_ty(input, allow_plus) } } fn ambig_ty(input: ParseStream, allow_plus: bool) -> Result<Type> { + let begin = input.fork(); + if input.peek(token::Group) { - return input.parse().map(Type::Group); + let mut group: TypeGroup = input.parse()?; + if input.peek(Token![::]) && input.peek3(Ident::peek_any) { + if let Type::Path(mut ty) = *group.elem { + Path::parse_rest(input, &mut ty.path, false)?; + return Ok(Type::Path(ty)); + } else { + return Ok(Type::Path(TypePath { + qself: Some(QSelf { + lt_token: Token![<](group.group_token.span), + position: 0, + as_token: None, + gt_token: Token![>](group.group_token.span), + ty: group.elem, + }), + path: Path::parse_helper(input, false)?, + })); + } + } else if input.peek(Token![<]) || input.peek(Token![::]) && input.peek3(Token![<]) { + if let Type::Path(mut ty) = *group.elem { + let arguments = &mut ty.path.segments.last_mut().unwrap().arguments; + if let PathArguments::None = arguments { + *arguments = PathArguments::AngleBracketed(input.parse()?); + Path::parse_rest(input, &mut ty.path, false)?; + return Ok(Type::Path(ty)); + } else { + group.elem = Box::new(Type::Path(ty)); + } + } + } + return Ok(Type::Group(group)); } let mut lifetimes = None::<BoundLifetimes>; @@ -490,9 +458,13 @@ pub mod parsing { let mut elems = Punctuated::new(); elems.push_value(first); elems.push_punct(content.parse()?); - let rest: Punctuated<Type, Token![,]> = - content.parse_terminated(Parse::parse)?; - elems.extend(rest); + while !content.is_empty() { + elems.push_value(content.parse()?); + if content.is_empty() { + break; + } + elems.push_punct(content.parse()?); + } elems }, })); @@ -526,7 +498,7 @@ pub mod parsing { ..trait_bound }) } - other => other, + other @ TypeParamBound::Lifetime(_) => other, } } _ => break, @@ -551,17 +523,20 @@ pub mod parsing { })) } else if lookahead.peek(Token![fn]) || lookahead.peek(Token![unsafe]) - || lookahead.peek(Token![extern]) && !input.peek2(Token![::]) + || lookahead.peek(Token![extern]) { - let mut bare_fn: TypeBareFn = input.parse()?; - bare_fn.lifetimes = lifetimes; - Ok(Type::BareFn(bare_fn)) + let allow_mut_self = true; + if let Some(mut bare_fn) = parse_bare_fn(input, allow_mut_self)? { + bare_fn.lifetimes = lifetimes; + Ok(Type::BareFn(bare_fn)) + } else { + Ok(Type::Verbatim(verbatim::between(begin, input))) + } } else if lookahead.peek(Ident) || input.peek(Token![super]) || input.peek(Token![self]) || input.peek(Token![Self]) || input.peek(Token![crate]) - || input.peek(Token![extern]) || lookahead.peek(Token![::]) || lookahead.peek(Token![<]) { @@ -666,6 +641,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeSlice { fn parse(input: ParseStream) -> Result<Self> { let content; @@ -676,6 +652,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeArray { fn parse(input: ParseStream) -> Result<Self> { let content; @@ -688,6 +665,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypePtr { fn parse(input: ParseStream) -> Result<Self> { let star_token: Token![*] = input.parse()?; @@ -710,6 +688,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeReference { fn parse(input: ParseStream) -> Result<Self> { Ok(TypeReference { @@ -722,49 +701,65 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeBareFn { fn parse(input: ParseStream) -> Result<Self> { - let args; - let mut variadic = None; - Ok(TypeBareFn { - lifetimes: input.parse()?, - unsafety: input.parse()?, - abi: input.parse()?, - fn_token: input.parse()?, - paren_token: parenthesized!(args in input), - inputs: { - let mut inputs = Punctuated::new(); - - while !args.is_empty() { - let attrs = args.call(Attribute::parse_outer)?; - - if inputs.empty_or_trailing() && args.peek(Token![...]) { - variadic = Some(Variadic { - attrs, - dots: args.parse()?, - }); - break; - } + let allow_mut_self = false; + parse_bare_fn(input, allow_mut_self).map(Option::unwrap) + } + } - inputs.push_value(BareFnArg { + fn parse_bare_fn(input: ParseStream, allow_mut_self: bool) -> Result<Option<TypeBareFn>> { + let args; + let mut variadic = None; + let mut has_mut_self = false; + + let bare_fn = TypeBareFn { + lifetimes: input.parse()?, + unsafety: input.parse()?, + abi: input.parse()?, + fn_token: input.parse()?, + paren_token: parenthesized!(args in input), + inputs: { + let mut inputs = Punctuated::new(); + + while !args.is_empty() { + let attrs = args.call(Attribute::parse_outer)?; + + if inputs.empty_or_trailing() && args.peek(Token![...]) { + variadic = Some(Variadic { attrs, - ..args.parse()? + dots: args.parse()?, }); - if args.is_empty() { - break; - } + break; + } - inputs.push_punct(args.parse()?); + if let Some(arg) = parse_bare_fn_arg(&args, allow_mut_self)? { + inputs.push_value(BareFnArg { attrs, ..arg }); + } else { + has_mut_self = true; + } + if args.is_empty() { + break; } - inputs - }, - variadic, - output: input.call(ReturnType::without_plus)?, - }) + inputs.push_punct(args.parse()?); + } + + inputs + }, + variadic, + output: input.call(ReturnType::without_plus)?, + }; + + if has_mut_self { + Ok(None) + } else { + Ok(Some(bare_fn)) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeNever { fn parse(input: ParseStream) -> Result<Self> { Ok(TypeNever { @@ -773,6 +768,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeInfer { fn parse(input: ParseStream) -> Result<Self> { Ok(TypeInfer { @@ -781,16 +777,40 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeTuple { fn parse(input: ParseStream) -> Result<Self> { let content; + let paren_token = parenthesized!(content in input); + + if content.is_empty() { + return Ok(TypeTuple { + paren_token, + elems: Punctuated::new(), + }); + } + + let first: Type = content.parse()?; Ok(TypeTuple { - paren_token: parenthesized!(content in input), - elems: content.parse_terminated(Type::parse)?, + paren_token, + elems: { + let mut elems = Punctuated::new(); + elems.push_value(first); + elems.push_punct(content.parse()?); + while !content.is_empty() { + elems.push_value(content.parse()?); + if content.is_empty() { + break; + } + elems.push_punct(content.parse()?); + } + elems + }, }) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeMacro { fn parse(input: ParseStream) -> Result<Self> { Ok(TypeMacro { @@ -799,6 +819,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypePath { fn parse(input: ParseStream) -> Result<Self> { let (qself, mut path) = path::parsing::qpath(input, false)?; @@ -815,9 +836,11 @@ pub mod parsing { impl ReturnType { pub fn without_plus(input: ParseStream) -> Result<Self> { - Self::parse(input, false) + let allow_plus = false; + Self::parse(input, allow_plus) } + #[doc(hidden)] pub fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> { if input.peek(Token![->]) { let arrow = input.parse()?; @@ -829,12 +852,14 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ReturnType { fn parse(input: ParseStream) -> Result<Self> { Self::parse(input, true) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeTraitObject { fn parse(input: ParseStream) -> Result<Self> { Self::parse(input, true) @@ -852,10 +877,12 @@ pub mod parsing { impl TypeTraitObject { pub fn without_plus(input: ParseStream) -> Result<Self> { - Self::parse(input, false) + let allow_plus = false; + Self::parse(input, allow_plus) } // Only allow multiple trait references if allow_plus is true. + #[doc(hidden)] pub fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> { Ok(TypeTraitObject { dyn_token: input.parse()?, @@ -885,6 +912,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeImplTrait { fn parse(input: ParseStream) -> Result<Self> { Ok(TypeImplTrait { @@ -906,6 +934,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeGroup { fn parse(input: ParseStream) -> Result<Self> { let group = crate::group::parse_group(input)?; @@ -916,9 +945,11 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TypeParen { fn parse(input: ParseStream) -> Result<Self> { - Self::parse(input, false) + let allow_plus = false; + Self::parse(input, allow_plus) } } @@ -932,43 +963,79 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for BareFnArg { fn parse(input: ParseStream) -> Result<Self> { - Ok(BareFnArg { - attrs: input.call(Attribute::parse_outer)?, - name: { - if (input.peek(Ident) || input.peek(Token![_])) - && input.peek2(Token![:]) - && !input.peek2(Token![::]) - { - let name = input.call(Ident::parse_any)?; - let colon: Token![:] = input.parse()?; - Some((name, colon)) - } else { - None - } - }, - ty: match input.parse::<Option<Token![...]>>()? { - Some(dot3) => { - let args = vec![ - TokenTree::Punct(Punct::new('.', Spacing::Joint)), - TokenTree::Punct(Punct::new('.', Spacing::Joint)), - TokenTree::Punct(Punct::new('.', Spacing::Alone)), - ]; - let tokens = TokenStream::from_iter(args.into_iter().zip(&dot3.spans).map( - |(mut arg, span)| { - arg.set_span(*span); - arg - }, - )); - Type::Verbatim(tokens) - } - None => input.parse()?, - }, - }) + let allow_mut_self = false; + parse_bare_fn_arg(input, allow_mut_self).map(Option::unwrap) + } + } + + fn parse_bare_fn_arg( + input: ParseStream, + mut allow_mut_self: bool, + ) -> Result<Option<BareFnArg>> { + let mut has_mut_self = false; + let arg = BareFnArg { + attrs: input.call(Attribute::parse_outer)?, + name: { + if (input.peek(Ident) || input.peek(Token![_]) || input.peek(Token![self])) + && input.peek2(Token![:]) + && !input.peek2(Token![::]) + { + let name = input.call(Ident::parse_any)?; + let colon: Token![:] = input.parse()?; + Some((name, colon)) + } else if allow_mut_self + && input.peek(Token![mut]) + && input.peek2(Token![self]) + && input.peek3(Token![:]) + && !input.peek3(Token![::]) + { + has_mut_self = true; + allow_mut_self = false; + input.parse::<Token![mut]>()?; + input.parse::<Token![self]>()?; + input.parse::<Token![:]>()?; + None + } else { + None + } + }, + ty: if !has_mut_self && input.peek(Token![...]) { + let dot3 = input.parse::<Token![...]>()?; + let args = vec![ + TokenTree::Punct(Punct::new('.', Spacing::Joint)), + TokenTree::Punct(Punct::new('.', Spacing::Joint)), + TokenTree::Punct(Punct::new('.', Spacing::Alone)), + ]; + let tokens = TokenStream::from_iter(args.into_iter().zip(&dot3.spans).map( + |(mut arg, span)| { + arg.set_span(*span); + arg + }, + )); + Type::Verbatim(tokens) + } else if allow_mut_self && input.peek(Token![mut]) && input.peek2(Token![self]) { + has_mut_self = true; + input.parse::<Token![mut]>()?; + Type::Path(TypePath { + qself: None, + path: input.parse::<Token![self]>()?.into(), + }) + } else { + input.parse()? + }, + }; + + if has_mut_self { + Ok(None) + } else { + Ok(Some(arg)) } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Abi { fn parse(input: ParseStream) -> Result<Self> { Ok(Abi { @@ -978,6 +1045,7 @@ pub mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Option<Abi> { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Token![extern]) { @@ -992,13 +1060,12 @@ pub mod parsing { #[cfg(feature = "printing")] mod printing { use super::*; - - use proc_macro2::TokenStream; - use quote::{ToTokens, TokenStreamExt}; - use crate::attr::FilterAttrs; use crate::print::TokensOrDefault; + use proc_macro2::TokenStream; + use quote::{ToTokens, TokenStreamExt}; + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeSlice { fn to_tokens(&self, tokens: &mut TokenStream) { self.bracket_token.surround(tokens, |tokens| { @@ -1007,6 +1074,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeArray { fn to_tokens(&self, tokens: &mut TokenStream) { self.bracket_token.surround(tokens, |tokens| { @@ -1017,6 +1085,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypePtr { fn to_tokens(&self, tokens: &mut TokenStream) { self.star_token.to_tokens(tokens); @@ -1030,6 +1099,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeReference { fn to_tokens(&self, tokens: &mut TokenStream) { self.and_token.to_tokens(tokens); @@ -1039,6 +1109,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeBareFn { fn to_tokens(&self, tokens: &mut TokenStream) { self.lifetimes.to_tokens(tokens); @@ -1059,12 +1130,14 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeNever { fn to_tokens(&self, tokens: &mut TokenStream) { self.bang_token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeTuple { fn to_tokens(&self, tokens: &mut TokenStream) { self.paren_token.surround(tokens, |tokens| { @@ -1073,12 +1146,14 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypePath { fn to_tokens(&self, tokens: &mut TokenStream) { private::print_path(tokens, &self.qself, &self.path); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeTraitObject { fn to_tokens(&self, tokens: &mut TokenStream) { self.dyn_token.to_tokens(tokens); @@ -1086,6 +1161,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeImplTrait { fn to_tokens(&self, tokens: &mut TokenStream) { self.impl_token.to_tokens(tokens); @@ -1093,6 +1169,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeGroup { fn to_tokens(&self, tokens: &mut TokenStream) { self.group_token.surround(tokens, |tokens| { @@ -1101,6 +1178,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeParen { fn to_tokens(&self, tokens: &mut TokenStream) { self.paren_token.surround(tokens, |tokens| { @@ -1109,18 +1187,21 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeInfer { fn to_tokens(&self, tokens: &mut TokenStream) { self.underscore_token.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for TypeMacro { fn to_tokens(&self, tokens: &mut TokenStream) { self.mac.to_tokens(tokens); } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ReturnType { fn to_tokens(&self, tokens: &mut TokenStream) { match self { @@ -1133,6 +1214,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for BareFnArg { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -1144,6 +1226,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Variadic { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); @@ -1151,6 +1234,7 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Abi { fn to_tokens(&self, tokens: &mut TokenStream) { self.extern_token.to_tokens(tokens); diff --git a/src/verbatim.rs b/src/verbatim.rs new file mode 100644 index 00000000..0686352f --- /dev/null +++ b/src/verbatim.rs @@ -0,0 +1,15 @@ +use crate::parse::{ParseBuffer, ParseStream}; +use proc_macro2::TokenStream; +use std::iter; + +pub fn between<'a>(begin: ParseBuffer<'a>, end: ParseStream<'a>) -> TokenStream { + let end = end.cursor(); + let mut cursor = begin.cursor(); + let mut tokens = TokenStream::new(); + while cursor != end { + let (tt, next) = cursor.token_tree().unwrap(); + tokens.extend(iter::once(tt)); + cursor = next; + } + tokens +} diff --git a/src/whitespace.rs b/src/whitespace.rs new file mode 100644 index 00000000..7be082e1 --- /dev/null +++ b/src/whitespace.rs @@ -0,0 +1,65 @@ +pub fn skip(mut s: &str) -> &str { + 'skip: while !s.is_empty() { + let byte = s.as_bytes()[0]; + if byte == b'/' { + if s.starts_with("//") + && (!s.starts_with("///") || s.starts_with("////")) + && !s.starts_with("//!") + { + if let Some(i) = s.find('\n') { + s = &s[i + 1..]; + continue; + } else { + return ""; + } + } else if s.starts_with("/**/") { + s = &s[4..]; + continue; + } else if s.starts_with("/*") + && (!s.starts_with("/**") || s.starts_with("/***")) + && !s.starts_with("/*!") + { + let mut depth = 0; + let bytes = s.as_bytes(); + let mut i = 0; + let upper = bytes.len() - 1; + while i < upper { + if bytes[i] == b'/' && bytes[i + 1] == b'*' { + depth += 1; + i += 1; // eat '*' + } else if bytes[i] == b'*' && bytes[i + 1] == b'/' { + depth -= 1; + if depth == 0 { + s = &s[i + 2..]; + continue 'skip; + } + i += 1; // eat '/' + } + i += 1; + } + return s; + } + } + match byte { + b' ' | 0x09..=0x0d => { + s = &s[1..]; + continue; + } + b if b <= 0x7f => {} + _ => { + let ch = s.chars().next().unwrap(); + if is_whitespace(ch) { + s = &s[ch.len_utf8()..]; + continue; + } + } + } + return s; + } + s +} + +fn is_whitespace(ch: char) -> bool { + // Rust treats left-to-right mark and right-to-left mark as whitespace + ch.is_whitespace() || ch == '\u{200e}' || ch == '\u{200f}' +} diff --git a/tests/.gitignore b/tests/.gitignore new file mode 100644 index 00000000..291ed43a --- /dev/null +++ b/tests/.gitignore @@ -0,0 +1 @@ +/*.pending-snap diff --git a/tests/common/eq.rs b/tests/common/eq.rs new file mode 100644 index 00000000..944d5851 --- /dev/null +++ b/tests/common/eq.rs @@ -0,0 +1,623 @@ +extern crate rustc_ast; +extern crate rustc_data_structures; +extern crate rustc_span; + +use rustc_ast::ast::{ + AngleBracketedArg, AngleBracketedArgs, AnonConst, Arm, AssocItemKind, AssocTyConstraint, + AssocTyConstraintKind, Async, AttrId, AttrItem, AttrKind, AttrStyle, Attribute, BareFnTy, + BinOpKind, BindingMode, Block, BlockCheckMode, BorrowKind, CaptureBy, Const, Crate, CrateSugar, + Defaultness, EnumDef, Expr, ExprField, ExprKind, Extern, FieldDef, FloatTy, FnDecl, FnHeader, + FnKind, FnRetTy, FnSig, ForeignItemKind, ForeignMod, GenericArg, GenericArgs, GenericBound, + GenericParam, GenericParamKind, Generics, GlobalAsm, ImplKind, ImplPolarity, Inline, InlineAsm, + InlineAsmOperand, InlineAsmOptions, InlineAsmRegOrRegClass, InlineAsmTemplatePiece, IntTy, + IsAuto, Item, ItemKind, Label, Lifetime, Lit, LitFloatType, LitIntType, LitKind, + LlvmAsmDialect, LlvmInlineAsm, LlvmInlineAsmOutput, Local, MacArgs, MacCall, MacCallStmt, + MacDelimiter, MacStmtStyle, MacroDef, ModKind, Movability, MutTy, Mutability, NodeId, Param, + ParenthesizedArgs, Pat, PatField, PatKind, Path, PathSegment, PolyTraitRef, QSelf, RangeEnd, + RangeLimits, RangeSyntax, Stmt, StmtKind, StrLit, StrStyle, StructExpr, StructRest, + TraitBoundModifier, TraitKind, TraitObjectSyntax, TraitRef, Ty, TyAliasKind, TyKind, UintTy, + UnOp, Unsafe, UnsafeSource, UseTree, UseTreeKind, Variant, VariantData, Visibility, + VisibilityKind, WhereBoundPredicate, WhereClause, WhereEqPredicate, WherePredicate, + WhereRegionPredicate, +}; +use rustc_ast::ptr::P; +use rustc_ast::token::{self, CommentKind, DelimToken, Nonterminal, Token, TokenKind}; +use rustc_ast::tokenstream::{DelimSpan, LazyTokenStream, TokenStream, TokenTree}; +use rustc_data_structures::sync::Lrc; +use rustc_data_structures::thin_vec::ThinVec; +use rustc_span::source_map::Spanned; +use rustc_span::symbol::{sym, Ident}; +use rustc_span::{Span, Symbol, SyntaxContext, DUMMY_SP}; + +pub trait SpanlessEq { + fn eq(&self, other: &Self) -> bool; +} + +impl<T: SpanlessEq> SpanlessEq for Box<T> { + fn eq(&self, other: &Self) -> bool { + SpanlessEq::eq(&**self, &**other) + } +} + +impl<T: SpanlessEq> SpanlessEq for P<T> { + fn eq(&self, other: &Self) -> bool { + SpanlessEq::eq(&**self, &**other) + } +} + +impl<T: ?Sized + SpanlessEq> SpanlessEq for Lrc<T> { + fn eq(&self, other: &Self) -> bool { + SpanlessEq::eq(&**self, &**other) + } +} + +impl<T: SpanlessEq> SpanlessEq for Option<T> { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (None, None) => true, + (Some(this), Some(other)) => SpanlessEq::eq(this, other), + _ => false, + } + } +} + +impl<T: SpanlessEq> SpanlessEq for [T] { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() && self.iter().zip(other).all(|(a, b)| SpanlessEq::eq(a, b)) + } +} + +impl<T: SpanlessEq> SpanlessEq for Vec<T> { + fn eq(&self, other: &Self) -> bool { + <[T] as SpanlessEq>::eq(self, other) + } +} + +impl<T: SpanlessEq> SpanlessEq for ThinVec<T> { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() + && self + .iter() + .zip(other.iter()) + .all(|(a, b)| SpanlessEq::eq(a, b)) + } +} + +impl<T: SpanlessEq> SpanlessEq for Spanned<T> { + fn eq(&self, other: &Self) -> bool { + SpanlessEq::eq(&self.node, &other.node) + } +} + +impl<A: SpanlessEq, B: SpanlessEq> SpanlessEq for (A, B) { + fn eq(&self, other: &Self) -> bool { + SpanlessEq::eq(&self.0, &other.0) && SpanlessEq::eq(&self.1, &other.1) + } +} + +macro_rules! spanless_eq_true { + ($name:ty) => { + impl SpanlessEq for $name { + fn eq(&self, _other: &Self) -> bool { + true + } + } + }; +} + +spanless_eq_true!(Span); +spanless_eq_true!(DelimSpan); +spanless_eq_true!(AttrId); +spanless_eq_true!(NodeId); +spanless_eq_true!(SyntaxContext); + +macro_rules! spanless_eq_partial_eq { + ($name:ty) => { + impl SpanlessEq for $name { + fn eq(&self, other: &Self) -> bool { + PartialEq::eq(self, other) + } + } + }; +} + +spanless_eq_partial_eq!(bool); +spanless_eq_partial_eq!(u8); +spanless_eq_partial_eq!(u16); +spanless_eq_partial_eq!(u128); +spanless_eq_partial_eq!(usize); +spanless_eq_partial_eq!(char); +spanless_eq_partial_eq!(String); +spanless_eq_partial_eq!(Symbol); +spanless_eq_partial_eq!(CommentKind); +spanless_eq_partial_eq!(DelimToken); +spanless_eq_partial_eq!(InlineAsmOptions); +spanless_eq_partial_eq!(token::LitKind); + +macro_rules! spanless_eq_struct { + { + $($name:ident)::+ $(<$param:ident>)? + $([$field:tt $this:ident $other:ident])* + $(![$ignore:tt])*; + } => { + impl $(<$param: SpanlessEq>)* SpanlessEq for $($name)::+ $(<$param>)* { + fn eq(&self, other: &Self) -> bool { + let $($name)::+ { $($field: $this,)* $($ignore: _,)* } = self; + let $($name)::+ { $($field: $other,)* $($ignore: _,)* } = other; + true $(&& SpanlessEq::eq($this, $other))* + } + } + }; + + { + $($name:ident)::+ $(<$param:ident>)? + $([$field:tt $this:ident $other:ident])* + $(![$ignore:tt])*; + !$next:tt + $($rest:tt)* + } => { + spanless_eq_struct! { + $($name)::+ $(<$param>)* + $([$field $this $other])* + $(![$ignore])* + ![$next]; + $($rest)* + } + }; + + { + $($name:ident)::+ $(<$param:ident>)? + $([$field:tt $this:ident $other:ident])* + $(![$ignore:tt])*; + $next:tt + $($rest:tt)* + } => { + spanless_eq_struct! { + $($name)::+ $(<$param>)* + $([$field $this $other])* + [$next this other] + $(![$ignore])*; + $($rest)* + } + }; +} + +macro_rules! spanless_eq_enum { + { + $($name:ident)::+; + $([$($variant:ident)::+; $([$field:tt $this:ident $other:ident])* $(![$ignore:tt])*])* + } => { + impl SpanlessEq for $($name)::+ { + fn eq(&self, other: &Self) -> bool { + match self { + $( + $($variant)::+ { .. } => {} + )* + } + #[allow(unreachable_patterns)] + match (self, other) { + $( + ( + $($variant)::+ { $($field: $this,)* $($ignore: _,)* }, + $($variant)::+ { $($field: $other,)* $($ignore: _,)* }, + ) => { + true $(&& SpanlessEq::eq($this, $other))* + } + )* + _ => false, + } + } + } + }; + + { + $($name:ident)::+; + $([$($variant:ident)::+; $($fields:tt)*])* + $next:ident [$([$($named:tt)*])* $(![$ignore:tt])*] (!$i:tt $($field:tt)*) + $($rest:tt)* + } => { + spanless_eq_enum! { + $($name)::+; + $([$($variant)::+; $($fields)*])* + $next [$([$($named)*])* $(![$ignore])* ![$i]] ($($field)*) + $($rest)* + } + }; + + { + $($name:ident)::+; + $([$($variant:ident)::+; $($fields:tt)*])* + $next:ident [$([$($named:tt)*])* $(![$ignore:tt])*] ($i:tt $($field:tt)*) + $($rest:tt)* + } => { + spanless_eq_enum! { + $($name)::+; + $([$($variant)::+; $($fields)*])* + $next [$([$($named)*])* [$i this other] $(![$ignore])*] ($($field)*) + $($rest)* + } + }; + + { + $($name:ident)::+; + $([$($variant:ident)::+; $($fields:tt)*])* + $next:ident [$($named:tt)*] () + $($rest:tt)* + } => { + spanless_eq_enum! { + $($name)::+; + $([$($variant)::+; $($fields)*])* + [$($name)::+::$next; $($named)*] + $($rest)* + } + }; + + { + $($name:ident)::+; + $([$($variant:ident)::+; $($fields:tt)*])* + $next:ident ($($field:tt)*) + $($rest:tt)* + } => { + spanless_eq_enum! { + $($name)::+; + $([$($variant)::+; $($fields)*])* + $next [] ($($field)*) + $($rest)* + } + }; + + { + $($name:ident)::+; + $([$($variant:ident)::+; $($fields:tt)*])* + $next:ident + $($rest:tt)* + } => { + spanless_eq_enum! { + $($name)::+; + $([$($variant)::+; $($fields)*])* + [$($name)::+::$next;] + $($rest)* + } + }; +} + +spanless_eq_struct!(AngleBracketedArgs; span args); +spanless_eq_struct!(AnonConst; id value); +spanless_eq_struct!(Arm; attrs pat guard body span id is_placeholder); +spanless_eq_struct!(AssocTyConstraint; id ident gen_args kind span); +spanless_eq_struct!(AttrItem; path args tokens); +spanless_eq_struct!(Attribute; kind id style span); +spanless_eq_struct!(BareFnTy; unsafety ext generic_params decl); +spanless_eq_struct!(Block; stmts id rules span tokens); +spanless_eq_struct!(Crate; attrs items span proc_macros); +spanless_eq_struct!(EnumDef; variants); +spanless_eq_struct!(Expr; id kind span attrs !tokens); +spanless_eq_struct!(ExprField; attrs id span ident expr is_shorthand is_placeholder); +spanless_eq_struct!(FieldDef; attrs id span vis ident ty is_placeholder); +spanless_eq_struct!(FnDecl; inputs output); +spanless_eq_struct!(FnHeader; constness asyncness unsafety ext); +spanless_eq_struct!(FnKind; 0 1 2 3); +spanless_eq_struct!(FnSig; header decl span); +spanless_eq_struct!(ForeignMod; unsafety abi items); +spanless_eq_struct!(GenericParam; id ident attrs bounds is_placeholder kind); +spanless_eq_struct!(Generics; params where_clause span); +spanless_eq_struct!(GlobalAsm; asm); +spanless_eq_struct!(ImplKind; unsafety polarity defaultness constness generics of_trait self_ty items); +spanless_eq_struct!(InlineAsm; template operands options line_spans); +spanless_eq_struct!(Item<K>; attrs id span vis ident kind !tokens); +spanless_eq_struct!(Label; ident); +spanless_eq_struct!(Lifetime; id ident); +spanless_eq_struct!(Lit; token kind span); +spanless_eq_struct!(LlvmInlineAsm; asm asm_str_style outputs inputs clobbers volatile alignstack dialect); +spanless_eq_struct!(LlvmInlineAsmOutput; constraint expr is_rw is_indirect); +spanless_eq_struct!(Local; pat ty init id span attrs !tokens); +spanless_eq_struct!(MacCall; path args prior_type_ascription); +spanless_eq_struct!(MacCallStmt; mac style attrs tokens); +spanless_eq_struct!(MacroDef; body macro_rules); +spanless_eq_struct!(MutTy; ty mutbl); +spanless_eq_struct!(ParenthesizedArgs; span inputs inputs_span output); +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!(QSelf; ty path_span position); +spanless_eq_struct!(Stmt; id kind span); +spanless_eq_struct!(StrLit; style symbol suffix span symbol_unescaped); +spanless_eq_struct!(StructExpr; path fields rest); +spanless_eq_struct!(Token; kind span); +spanless_eq_struct!(TraitKind; 0 1 2 3 4); +spanless_eq_struct!(TraitRef; path ref_id); +spanless_eq_struct!(Ty; id kind span tokens); +spanless_eq_struct!(TyAliasKind; 0 1 2 3); +spanless_eq_struct!(UseTree; prefix kind span); +spanless_eq_struct!(Variant; attrs id span !vis ident data disr_expr is_placeholder); +spanless_eq_struct!(Visibility; kind span tokens); +spanless_eq_struct!(WhereBoundPredicate; span bound_generic_params bounded_ty bounds); +spanless_eq_struct!(WhereClause; has_where_token predicates span); +spanless_eq_struct!(WhereEqPredicate; id span lhs_ty rhs_ty); +spanless_eq_struct!(WhereRegionPredicate; span lifetime bounds); +spanless_eq_struct!(token::Lit; kind symbol suffix); +spanless_eq_enum!(AngleBracketedArg; Arg(0) Constraint(0)); +spanless_eq_enum!(AssocItemKind; Const(0 1 2) Fn(0) TyAlias(0) MacCall(0)); +spanless_eq_enum!(AssocTyConstraintKind; Equality(ty) Bound(bounds)); +spanless_eq_enum!(Async; Yes(span closure_id return_impl_trait_id) No); +spanless_eq_enum!(AttrStyle; Outer Inner); +spanless_eq_enum!(BinOpKind; Add Sub Mul Div Rem And Or BitXor BitAnd BitOr Shl Shr Eq Lt Le Ne Ge Gt); +spanless_eq_enum!(BindingMode; ByRef(0) ByValue(0)); +spanless_eq_enum!(BlockCheckMode; Default Unsafe(0)); +spanless_eq_enum!(BorrowKind; Ref Raw); +spanless_eq_enum!(CaptureBy; Value Ref); +spanless_eq_enum!(Const; Yes(0) No); +spanless_eq_enum!(CrateSugar; PubCrate JustCrate); +spanless_eq_enum!(Defaultness; Default(0) Final); +spanless_eq_enum!(Extern; None Implicit Explicit(0)); +spanless_eq_enum!(FloatTy; F32 F64); +spanless_eq_enum!(FnRetTy; Default(0) Ty(0)); +spanless_eq_enum!(ForeignItemKind; Static(0 1 2) Fn(0) TyAlias(0) MacCall(0)); +spanless_eq_enum!(GenericArg; Lifetime(0) Type(0) Const(0)); +spanless_eq_enum!(GenericArgs; AngleBracketed(0) Parenthesized(0)); +spanless_eq_enum!(GenericBound; Trait(0 1) Outlives(0)); +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); +spanless_eq_enum!(InlineAsmRegOrRegClass; Reg(0) RegClass(0)); +spanless_eq_enum!(InlineAsmTemplatePiece; String(0) Placeholder(operand_idx modifier span)); +spanless_eq_enum!(IntTy; Isize I8 I16 I32 I64 I128); +spanless_eq_enum!(IsAuto; Yes No); +spanless_eq_enum!(LitFloatType; Suffixed(0) Unsuffixed); +spanless_eq_enum!(LitIntType; Signed(0) Unsigned(0) Unsuffixed); +spanless_eq_enum!(LlvmAsmDialect; Att Intel); +spanless_eq_enum!(MacArgs; Empty Delimited(0 1 2) Eq(0 1)); +spanless_eq_enum!(MacDelimiter; Parenthesis Bracket Brace); +spanless_eq_enum!(MacStmtStyle; Semicolon Braces NoBraces); +spanless_eq_enum!(ModKind; Loaded(0 1 2) Unloaded); +spanless_eq_enum!(Movability; Static Movable); +spanless_eq_enum!(Mutability; Mut Not); +spanless_eq_enum!(RangeEnd; Included(0) Excluded); +spanless_eq_enum!(RangeLimits; HalfOpen Closed); +spanless_eq_enum!(StmtKind; Local(0) Item(0) Expr(0) Semi(0) Empty MacCall(0)); +spanless_eq_enum!(StrStyle; Cooked Raw(0)); +spanless_eq_enum!(StructRest; Base(0) Rest(0) None); +spanless_eq_enum!(TokenTree; Token(0) Delimited(0 1 2)); +spanless_eq_enum!(TraitBoundModifier; None Maybe MaybeConst MaybeConstMaybe); +spanless_eq_enum!(TraitObjectSyntax; Dyn None); +spanless_eq_enum!(UintTy; Usize U8 U16 U32 U64 U128); +spanless_eq_enum!(UnOp; Deref Not Neg); +spanless_eq_enum!(Unsafe; Yes(0) No); +spanless_eq_enum!(UnsafeSource; CompilerGenerated UserProvided); +spanless_eq_enum!(UseTreeKind; Simple(0 1 2) Nested(0) Glob); +spanless_eq_enum!(VariantData; Struct(0 1) Tuple(0 1) Unit(0)); +spanless_eq_enum!(VisibilityKind; Public Crate(0) Restricted(path id) Inherited); +spanless_eq_enum!(WherePredicate; BoundPredicate(0) RegionPredicate(0) EqPredicate(0)); +spanless_eq_enum!(ExprKind; Box(0) Array(0) ConstBlock(0) Call(0 1) + MethodCall(0 1 2) Tup(0) Binary(0 1 2) Unary(0 1) Lit(0) Cast(0 1) Type(0 1) + Let(0 1) If(0 1 2) While(0 1 2) ForLoop(0 1 2 3) Loop(0 1) Match(0 1) + Closure(0 1 2 3 4 5) Block(0 1) Async(0 1 2) Await(0) TryBlock(0) + Assign(0 1 2) AssignOp(0 1 2) Field(0 1) Index(0 1) Underscore Range(0 1 2) + Path(0 1) AddrOf(0 1 2) Break(0 1) Continue(0) Ret(0) InlineAsm(0) + LlvmInlineAsm(0) MacCall(0) Struct(0) Repeat(0 1) Paren(0) Try(0) Yield(0) + Err); +spanless_eq_enum!(InlineAsmOperand; In(reg expr) Out(reg late expr) + InOut(reg late expr) SplitInOut(reg late in_expr out_expr) Const(anon_const) + Sym(expr)); +spanless_eq_enum!(ItemKind; ExternCrate(0) Use(0) Static(0 1 2) Const(0 1 2) + Fn(0) Mod(0 1) ForeignMod(0) GlobalAsm(0) TyAlias(0) Enum(0 1) Struct(0 1) + Union(0 1) Trait(0) TraitAlias(0 1) Impl(0) MacCall(0) MacroDef(0)); +spanless_eq_enum!(LitKind; Str(0 1) ByteStr(0) Byte(0) Char(0) Int(0 1) + Float(0 1) Bool(0) Err(0)); +spanless_eq_enum!(PatKind; Wild Ident(0 1 2) Struct(0 1 2) TupleStruct(0 1) + Or(0) Path(0 1) Tuple(0) Box(0) Ref(0 1) Lit(0) Range(0 1 2) Slice(0) Rest + Paren(0) MacCall(0)); +spanless_eq_enum!(TyKind; Slice(0) Array(0 1) Ptr(0) Rptr(0 1) BareFn(0) Never + Tup(0) Path(0 1) TraitObject(0 1) ImplTrait(0 1) Paren(0) Typeof(0) Infer + ImplicitSelf MacCall(0) Err CVarArgs); + +impl SpanlessEq for Ident { + fn eq(&self, other: &Self) -> bool { + self.as_str() == other.as_str() + } +} + +impl SpanlessEq for RangeSyntax { + fn eq(&self, _other: &Self) -> bool { + match self { + RangeSyntax::DotDotDot | RangeSyntax::DotDotEq => true, + } + } +} + +impl SpanlessEq for Param { + fn eq(&self, other: &Self) -> bool { + let Param { + attrs, + ty, + pat, + id, + span: _, + is_placeholder, + } = self; + let Param { + attrs: attrs2, + ty: ty2, + pat: pat2, + id: id2, + span: _, + is_placeholder: is_placeholder2, + } = other; + SpanlessEq::eq(id, id2) + && SpanlessEq::eq(is_placeholder, is_placeholder2) + && (matches!(ty.kind, TyKind::Err) + || matches!(ty2.kind, TyKind::Err) + || SpanlessEq::eq(attrs, attrs2) + && SpanlessEq::eq(ty, ty2) + && SpanlessEq::eq(pat, pat2)) + } +} + +impl SpanlessEq for TokenKind { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (TokenKind::Literal(this), TokenKind::Literal(other)) => SpanlessEq::eq(this, other), + (TokenKind::DotDotEq, _) | (TokenKind::DotDotDot, _) => match other { + TokenKind::DotDotEq | TokenKind::DotDotDot => true, + _ => false, + }, + (TokenKind::Interpolated(this), TokenKind::Interpolated(other)) => { + match (this.as_ref(), other.as_ref()) { + (Nonterminal::NtExpr(this), Nonterminal::NtExpr(other)) => { + SpanlessEq::eq(this, other) + } + _ => this == other, + } + } + _ => self == other, + } + } +} + +impl SpanlessEq for TokenStream { + fn eq(&self, other: &Self) -> bool { + let mut this_trees = self.trees(); + let mut other_trees = other.trees(); + loop { + let this = match this_trees.next() { + None => return other_trees.next().is_none(), + Some(tree) => tree, + }; + let other = match other_trees.next() { + None => return false, + Some(tree) => tree, + }; + if SpanlessEq::eq(&this, &other) { + continue; + } + if let (TokenTree::Token(this), TokenTree::Token(other)) = (this, other) { + if match (&this.kind, &other.kind) { + (TokenKind::Literal(this), TokenKind::Literal(other)) => { + SpanlessEq::eq(this, other) + } + (TokenKind::DocComment(_kind, style, symbol), TokenKind::Pound) => { + doc_comment(*style, *symbol, &mut other_trees) + } + (TokenKind::Pound, TokenKind::DocComment(_kind, style, symbol)) => { + doc_comment(*style, *symbol, &mut this_trees) + } + _ => false, + } { + continue; + } + } + return false; + } + } +} + +fn doc_comment<'a>( + style: AttrStyle, + unescaped: Symbol, + trees: &mut impl Iterator<Item = TokenTree>, +) -> bool { + if match style { + AttrStyle::Outer => false, + AttrStyle::Inner => true, + } { + match trees.next() { + Some(TokenTree::Token(Token { + kind: TokenKind::Not, + span: _, + })) => {} + _ => return false, + } + } + let stream = match trees.next() { + Some(TokenTree::Delimited(_span, DelimToken::Bracket, stream)) => stream, + _ => return false, + }; + let mut trees = stream.trees(); + match trees.next() { + Some(TokenTree::Token(Token { + kind: TokenKind::Ident(symbol, false), + span: _, + })) if symbol == sym::doc => {} + _ => return false, + } + match trees.next() { + Some(TokenTree::Token(Token { + kind: TokenKind::Eq, + span: _, + })) => {} + _ => return false, + } + match trees.next() { + Some(TokenTree::Token(token)) => { + is_escaped_literal(&token, unescaped) && trees.next().is_none() + } + _ => false, + } +} + +fn is_escaped_literal(token: &Token, unescaped: Symbol) -> bool { + match match token { + Token { + kind: TokenKind::Literal(lit), + span: _, + } => Lit::from_lit_token(*lit, DUMMY_SP), + Token { + kind: TokenKind::Interpolated(nonterminal), + span: _, + } => match nonterminal.as_ref() { + Nonterminal::NtExpr(expr) => match &expr.kind { + ExprKind::Lit(lit) => Ok(lit.clone()), + _ => return false, + }, + _ => return false, + }, + _ => return false, + } { + Ok(Lit { + token: + token::Lit { + kind: token::LitKind::Str, + symbol: _, + suffix: None, + }, + kind: LitKind::Str(symbol, StrStyle::Cooked), + span: _, + }) => symbol.as_str().replace('\r', "") == unescaped.as_str().replace('\r', ""), + _ => false, + } +} + +impl SpanlessEq for LazyTokenStream { + fn eq(&self, other: &Self) -> bool { + let this = self.create_token_stream(); + let other = other.create_token_stream(); + SpanlessEq::eq(&this, &other) + } +} + +impl SpanlessEq for AttrKind { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (AttrKind::Normal(item, tokens), AttrKind::Normal(item2, tokens2)) => { + SpanlessEq::eq(item, item2) && SpanlessEq::eq(tokens, tokens2) + } + (AttrKind::DocComment(kind, symbol), AttrKind::DocComment(kind2, symbol2)) => { + SpanlessEq::eq(kind, kind2) && SpanlessEq::eq(symbol, symbol2) + } + (AttrKind::DocComment(kind, unescaped), AttrKind::Normal(item2, _tokens)) => { + match kind { + CommentKind::Line | CommentKind::Block => {} + } + let path = Path::from_ident(Ident::with_dummy_span(sym::doc)); + SpanlessEq::eq(&path, &item2.path) + && match &item2.args { + MacArgs::Empty | MacArgs::Delimited(..) => false, + MacArgs::Eq(_span, token) => is_escaped_literal(token, *unescaped), + } + } + (AttrKind::Normal(..), AttrKind::DocComment(..)) => SpanlessEq::eq(other, self), + } + } +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 00000000..a1cc80a1 --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,27 @@ +#![allow(dead_code)] + +use rayon::ThreadPoolBuilder; +use std::env; + +pub mod eq; +pub mod parse; + +/// Read the `ABORT_AFTER_FAILURE` environment variable, and parse it. +pub fn abort_after() -> usize { + match env::var("ABORT_AFTER_FAILURE") { + Ok(s) => s.parse().expect("failed to parse ABORT_AFTER_FAILURE"), + Err(_) => usize::max_value(), + } +} + +/// Configure Rayon threadpool. +pub fn rayon_init() { + let stack_size = match env::var("RUST_MIN_STACK") { + Ok(s) => s.parse().expect("failed to parse RUST_MIN_STACK"), + Err(_) => 20 * 1024 * 1024, + }; + ThreadPoolBuilder::new() + .stack_size(stack_size) + .build_global() + .unwrap(); +} diff --git a/1.0.7/tests/common/parse.rs b/tests/common/parse.rs index e6425b78..636d0a37 100644 --- a/1.0.7/tests/common/parse.rs +++ b/tests/common/parse.rs @@ -1,19 +1,19 @@ -extern crate syntax; -extern crate syntax_pos; - -use syntax::ast; -use syntax::parse; -use syntax::ptr::P; -use syntax::sess::ParseSess; -use syntax::source_map::FilePathMapping; -use syntax_pos::FileName; +extern crate rustc_ast; +extern crate rustc_expand; +extern crate rustc_parse as parse; +extern crate rustc_session; +extern crate rustc_span; +use rustc_ast::ast; +use rustc_ast::ptr::P; +use rustc_session::parse::ParseSess; +use rustc_span::source_map::FilePathMapping; +use rustc_span::FileName; use std::panic; -pub fn libsyntax_expr(input: &str) -> Option<P<ast::Expr>> { +pub fn librustc_expr(input: &str) -> Option<P<ast::Expr>> { match panic::catch_unwind(|| { let sess = ParseSess::new(FilePathMapping::empty()); - sess.span_diagnostic.set_continue_after_error(false); let e = parse::new_parser_from_source_str( &sess, FileName::Custom("test_precedence".to_string()), @@ -31,7 +31,7 @@ pub fn libsyntax_expr(input: &str) -> Option<P<ast::Expr>> { Ok(Some(e)) => Some(e), Ok(None) => None, Err(_) => { - errorf!("libsyntax panicked\n"); + errorf!("librustc panicked\n"); None } } diff --git a/1.0.7/tests/debug/gen.rs b/tests/debug/gen.rs index 8450c09e..1eae327b 100644 --- a/1.0.7/tests/debug/gen.rs +++ b/tests/debug/gen.rs @@ -2,7 +2,7 @@ // It is not intended for manual editing. use super::{Lite, RefCast}; -use std::fmt::{self, Debug}; +use std::fmt::{self, Debug, Display}; impl Debug for Lite<syn::Abi> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let _val = &self.value; @@ -1039,9 +1039,9 @@ impl Debug for Lite<syn::Expr> { } syn::Expr::Verbatim(_val) => { formatter.write_str("Verbatim")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; + formatter.write_str("(`")?; + Display::fmt(_val, formatter)?; + formatter.write_str("`)")?; Ok(()) } syn::Expr::While(_val) => { @@ -2116,9 +2116,9 @@ impl Debug for Lite<syn::ForeignItem> { } syn::ForeignItem::Verbatim(_val) => { formatter.write_str("Verbatim")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; + formatter.write_str("(`")?; + Display::fmt(_val, formatter)?; + formatter.write_str("`)")?; Ok(()) } _ => unreachable!(), @@ -2432,9 +2432,9 @@ impl Debug for Lite<syn::ImplItem> { } syn::ImplItem::Verbatim(_val) => { formatter.write_str("Verbatim")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; + formatter.write_str("(`")?; + Display::fmt(_val, formatter)?; + formatter.write_str("`)")?; Ok(()) } _ => unreachable!(), @@ -2940,9 +2940,9 @@ impl Debug for Lite<syn::Item> { } syn::Item::Verbatim(_val) => { formatter.write_str("Verbatim")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; + formatter.write_str("(`")?; + Display::fmt(_val, formatter)?; + formatter.write_str("`)")?; Ok(()) } _ => unreachable!(), @@ -3424,12 +3424,24 @@ impl Debug for Lite<syn::Lit> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let _val = &self.value; match _val { - syn::Lit::Str(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::ByteStr(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::Byte(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::Char(_val) => write!(formatter, "{:?}", _val.value()), - syn::Lit::Int(_val) => write!(formatter, "{}", _val), - syn::Lit::Float(_val) => write!(formatter, "{}", _val), + syn::Lit::Str(_val) => { + write!(formatter, "{:?}", _val.value()) + } + syn::Lit::ByteStr(_val) => { + write!(formatter, "{:?}", _val.value()) + } + syn::Lit::Byte(_val) => { + write!(formatter, "{:?}", _val.value()) + } + syn::Lit::Char(_val) => { + write!(formatter, "{:?}", _val.value()) + } + syn::Lit::Int(_val) => { + write!(formatter, "{}", _val) + } + syn::Lit::Float(_val) => { + write!(formatter, "{}", _val) + } syn::Lit::Bool(_val) => { let mut formatter = formatter.debug_struct("Lit::Bool"); formatter.field("value", Lite(&_val.value)); @@ -3437,9 +3449,9 @@ impl Debug for Lite<syn::Lit> { } syn::Lit::Verbatim(_val) => { formatter.write_str("Verbatim")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; + formatter.write_str("(`")?; + Display::fmt(_val, formatter)?; + formatter.write_str("`)")?; Ok(()) } } @@ -3878,9 +3890,9 @@ impl Debug for Lite<syn::Pat> { } syn::Pat::Verbatim(_val) => { formatter.write_str("Verbatim")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; + formatter.write_str("(`")?; + Display::fmt(_val, formatter)?; + formatter.write_str("`)")?; Ok(()) } syn::Pat::Wild(_val) => { @@ -4674,9 +4686,9 @@ impl Debug for Lite<syn::TraitItem> { } syn::TraitItem::Verbatim(_val) => { formatter.write_str("Verbatim")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; + formatter.write_str("(`")?; + Display::fmt(_val, formatter)?; + formatter.write_str("`)")?; Ok(()) } _ => unreachable!(), @@ -5040,9 +5052,9 @@ impl Debug for Lite<syn::Type> { } syn::Type::Verbatim(_val) => { formatter.write_str("Verbatim")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; + formatter.write_str("(`")?; + Display::fmt(_val, formatter)?; + formatter.write_str("`)")?; Ok(()) } _ => unreachable!(), diff --git a/1.0.7/tests/debug/mod.rs b/tests/debug/mod.rs index 9c80e2c8..cefebace 100644 --- a/1.0.7/tests/debug/mod.rs +++ b/tests/debug/mod.rs @@ -63,7 +63,15 @@ impl Debug for Lite<Literal> { impl Debug for Lite<TokenStream> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "`{}`", self.value) + let string = self.value.to_string(); + if string.len() <= 80 { + write!(formatter, "TokenStream(`{}`)", self.value) + } else { + formatter + .debug_tuple("TokenStream") + .field(&format_args!("`{}`", string)) + .finish() + } } } diff --git a/1.0.7/tests/macros/mod.rs b/tests/macros/mod.rs index 3994615f..db90818e 100644 --- a/1.0.7/tests/macros/mod.rs +++ b/tests/macros/mod.rs @@ -1,7 +1,6 @@ #[path = "../debug/mod.rs"] pub mod debug; -use syn; use syn::parse::{Parse, Result}; #[macro_export] diff --git a/tests/repo/mod.rs b/tests/repo/mod.rs new file mode 100644 index 00000000..24b620c5 --- /dev/null +++ b/tests/repo/mod.rs @@ -0,0 +1,130 @@ +mod progress; + +use self::progress::Progress; +use anyhow::Result; +use flate2::read::GzDecoder; +use std::fs; +use std::path::Path; +use tar::Archive; +use walkdir::DirEntry; + +const REVISION: &str = "52e3dffa50cfffdcfa145c0cc0ba48b49abc0c07"; + +#[rustfmt::skip] +static EXCLUDE: &[&str] = &[ + // Compile-fail expr parameter in const generic position: f::<1 + 2>() + "src/test/ui/const-generics/closing-args-token.rs", + "src/test/ui/const-generics/const-expression-parameter.rs", + + // Deprecated anonymous parameter syntax in traits + "src/test/ui/issues/issue-13105.rs", + "src/test/ui/issues/issue-13775.rs", + "src/test/ui/issues/issue-34074.rs", + "src/test/ui/proc-macro/trait-fn-args-2015.rs", + + // Not actually test cases + "src/test/rustdoc-ui/test-compile-fail2.rs", + "src/test/rustdoc-ui/test-compile-fail3.rs", + "src/test/ui/include-single-expr-helper.rs", + "src/test/ui/include-single-expr-helper-1.rs", + "src/test/ui/json-bom-plus-crlf-multifile-aux.rs", + "src/test/ui/lint/expansion-time-include.rs", + "src/test/ui/macros/auxiliary/macro-comma-support.rs", + "src/test/ui/macros/auxiliary/macro-include-items-expr.rs", + "src/test/ui/parser/auxiliary/issue-21146-inc.rs", +]; + +pub fn base_dir_filter(entry: &DirEntry) -> bool { + let path = entry.path(); + if path.is_dir() { + return true; // otherwise walkdir does not visit the files + } + if path.extension().map(|e| e != "rs").unwrap_or(true) { + return false; + } + + let mut path_string = path.to_string_lossy(); + if cfg!(windows) { + path_string = path_string.replace('\\', "/").into(); + } + let path = if let Some(path) = path_string.strip_prefix("tests/rust/") { + path + } else { + panic!("unexpected path in Rust dist: {}", path_string); + }; + + if path.starts_with("src/test/compile-fail") || path.starts_with("src/test/rustfix") { + return false; + } + + if path.starts_with("src/test/ui") { + let stderr_path = entry.path().with_extension("stderr"); + if stderr_path.exists() { + // Expected to fail in some way + return false; + } + } + + !EXCLUDE.contains(&path) +} + +#[allow(dead_code)] +pub fn edition(path: &Path) -> &'static str { + if path.ends_with("dyn-2015-no-warnings-without-lints.rs") { + "2015" + } else { + "2018" + } +} + +pub fn clone_rust() { + let needs_clone = match fs::read_to_string("tests/rust/COMMIT") { + Err(_) => true, + Ok(contents) => contents.trim() != REVISION, + }; + if needs_clone { + download_and_unpack().unwrap(); + } + let mut missing = String::new(); + let test_src = Path::new("tests/rust"); + for exclude in EXCLUDE { + if !test_src.join(exclude).exists() { + missing += "\ntests/rust/"; + missing += exclude; + } + } + if !missing.is_empty() { + panic!("excluded test file does not exist:{}\n", missing); + } +} + +fn download_and_unpack() -> Result<()> { + let url = format!( + "https://github.com/rust-lang/rust/archive/{}.tar.gz", + REVISION + ); + let response = reqwest::blocking::get(&url)?.error_for_status()?; + let progress = Progress::new(response); + let decoder = GzDecoder::new(progress); + let mut archive = Archive::new(decoder); + let prefix = format!("rust-{}", REVISION); + + let tests_rust = Path::new("tests/rust"); + if tests_rust.exists() { + fs::remove_dir_all(tests_rust)?; + } + + for entry in archive.entries()? { + let mut entry = entry?; + let path = entry.path()?; + if path == Path::new("pax_global_header") { + continue; + } + let relative = path.strip_prefix(&prefix)?; + let out = tests_rust.join(relative); + entry.unpack(&out)?; + } + + fs::write("tests/rust/COMMIT", REVISION)?; + Ok(()) +} diff --git a/tests/repo/progress.rs b/tests/repo/progress.rs new file mode 100644 index 00000000..28c8a44b --- /dev/null +++ b/tests/repo/progress.rs @@ -0,0 +1,37 @@ +use std::io::{Read, Result}; +use std::time::{Duration, Instant}; + +pub struct Progress<R> { + bytes: usize, + tick: Instant, + stream: R, +} + +impl<R> Progress<R> { + pub fn new(stream: R) -> Self { + Progress { + bytes: 0, + tick: Instant::now() + Duration::from_millis(2000), + stream, + } + } +} + +impl<R: Read> Read for Progress<R> { + fn read(&mut self, buf: &mut [u8]) -> Result<usize> { + let num = self.stream.read(buf)?; + self.bytes += num; + let now = Instant::now(); + if now > self.tick { + self.tick = now + Duration::from_millis(500); + errorf!("downloading... {} bytes\n", self.bytes); + } + Ok(num) + } +} + +impl<R> Drop for Progress<R> { + fn drop(&mut self) { + errorf!("done ({} bytes)\n", self.bytes); + } +} diff --git a/1.0.7/tests/test_asyncness.rs b/tests/test_asyncness.rs index e09e816d..0efef597 100644 --- a/1.0.7/tests/test_asyncness.rs +++ b/tests/test_asyncness.rs @@ -1,5 +1,3 @@ -mod features; - #[macro_use] mod macros; diff --git a/1.0.7/tests/test_attribute.rs b/tests/test_attribute.rs index d77c0c09..c26bd090 100644 --- a/1.0.7/tests/test_attribute.rs +++ b/tests/test_attribute.rs @@ -1,5 +1,3 @@ -mod features; - #[macro_use] mod macros; @@ -286,6 +284,48 @@ fn test_bool_lit() { "###); } +#[test] +fn test_negative_lit() { + let meta = test("#[form(min = -1, max = 200)]"); + + snapshot!(meta, @r###" + Meta::List { + path: Path { + segments: [ + PathSegment { + ident: "form", + arguments: None, + }, + ], + }, + nested: [ + Meta(Meta::NameValue { + path: Path { + segments: [ + PathSegment { + ident: "min", + arguments: None, + }, + ], + }, + lit: -1, + }), + Meta(Meta::NameValue { + path: Path { + segments: [ + PathSegment { + ident: "max", + arguments: None, + }, + ], + }, + lit: 200, + }), + ], + } + "###); +} + fn test(input: &str) -> Meta { let attrs = Attribute::parse_outer.parse_str(input).unwrap(); diff --git a/1.0.7/tests/test_derive_input.rs b/tests/test_derive_input.rs index e3685aea..bf1ebdb6 100644 --- a/1.0.7/tests/test_derive_input.rs +++ b/tests/test_derive_input.rs @@ -1,5 +1,3 @@ -mod features; - #[macro_use] mod macros; @@ -48,7 +46,7 @@ fn test_struct() { }, ], }, - tokens: `( Debug , Clone )`, + tokens: TokenStream(`(Debug , Clone)`), }, ], vis: Visibility::Public, @@ -221,7 +219,7 @@ fn test_enum() { }, ], }, - tokens: `= r" See the std::result module documentation for details."`, + tokens: TokenStream(`= r" See the std::result module documentation for details."`), }, Attribute { style: Outer, @@ -233,7 +231,7 @@ fn test_enum() { }, ], }, - tokens: ``, + tokens: TokenStream(``), }, ], vis: Visibility::Public, @@ -380,7 +378,7 @@ fn test_attr_with_path() { }, ], }, - tokens: `fn main ( ) { assert_eq ! ( foo ( ) , "Hello, world!" ) ; }`, + tokens: TokenStream(`fn main () { assert_eq ! (foo () , "Hello, world!") ; }`), }, ], vis: Inherited, @@ -416,7 +414,7 @@ fn test_attr_with_non_mod_style_path() { }, ], }, - tokens: `< T >`, + tokens: TokenStream(`< T >`), }, ], vis: Inherited, @@ -456,7 +454,7 @@ fn test_attr_with_mod_style_path_with_self() { }, ], }, - tokens: ``, + tokens: TokenStream(``), }, ], vis: Inherited, diff --git a/tests/test_expr.rs b/tests/test_expr.rs new file mode 100644 index 00000000..b2b65a25 --- /dev/null +++ b/tests/test_expr.rs @@ -0,0 +1,302 @@ +#[macro_use] +mod macros; + +use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree}; +use quote::quote; +use std::iter::FromIterator; +use syn::{Expr, ExprRange}; + +#[test] +fn test_expr_parse() { + let tokens = quote!(..100u32); + snapshot!(tokens as Expr, @r###" + Expr::Range { + limits: HalfOpen, + to: Some(Expr::Lit { + lit: 100u32, + }), + } + "###); + + let tokens = quote!(..100u32); + snapshot!(tokens as ExprRange, @r###" + ExprRange { + limits: HalfOpen, + to: Some(Expr::Lit { + lit: 100u32, + }), + } + "###); +} + +#[test] +fn test_await() { + // Must not parse as Expr::Field. + let tokens = quote!(fut.await); + + snapshot!(tokens as Expr, @r###" + Expr::Await { + base: Expr::Path { + path: Path { + segments: [ + PathSegment { + ident: "fut", + arguments: None, + }, + ], + }, + }, + } + "###); +} + +#[rustfmt::skip] +#[test] +fn test_tuple_multi_index() { + for &input in &[ + "tuple.0.0", + "tuple .0.0", + "tuple. 0.0", + "tuple.0 .0", + "tuple.0. 0", + "tuple . 0 . 0", + ] { + snapshot!(input as Expr, @r###" + Expr::Field { + base: Expr::Field { + base: Expr::Path { + path: Path { + segments: [ + PathSegment { + ident: "tuple", + arguments: None, + }, + ], + }, + }, + member: Unnamed(Index { + index: 0, + }), + }, + member: Unnamed(Index { + index: 0, + }), + } + "###); + } + + for tokens in vec![ + quote!(tuple.0.0), + quote!(tuple .0.0), + quote!(tuple. 0.0), + quote!(tuple.0 .0), + quote!(tuple.0. 0), + quote!(tuple . 0 . 0), + ] { + snapshot!(tokens as Expr, @r###" + Expr::Field { + base: Expr::Field { + base: Expr::Path { + path: Path { + segments: [ + PathSegment { + ident: "tuple", + arguments: None, + }, + ], + }, + }, + member: Unnamed(Index { + index: 0, + }), + }, + member: Unnamed(Index { + index: 0, + }), + } + "###); + } +} + +#[test] +fn test_macro_variable_func() { + // mimics the token stream corresponding to `$fn()` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, quote! { f })), + TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::new())), + ]); + + snapshot!(tokens as Expr, @r###" + Expr::Call { + func: Expr::Group { + expr: Expr::Path { + path: Path { + segments: [ + PathSegment { + ident: "f", + arguments: None, + }, + ], + }, + }, + }, + } + "###); + + let tokens = TokenStream::from_iter(vec![ + TokenTree::Punct(Punct::new('#', Spacing::Alone)), + TokenTree::Group(Group::new(Delimiter::Bracket, quote! { outside })), + TokenTree::Group(Group::new(Delimiter::None, quote! { #[inside] f })), + TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::new())), + ]); + + snapshot!(tokens as Expr, @r###" + Expr::Call { + attrs: [ + Attribute { + style: Outer, + path: Path { + segments: [ + PathSegment { + ident: "outside", + arguments: None, + }, + ], + }, + tokens: TokenStream(``), + }, + ], + func: Expr::Group { + expr: Expr::Path { + attrs: [ + Attribute { + style: Outer, + path: Path { + segments: [ + PathSegment { + ident: "inside", + arguments: None, + }, + ], + }, + tokens: TokenStream(``), + }, + ], + path: Path { + segments: [ + PathSegment { + ident: "f", + arguments: None, + }, + ], + }, + }, + }, + } + "###); +} + +#[test] +fn test_macro_variable_macro() { + // mimics the token stream corresponding to `$macro!()` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, quote! { m })), + TokenTree::Punct(Punct::new('!', Spacing::Alone)), + TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::new())), + ]); + + snapshot!(tokens as Expr, @r###" + Expr::Macro { + mac: Macro { + path: Path { + segments: [ + PathSegment { + ident: "m", + arguments: None, + }, + ], + }, + delimiter: Paren, + tokens: TokenStream(``), + }, + } + "###); +} + +#[test] +fn test_macro_variable_struct() { + // mimics the token stream corresponding to `$struct {}` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, quote! { S })), + TokenTree::Group(Group::new(Delimiter::Brace, TokenStream::new())), + ]); + + snapshot!(tokens as Expr, @r###" + Expr::Struct { + path: Path { + segments: [ + PathSegment { + ident: "S", + arguments: None, + }, + ], + }, + } + "###); +} + +#[test] +fn test_macro_variable_match_arm() { + // mimics the token stream corresponding to `match v { _ => $expr }` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("match", Span::call_site())), + TokenTree::Ident(Ident::new("v", Span::call_site())), + TokenTree::Group(Group::new( + Delimiter::Brace, + TokenStream::from_iter(vec![ + TokenTree::Punct(Punct::new('_', Spacing::Alone)), + TokenTree::Punct(Punct::new('=', Spacing::Joint)), + TokenTree::Punct(Punct::new('>', Spacing::Alone)), + TokenTree::Group(Group::new(Delimiter::None, quote! { #[a] () })), + ]), + )), + ]); + + snapshot!(tokens as Expr, @r###" + Expr::Match { + expr: Expr::Path { + path: Path { + segments: [ + PathSegment { + ident: "v", + arguments: None, + }, + ], + }, + }, + arms: [ + Arm { + pat: Pat::Wild, + body: Expr::Group { + expr: Expr::Tuple { + attrs: [ + Attribute { + style: Outer, + path: Path { + segments: [ + PathSegment { + ident: "a", + arguments: None, + }, + ], + }, + tokens: TokenStream(``), + }, + ], + }, + }, + }, + ], + } + "###); +} diff --git a/1.0.7/tests/test_generics.rs b/tests/test_generics.rs index e863b779..b29434a1 100644 --- a/1.0.7/tests/test_generics.rs +++ b/tests/test_generics.rs @@ -1,5 +1,3 @@ -mod features; - #[macro_use] mod macros; @@ -47,7 +45,7 @@ fn test_split_for_impl() { }, ], }, - tokens: ``, + tokens: TokenStream(``), }, ], ident: "T", @@ -267,7 +265,7 @@ fn test_fn_precedence_in_where_clause() { assert_eq!(predicate.bounds.len(), 2, "{:#?}", predicate.bounds); let first_bound = &predicate.bounds[0]; - assert_eq!(quote!(#first_bound).to_string(), "FnOnce ( ) -> i32"); + assert_eq!(quote!(#first_bound).to_string(), "FnOnce () -> i32"); let second_bound = &predicate.bounds[1]; assert_eq!(quote!(#second_bound).to_string(), "Send"); diff --git a/1.0.7/tests/test_grouping.rs b/tests/test_grouping.rs index 4e43ab8a..9eb7eee9 100644 --- a/1.0.7/tests/test_grouping.rs +++ b/tests/test_grouping.rs @@ -1,12 +1,9 @@ -mod features; - #[macro_use] mod macros; use proc_macro2::{Delimiter, Group, Literal, Punct, Spacing, TokenStream, TokenTree}; -use syn::Expr; - use std::iter::FromIterator; +use syn::Expr; #[test] fn test_grouping() { @@ -25,7 +22,7 @@ fn test_grouping() { TokenTree::Literal(Literal::i32_suffixed(4)), ]); - assert_eq!(tokens.to_string(), "1i32 + 2i32 + 3i32 * 4i32"); + assert_eq!(tokens.to_string(), "1i32 + 2i32 + 3i32 * 4i32"); snapshot!(tokens as Expr, @r###" Expr::Binary { diff --git a/1.0.7/tests/test_ident.rs b/tests/test_ident.rs index 7578381e..ee01bfcc 100644 --- a/1.0.7/tests/test_ident.rs +++ b/tests/test_ident.rs @@ -1,5 +1,3 @@ -mod features; - use proc_macro2::{Ident, Span, TokenStream}; use std::str::FromStr; use syn::Result; diff --git a/tests/test_item.rs b/tests/test_item.rs new file mode 100644 index 00000000..712c6c6f --- /dev/null +++ b/tests/test_item.rs @@ -0,0 +1,268 @@ +#[macro_use] +mod macros; + +use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; +use quote::quote; +use std::iter::FromIterator; +use syn::{Item, ItemTrait}; + +#[test] +fn test_macro_variable_attr() { + // mimics the token stream corresponding to `$attr fn f() {}` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, quote! { #[test] })), + TokenTree::Ident(Ident::new("fn", Span::call_site())), + TokenTree::Ident(Ident::new("f", Span::call_site())), + TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::new())), + TokenTree::Group(Group::new(Delimiter::Brace, TokenStream::new())), + ]); + + snapshot!(tokens as Item, @r###" + Item::Fn { + attrs: [ + Attribute { + style: Outer, + path: Path { + segments: [ + PathSegment { + ident: "test", + arguments: None, + }, + ], + }, + tokens: TokenStream(``), + }, + ], + vis: Inherited, + sig: Signature { + ident: "f", + generics: Generics, + output: Default, + }, + block: Block, + } + "###); +} + +#[test] +fn test_negative_impl() { + // Rustc parses all of the following. + + #[cfg(any())] + impl ! {} + let tokens = quote! { + impl ! {} + }; + snapshot!(tokens as Item, @r###" + Item::Impl { + generics: Generics, + self_ty: Type::Never, + } + "###); + + #[cfg(any())] + #[rustfmt::skip] + impl !Trait {} + let tokens = quote! { + impl !Trait {} + }; + snapshot!(tokens as Item, @r###" + Item::Impl { + generics: Generics, + self_ty: Verbatim(`! Trait`), + } + "###); + + #[cfg(any())] + impl !Trait for T {} + let tokens = quote! { + impl !Trait for T {} + }; + snapshot!(tokens as Item, @r###" + Item::Impl { + generics: Generics, + trait_: Some(( + Some, + Path { + segments: [ + PathSegment { + ident: "Trait", + arguments: None, + }, + ], + }, + )), + self_ty: Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "T", + arguments: None, + }, + ], + }, + }, + } + "###); + + #[cfg(any())] + #[rustfmt::skip] + impl !! {} + let tokens = quote! { + impl !! {} + }; + snapshot!(tokens as Item, @r###" + Item::Impl { + generics: Generics, + self_ty: Verbatim(`! !`), + } + "###); +} + +#[test] +fn test_macro_variable_impl() { + // mimics the token stream corresponding to `impl $trait for $ty {}` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("impl", Span::call_site())), + TokenTree::Group(Group::new(Delimiter::None, quote!(Trait))), + TokenTree::Ident(Ident::new("for", Span::call_site())), + TokenTree::Group(Group::new(Delimiter::None, quote!(Type))), + TokenTree::Group(Group::new(Delimiter::Brace, TokenStream::new())), + ]); + + snapshot!(tokens as Item, @r###" + Item::Impl { + generics: Generics, + trait_: Some(( + None, + Path { + segments: [ + PathSegment { + ident: "Trait", + arguments: None, + }, + ], + }, + )), + self_ty: Type::Group { + elem: Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "Type", + arguments: None, + }, + ], + }, + }, + }, + } + "###); +} + +#[test] +fn test_supertraits() { + // Rustc parses all of the following. + + #[rustfmt::skip] + let tokens = quote!(trait Trait where {}); + snapshot!(tokens as ItemTrait, @r###" + ItemTrait { + vis: Inherited, + ident: "Trait", + generics: Generics { + where_clause: Some(WhereClause), + }, + } + "###); + + #[rustfmt::skip] + let tokens = quote!(trait Trait: where {}); + snapshot!(tokens as ItemTrait, @r###" + ItemTrait { + vis: Inherited, + ident: "Trait", + generics: Generics { + where_clause: Some(WhereClause), + }, + colon_token: Some, + } + "###); + + #[rustfmt::skip] + let tokens = quote!(trait Trait: Sized where {}); + snapshot!(tokens as ItemTrait, @r###" + ItemTrait { + vis: Inherited, + ident: "Trait", + generics: Generics { + where_clause: Some(WhereClause), + }, + colon_token: Some, + supertraits: [ + Trait(TraitBound { + modifier: None, + path: Path { + segments: [ + PathSegment { + ident: "Sized", + arguments: None, + }, + ], + }, + }), + ], + } + "###); + + #[rustfmt::skip] + let tokens = quote!(trait Trait: Sized + where {}); + snapshot!(tokens as ItemTrait, @r###" + ItemTrait { + vis: Inherited, + ident: "Trait", + generics: Generics { + where_clause: Some(WhereClause), + }, + colon_token: Some, + supertraits: [ + Trait(TraitBound { + modifier: None, + path: Path { + segments: [ + PathSegment { + ident: "Sized", + arguments: None, + }, + ], + }, + }), + ], + } + "###); +} + +#[test] +fn test_type_empty_bounds() { + #[rustfmt::skip] + let tokens = quote! { + trait Foo { + type Bar: ; + } + }; + + snapshot!(tokens as ItemTrait, @r###" + ItemTrait { + vis: Inherited, + ident: "Foo", + generics: Generics, + items: [ + TraitItem::Type { + ident: "Bar", + generics: Generics, + colon_token: Some, + }, + ], + } + "###); +} diff --git a/1.0.7/tests/test_iterators.rs b/tests/test_iterators.rs index f1072977..2c8359c1 100644 --- a/1.0.7/tests/test_iterators.rs +++ b/tests/test_iterators.rs @@ -1,8 +1,6 @@ use syn::punctuated::{Pair, Punctuated}; use syn::Token; -mod features; - #[macro_use] mod macros; diff --git a/1.0.7/tests/test_lit.rs b/tests/test_lit.rs index 0b300c4e..099daf10 100644 --- a/1.0.7/tests/test_lit.rs +++ b/tests/test_lit.rs @@ -1,9 +1,11 @@ -mod features; +#[macro_use] +mod macros; -use proc_macro2::{TokenStream, TokenTree}; +use proc_macro2::{Delimiter, Group, Literal, Span, TokenStream, TokenTree}; use quote::ToTokens; +use std::iter::FromIterator; use std::str::FromStr; -use syn::Lit; +use syn::{Lit, LitFloat, LitInt, LitStr}; fn lit(s: &str) -> Lit { match TokenStream::from_str(s) @@ -41,11 +43,15 @@ fn strings() { test_string("\"'\"", "'"); test_string("\"\"", ""); test_string("\"\\u{1F415}\"", "\u{1F415}"); + test_string("\"\\u{1_2__3_}\"", "\u{123}"); test_string( "\"contains\nnewlines\\\nescaped newlines\"", "contains\nnewlinesescaped newlines", ); test_string("r\"raw\nstring\\\nhere\"", "raw\nstring\\\nhere"); + test_string("\"...\"q", "..."); + test_string("r\"...\"q", "..."); + test_string("r##\"...\"##q", "..."); } #[test] @@ -75,6 +81,9 @@ fn byte_strings() { b"contains\nnewlinesescaped newlines", ); test_byte_string("br\"raw\nstring\\\nhere\"", b"raw\nstring\\\nhere"); + test_byte_string("b\"...\"q", b"..."); + test_byte_string("br\"...\"q", b"..."); + test_byte_string("br##\"...\"##q", b"..."); } #[test] @@ -96,6 +105,7 @@ fn bytes() { test_byte("b'\\t'", b'\t'); test_byte("b'\\''", b'\''); test_byte("b'\"'", b'"'); + test_byte("b'a'q", b'a'); } #[test] @@ -121,6 +131,7 @@ fn chars() { test_char("'\\''", '\''); test_char("'\"'", '"'); test_char("'\\u{1F415}'", '\u{1F415}'); + test_char("'a'q", 'a'); } #[test] @@ -141,6 +152,9 @@ fn ints() { test_int("5", 5, ""); test_int("5u32", 5, "u32"); + test_int("0E", 0, "E"); + test_int("0ECMA", 0, "ECMA"); + test_int("0o0A", 0, "A"); test_int("5_0", 50, ""); test_int("5_____0_____", 50, ""); test_int("0x7f", 127, ""); @@ -157,6 +171,7 @@ fn ints() { test_int("0x_7F__u8", 127, "u8"); test_int("0b__10__0_1i8", 9, "i8"); test_int("0o__7__________________3u32", 59, "u32"); + test_int("0e1\u{5c5}", 0, "e1\u{5c5}"); } #[test] @@ -181,4 +196,76 @@ fn floats() { test_float("5.5e12", 5.5e12, ""); test_float("1.0__3e-12", 1.03e-12, ""); test_float("1.03e+12", 1.03e12, ""); + test_float("9e99e99", 9e99, "e99"); + test_float("1e_0", 1.0, ""); + test_float("0.0ECMA", 0.0, "ECMA"); +} + +#[test] +fn negative() { + let span = Span::call_site(); + assert_eq!("-1", LitInt::new("-1", span).to_string()); + assert_eq!("-1i8", LitInt::new("-1i8", span).to_string()); + assert_eq!("-1i16", LitInt::new("-1i16", span).to_string()); + assert_eq!("-1i32", LitInt::new("-1i32", span).to_string()); + assert_eq!("-1i64", LitInt::new("-1i64", span).to_string()); + assert_eq!("-1.5", LitFloat::new("-1.5", span).to_string()); + assert_eq!("-1.5f32", LitFloat::new("-1.5f32", span).to_string()); + assert_eq!("-1.5f64", LitFloat::new("-1.5f64", span).to_string()); +} + +#[test] +fn negative_overflow() { + assert!(syn::parse_str::<LitFloat>("-1.0e99f64").is_ok()); + assert!(syn::parse_str::<LitFloat>("-1.0e999f64").is_err()); +} + +#[test] +fn suffix() { + fn get_suffix(token: &str) -> String { + let lit = syn::parse_str::<Lit>(token).unwrap(); + match lit { + Lit::Str(lit) => lit.suffix().to_owned(), + Lit::ByteStr(lit) => lit.suffix().to_owned(), + Lit::Byte(lit) => lit.suffix().to_owned(), + Lit::Char(lit) => lit.suffix().to_owned(), + Lit::Int(lit) => lit.suffix().to_owned(), + Lit::Float(lit) => lit.suffix().to_owned(), + _ => unimplemented!(), + } + } + + assert_eq!(get_suffix("\"\"s"), "s"); + assert_eq!(get_suffix("r\"\"r"), "r"); + assert_eq!(get_suffix("b\"\"b"), "b"); + assert_eq!(get_suffix("br\"\"br"), "br"); + assert_eq!(get_suffix("r#\"\"#r"), "r"); + assert_eq!(get_suffix("'c'c"), "c"); + assert_eq!(get_suffix("b'b'b"), "b"); + assert_eq!(get_suffix("1i32"), "i32"); + assert_eq!(get_suffix("1_i32"), "i32"); + assert_eq!(get_suffix("1.0f32"), "f32"); + assert_eq!(get_suffix("1.0_f32"), "f32"); +} + +#[test] +fn test_deep_group_empty() { + let tokens = TokenStream::from_iter(vec![TokenTree::Group(Group::new( + Delimiter::None, + TokenStream::from_iter(vec![TokenTree::Group(Group::new( + Delimiter::None, + TokenStream::from_iter(vec![TokenTree::Literal(Literal::string("hi"))]), + ))]), + ))]); + + snapshot!(tokens as Lit, @r#""hi""# ); +} + +#[test] +fn test_error() { + let err = syn::parse_str::<LitStr>("...").unwrap_err(); + assert_eq!("expected string literal", err.to_string()); + + let err = syn::parse_str::<LitStr>("5").unwrap_err(); + assert_eq!("expected string literal", err.to_string()); } diff --git a/1.0.7/tests/test_meta.rs b/tests/test_meta.rs index 618296e2..de6cc4da 100644 --- a/1.0.7/tests/test_meta.rs +++ b/tests/test_meta.rs @@ -1,5 +1,3 @@ -mod features; - #[macro_use] mod macros; @@ -339,3 +337,40 @@ fn test_parse_nested_meta() { }) "###); } + +#[test] +fn test_parse_path() { + let input = "::serde::Serialize"; + snapshot!(input as Meta, @r###" + Path(Path { + leading_colon: Some, + segments: [ + PathSegment { + ident: "serde", + arguments: None, + }, + PathSegment { + ident: "Serialize", + arguments: None, + }, + ], + }) + "###); + + let input = "::serde::Serialize"; + snapshot!(input as NestedMeta, @r###" + Meta(Path(Path { + leading_colon: Some, + segments: [ + PathSegment { + ident: "serde", + arguments: None, + }, + PathSegment { + ident: "Serialize", + arguments: None, + }, + ], + })) + "###); +} diff --git a/0.15.42/tests/test_parse_buffer.rs b/tests/test_parse_buffer.rs index f0949518..57a3c7c3 100644 --- a/0.15.42/tests/test_parse_buffer.rs +++ b/tests/test_parse_buffer.rs @@ -1,7 +1,7 @@ -#[macro_use] -extern crate syn; - +use proc_macro2::{Delimiter, Group, Punct, Spacing, TokenStream, TokenTree}; +use std::iter::FromIterator; use syn::parse::{discouraged::Speculative, Parse, ParseStream, Parser, Result}; +use syn::{parenthesized, Token}; #[test] #[should_panic(expected = "Fork was not derived from the advancing parse stream")] @@ -53,3 +53,38 @@ fn smuggled_speculative_cursor_into_brackets() { syn::parse_str::<BreakRules>("()").unwrap(); } + +#[test] +fn trailing_empty_none_group() { + fn parse(input: ParseStream) -> Result<()> { + input.parse::<Token![+]>()?; + + let content; + parenthesized!(content in input); + content.parse::<Token![+]>()?; + + Ok(()) + } + + // `+ ( + <Ø Ø> ) <Ø <Ø Ø> Ø>` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Punct(Punct::new('+', Spacing::Alone)), + TokenTree::Group(Group::new( + Delimiter::Parenthesis, + TokenStream::from_iter(vec![ + TokenTree::Punct(Punct::new('+', Spacing::Alone)), + TokenTree::Group(Group::new(Delimiter::None, TokenStream::new())), + ]), + )), + TokenTree::Group(Group::new(Delimiter::None, TokenStream::new())), + TokenTree::Group(Group::new( + Delimiter::None, + TokenStream::from_iter(vec![TokenTree::Group(Group::new( + Delimiter::None, + TokenStream::new(), + ))]), + )), + ]); + + parse.parse2(tokens).unwrap(); +} diff --git a/tests/test_parse_stream.rs b/tests/test_parse_stream.rs new file mode 100644 index 00000000..76bd0657 --- /dev/null +++ b/tests/test_parse_stream.rs @@ -0,0 +1,12 @@ +use syn::ext::IdentExt; +use syn::parse::ParseStream; +use syn::{Ident, Token}; + +#[test] +fn test_peek() { + let _ = |input: ParseStream| { + let _ = input.peek(Ident); + let _ = input.peek(Ident::peek_any); + let _ = input.peek(Token![::]); + }; +} diff --git a/tests/test_pat.rs b/tests/test_pat.rs new file mode 100644 index 00000000..695e4736 --- /dev/null +++ b/tests/test_pat.rs @@ -0,0 +1,67 @@ +#[macro_use] +mod macros; + +use proc_macro2::{Delimiter, Group, TokenStream, TokenTree}; +use quote::quote; +use std::iter::FromIterator; +use syn::{Item, Pat, Stmt}; + +#[test] +fn test_pat_ident() { + match syn::parse2(quote!(self)).unwrap() { + Pat::Ident(_) => (), + value => panic!("expected PatIdent, got {:?}", value), + } +} + +#[test] +fn test_pat_path() { + match syn::parse2(quote!(self::CONST)).unwrap() { + Pat::Path(_) => (), + value => panic!("expected PatPath, got {:?}", value), + } +} + +#[test] +fn test_leading_vert() { + // https://github.com/rust-lang/rust/blob/1.43.0/src/test/ui/or-patterns/remove-leading-vert.rs + + syn::parse_str::<Item>("fn f() {}").unwrap(); + syn::parse_str::<Item>("fn fun1(| A: E) {}").unwrap_err(); + syn::parse_str::<Item>("fn fun2(|| A: E) {}").unwrap_err(); + + syn::parse_str::<Stmt>("let | () = ();").unwrap(); + syn::parse_str::<Stmt>("let (| A): E;").unwrap(); + syn::parse_str::<Stmt>("let (|| A): (E);").unwrap_err(); + syn::parse_str::<Stmt>("let (| A,): (E,);").unwrap(); + syn::parse_str::<Stmt>("let [| A]: [E; 1];").unwrap(); + syn::parse_str::<Stmt>("let [|| A]: [E; 1];").unwrap_err(); + syn::parse_str::<Stmt>("let TS(| A): TS;").unwrap(); + syn::parse_str::<Stmt>("let TS(|| A): TS;").unwrap_err(); + syn::parse_str::<Stmt>("let NS { f: | A }: NS;").unwrap(); + syn::parse_str::<Stmt>("let NS { f: || A }: NS;").unwrap_err(); +} + +#[test] +fn test_group() { + let group = Group::new(Delimiter::None, quote!(Some(_))); + let tokens = TokenStream::from_iter(vec![TokenTree::Group(group)]); + + snapshot!(tokens as Pat, @r###" + Pat::TupleStruct { + path: Path { + segments: [ + PathSegment { + ident: "Some", + arguments: None, + }, + ], + }, + pat: PatTuple { + elems: [ + Pat::Wild, + ], + }, + } + "###); +} diff --git a/tests/test_path.rs b/tests/test_path.rs new file mode 100644 index 00000000..e05b52ee --- /dev/null +++ b/tests/test_path.rs @@ -0,0 +1,104 @@ +#[macro_use] +mod macros; + +use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree}; +use quote::{quote, ToTokens}; +use std::iter::FromIterator; +use syn::{parse_quote, Expr, Type, TypePath}; + +#[test] +fn parse_interpolated_leading_component() { + // mimics the token stream corresponding to `$mod::rest` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, quote! { first })), + TokenTree::Punct(Punct::new(':', Spacing::Joint)), + TokenTree::Punct(Punct::new(':', Spacing::Alone)), + TokenTree::Ident(Ident::new("rest", Span::call_site())), + ]); + + snapshot!(tokens.clone() as Expr, @r###" + Expr::Path { + path: Path { + segments: [ + PathSegment { + ident: "first", + arguments: None, + }, + PathSegment { + ident: "rest", + arguments: None, + }, + ], + }, + } + "###); + + snapshot!(tokens as Type, @r###" + Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "first", + arguments: None, + }, + PathSegment { + ident: "rest", + arguments: None, + }, + ], + }, + } + "###); +} + +#[test] +fn print_incomplete_qpath() { + // qpath with `as` token + let mut ty: TypePath = parse_quote!(<Self as A>::Q); + snapshot!(ty.to_token_stream(), @r###" + TokenStream(`< Self as A > :: Q`) + "###); + assert!(ty.path.segments.pop().is_some()); + snapshot!(ty.to_token_stream(), @r###" + TokenStream(`< Self as A > ::`) + "###); + assert!(ty.path.segments.pop().is_some()); + snapshot!(ty.to_token_stream(), @r###" + TokenStream(`< Self >`) + "###); + assert!(ty.path.segments.pop().is_none()); + + // qpath without `as` token + let mut ty: TypePath = parse_quote!(<Self>::A::B); + snapshot!(ty.to_token_stream(), @r###" + TokenStream(`< Self > :: A :: B`) + "###); + assert!(ty.path.segments.pop().is_some()); + snapshot!(ty.to_token_stream(), @r###" + TokenStream(`< Self > :: A ::`) + "###); + assert!(ty.path.segments.pop().is_some()); + snapshot!(ty.to_token_stream(), @r###" + 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`) + "###); + assert!(ty.path.segments.pop().is_some()); + snapshot!(ty.to_token_stream(), @r###" + TokenStream(`Self :: A ::`) + "###); + assert!(ty.path.segments.pop().is_some()); + snapshot!(ty.to_token_stream(), @r###" + TokenStream(`Self ::`) + "###); + assert!(ty.path.segments.pop().is_some()); + snapshot!(ty.to_token_stream(), @r###" + TokenStream(``) + "###); + assert!(ty.path.segments.pop().is_none()); +} diff --git a/1.0.7/tests/test_precedence.rs b/tests/test_precedence.rs index 582c0fda..3eb2d348 100644 --- a/1.0.7/tests/test_precedence.rs +++ b/tests/test_precedence.rs @@ -4,39 +4,32 @@ //! The tests in this module do the following: //! -//! 1. Parse a given expression in both `syn` and `libsyntax`. +//! 1. Parse a given expression in both `syn` and `librustc`. //! 2. Fold over the expression adding brackets around each subexpression (with -//! some complications - see the `syn_brackets` and `libsyntax_brackets` +//! some complications - see the `syn_brackets` and `librustc_brackets` //! methods). //! 3. Serialize the `syn` expression back into a string, and re-parse it with -//! `libsyntax`. +//! `librustc`. //! 4. Respan all of the expressions, replacing the spans with the default //! spans. //! 5. Compare the expressions with one another, if they are not equal fail. +extern crate rustc_ast; extern crate rustc_data_structures; -extern crate smallvec; -extern crate syntax; -extern crate syntax_pos; - -mod features; +extern crate rustc_span; +use crate::common::eq::SpanlessEq; +use crate::common::parse; use quote::quote; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use regex::Regex; -use smallvec::smallvec; -use syntax::ast; -use syntax::ptr::P; -use syntax_pos::edition::Edition; -use walkdir::{DirEntry, WalkDir}; - -use std::fs::File; -use std::io::Read; +use rustc_ast::ast; +use rustc_ast::ptr::P; +use rustc_span::edition::Edition; +use std::fs; use std::process; use std::sync::atomic::{AtomicUsize, Ordering}; - -use common::eq::SpanlessEq; -use common::parse; +use walkdir::{DirEntry, WalkDir}; #[macro_use] mod macros; @@ -68,7 +61,7 @@ fn test_simple_precedence() { continue; }; - let pf = match test_expressions(vec![expr]) { + let pf = match test_expressions(Edition::Edition2018, vec![expr]) { (1, 0) => "passed", (0, 1) => { failed += 1; @@ -86,8 +79,8 @@ fn test_simple_precedence() { /// Test expressions from rustc, like in `test_round_trip`. #[test] -#[cfg_attr(target_os = "windows", ignore = "requires nix .sh")] fn test_rustc_precedence() { + common::rayon_init(); repo::clone_rust(); let abort_after = common::abort_after(); if abort_after == 0 { @@ -113,24 +106,14 @@ fn test_rustc_precedence() { return; } - // Our version of `libsyntax` can't parse this tests - if path - .to_str() - .unwrap() - .ends_with("optional_comma_in_match_arm.rs") - { - return; - } - - let mut file = File::open(path).unwrap(); - let mut content = String::new(); - file.read_to_string(&mut content).unwrap(); + let content = fs::read_to_string(path).unwrap(); let content = edition_regex.replace_all(&content, "_$0"); let (l_passed, l_failed) = match syn::parse_file(&content) { Ok(file) => { + let edition = repo::edition(path).parse().unwrap(); let exprs = collect_exprs(file); - test_expressions(exprs) + test_expressions(edition, exprs) } Err(msg) => { errorf!("syn failed to parse\n{:?}\n", msg); @@ -164,36 +147,36 @@ fn test_rustc_precedence() { } } -fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) { +fn test_expressions(edition: Edition, exprs: Vec<syn::Expr>) -> (usize, usize) { let mut passed = 0; let mut failed = 0; - syntax::with_globals(Edition::Edition2018, || { + rustc_span::with_session_globals(edition, || { for expr in exprs { let raw = quote!(#expr).to_string(); - let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) { + let librustc_ast = if let Some(e) = librustc_parse_and_rewrite(&raw) { e } else { failed += 1; - errorf!("\nFAIL - libsyntax failed to parse raw\n"); + errorf!("\nFAIL - librustc failed to parse raw\n"); continue; }; let syn_expr = syn_brackets(expr); - let syn_ast = if let Some(e) = parse::libsyntax_expr("e!(#syn_expr).to_string()) { + let syn_ast = if let Some(e) = parse::librustc_expr("e!(#syn_expr).to_string()) { e } else { failed += 1; - errorf!("\nFAIL - libsyntax failed to parse bracketed\n"); + errorf!("\nFAIL - librustc failed to parse bracketed\n"); continue; }; - if SpanlessEq::eq(&syn_ast, &libsyntax_ast) { + if SpanlessEq::eq(&syn_ast, &librustc_ast) { passed += 1; } else { failed += 1; - errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast); + errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, librustc_ast); } } }); @@ -201,30 +184,82 @@ fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) { (passed, failed) } -fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> { - parse::libsyntax_expr(input).and_then(libsyntax_brackets) +fn librustc_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> { + parse::librustc_expr(input).and_then(librustc_brackets) } /// Wrap every expression which is not already wrapped in parens with parens, to /// reveal the precidence of the parsed expressions, and produce a stringified /// form of the resulting expression. /// -/// This method operates on libsyntax objects. -fn libsyntax_brackets(mut libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> { +/// This method operates on librustc objects. +fn librustc_brackets(mut librustc_expr: P<ast::Expr>) -> Option<P<ast::Expr>> { + use rustc_ast::ast::{ + Block, BorrowKind, Expr, ExprField, ExprKind, GenericArg, Pat, Stmt, StmtKind, StructExpr, + StructRest, Ty, + }; + use rustc_ast::mut_visit::{noop_visit_generic_arg, MutVisitor}; + use rustc_data_structures::map_in_place::MapInPlace; use rustc_data_structures::thin_vec::ThinVec; - use smallvec::SmallVec; + use rustc_span::DUMMY_SP; use std::mem; - use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty}; - use syntax::mut_visit::{noop_visit_expr, MutVisitor}; - use syntax_pos::DUMMY_SP; + use std::ops::DerefMut; struct BracketsVisitor { failed: bool, - }; + } + + fn flat_map_field<T: MutVisitor>(mut f: ExprField, vis: &mut T) -> Vec<ExprField> { + if f.is_shorthand { + noop_visit_expr(&mut f.expr, vis); + } else { + vis.visit_expr(&mut f.expr); + } + vec![f] + } + + fn flat_map_stmt<T: MutVisitor>(stmt: Stmt, vis: &mut T) -> Vec<Stmt> { + let kind = match stmt.kind { + // Don't wrap toplevel expressions in statements. + StmtKind::Expr(mut e) => { + noop_visit_expr(&mut e, vis); + StmtKind::Expr(e) + } + StmtKind::Semi(mut e) => { + noop_visit_expr(&mut e, vis); + StmtKind::Semi(e) + } + s => s, + }; + + vec![Stmt { kind, ..stmt }] + } + + fn noop_visit_expr<T: MutVisitor>(e: &mut Expr, vis: &mut T) { + use rustc_ast::mut_visit::{noop_visit_expr, visit_thin_attrs}; + match &mut e.kind { + ExprKind::AddrOf(BorrowKind::Raw, ..) => {} + ExprKind::Struct(expr) => { + let StructExpr { path, fields, rest } = expr.deref_mut(); + vis.visit_path(path); + fields.flat_map_in_place(|field| flat_map_field(field, vis)); + if let StructRest::Base(rest) = rest { + vis.visit_expr(rest); + } + vis.visit_id(&mut e.id); + vis.visit_span(&mut e.span); + visit_thin_attrs(&mut e.attrs, vis); + } + _ => noop_visit_expr(e, vis), + } + } impl MutVisitor for BracketsVisitor { fn visit_expr(&mut self, e: &mut P<Expr>) { - noop_visit_expr(e, self); + match e.kind { + ExprKind::ConstBlock(..) => {} + _ => noop_visit_expr(e, self), + } match e.kind { ExprKind::If(..) | ExprKind::Block(..) | ExprKind::Let(..) => {} _ => { @@ -235,6 +270,7 @@ fn libsyntax_brackets(mut libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> kind: ExprKind::Err, span: DUMMY_SP, attrs: ThinVec::new(), + tokens: None, }), ); e.kind = ExprKind::Paren(inner); @@ -242,13 +278,20 @@ fn libsyntax_brackets(mut libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> } } - fn flat_map_field(&mut self, mut f: Field) -> SmallVec<[Field; 1]> { - if f.is_shorthand { - noop_visit_expr(&mut f.expr, self); - } else { - self.visit_expr(&mut f.expr); + fn visit_generic_arg(&mut self, arg: &mut GenericArg) { + match arg { + // Don't wrap const generic arg as that's invalid syntax. + GenericArg::Const(arg) => noop_visit_expr(&mut arg.value, self), + _ => noop_visit_generic_arg(arg, self), } - SmallVec::from([f]) + } + + fn visit_block(&mut self, block: &mut P<Block>) { + self.visit_id(&mut block.id); + block + .stmts + .flat_map_in_place(|stmt| flat_map_stmt(stmt, self)); + self.visit_span(&mut block.span); } // We don't want to look at expressions that might appear in patterns or @@ -261,40 +304,14 @@ fn libsyntax_brackets(mut libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> fn visit_ty(&mut self, ty: &mut P<Ty>) { let _ = ty; } - - fn flat_map_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> { - let kind = match stmt.kind { - // Don't wrap toplevel expressions in statements. - StmtKind::Expr(mut e) => { - noop_visit_expr(&mut e, self); - StmtKind::Expr(e) - } - StmtKind::Semi(mut e) => { - noop_visit_expr(&mut e, self); - StmtKind::Semi(e) - } - s => s, - }; - - smallvec![Stmt { kind, ..stmt }] - } - - fn visit_mac(&mut self, mac: &mut Mac) { - // By default when folding over macros, libsyntax panics. This is - // because it's usually not what you want, you want to run after - // macro expansion. We do want to do that (syn doesn't do macro - // expansion), so we implement visit_mac to just return the macro - // unchanged. - let _ = mac; - } } let mut folder = BracketsVisitor { failed: false }; - folder.visit_expr(&mut libsyntax_expr); + folder.visit_expr(&mut librustc_expr); if folder.failed { None } else { - Some(libsyntax_expr) + Some(librustc_expr) } } @@ -321,6 +338,25 @@ fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr { } } + fn fold_generic_argument(&mut self, arg: GenericArgument) -> GenericArgument { + match arg { + // Don't wrap const generic arg as that's invalid syntax. + GenericArgument::Const(a) => GenericArgument::Const(fold_expr(self, a)), + _ => fold_generic_argument(self, arg), + } + } + + fn fold_generic_method_argument( + &mut self, + arg: GenericMethodArgument, + ) -> GenericMethodArgument { + match arg { + // Don't wrap const generic arg as that's invalid syntax. + GenericMethodArgument::Const(a) => GenericMethodArgument::Const(fold_expr(self, a)), + _ => fold_generic_method_argument(self, arg), + } + } + fn fold_stmt(&mut self, stmt: Stmt) -> Stmt { match stmt { // Don't wrap toplevel expressions in statements. @@ -355,7 +391,10 @@ fn collect_exprs(file: syn::File) -> Vec<syn::Expr> { struct CollectExprs(Vec<Expr>); impl Fold for CollectExprs { fn fold_expr(&mut self, expr: Expr) -> Expr { - self.0.push(expr); + match expr { + Expr::Verbatim(tokens) if tokens.is_empty() => {} + _ => self.0.push(expr), + } Expr::Tuple(ExprTuple { attrs: vec![], diff --git a/1.0.7/tests/test_receiver.rs b/tests/test_receiver.rs index 168db8f8..923df96b 100644 --- a/1.0.7/tests/test_receiver.rs +++ b/tests/test_receiver.rs @@ -1,10 +1,10 @@ -mod features; - -use syn::{FnArg, Receiver, TraitItemMethod}; +use syn::{parse_quote, FnArg, Receiver, TraitItemMethod}; #[test] fn test_by_value() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn by_value(self: Self);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn by_value(self: Self); + }; match sig.receiver() { Some(FnArg::Typed(_)) => (), value => panic!("expected FnArg::Typed, got {:?}", value), @@ -13,7 +13,9 @@ fn test_by_value() { #[test] fn test_by_mut_value() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn by_mut(mut self: Self);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn by_mut(mut self: Self); + }; match sig.receiver() { Some(FnArg::Typed(_)) => (), value => panic!("expected FnArg::Typed, got {:?}", value), @@ -22,7 +24,9 @@ fn test_by_mut_value() { #[test] fn test_by_ref() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn by_ref(self: &Self);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn by_ref(self: &Self); + }; match sig.receiver() { Some(FnArg::Typed(_)) => (), value => panic!("expected FnArg::Typed, got {:?}", value), @@ -31,7 +35,9 @@ fn test_by_ref() { #[test] fn test_by_box() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn by_box(self: Box<Self>);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn by_box(self: Box<Self>); + }; match sig.receiver() { Some(FnArg::Typed(_)) => (), value => panic!("expected FnArg::Typed, got {:?}", value), @@ -40,7 +46,9 @@ fn test_by_box() { #[test] fn test_by_pin() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn by_pin(self: Pin<Self>);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn by_pin(self: Pin<Self>); + }; match sig.receiver() { Some(FnArg::Typed(_)) => (), value => panic!("expected FnArg::Typed, got {:?}", value), @@ -49,7 +57,9 @@ fn test_by_pin() { #[test] fn test_explicit_type() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn explicit_type(self: Pin<MyType>);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn explicit_type(self: Pin<MyType>); + }; match sig.receiver() { Some(FnArg::Typed(_)) => (), value => panic!("expected FnArg::Typed, got {:?}", value), @@ -58,7 +68,9 @@ fn test_explicit_type() { #[test] fn test_value_shorthand() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn value_shorthand(self);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn value_shorthand(self); + }; match sig.receiver() { Some(FnArg::Receiver(Receiver { reference: None, @@ -71,7 +83,9 @@ fn test_value_shorthand() { #[test] fn test_mut_value_shorthand() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn mut_value_shorthand(mut self);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn mut_value_shorthand(mut self); + }; match sig.receiver() { Some(FnArg::Receiver(Receiver { reference: None, @@ -84,7 +98,9 @@ fn test_mut_value_shorthand() { #[test] fn test_ref_shorthand() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn ref_shorthand(&self);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn ref_shorthand(&self); + }; match sig.receiver() { Some(FnArg::Receiver(Receiver { reference: Some(_), @@ -97,7 +113,9 @@ fn test_ref_shorthand() { #[test] fn test_ref_mut_shorthand() { - let TraitItemMethod { sig, .. } = syn::parse_quote!(fn ref_mut_shorthand(&mut self);); + let TraitItemMethod { sig, .. } = parse_quote! { + fn ref_mut_shorthand(&mut self); + }; match sig.receiver() { Some(FnArg::Receiver(Receiver { reference: Some(_), diff --git a/tests/test_round_trip.rs b/tests/test_round_trip.rs new file mode 100644 index 00000000..e8ed3454 --- /dev/null +++ b/tests/test_round_trip.rs @@ -0,0 +1,200 @@ +#![cfg(not(syn_disable_nightly_tests))] +#![recursion_limit = "1024"] +#![feature(rustc_private)] + +extern crate rustc_ast; +extern crate rustc_errors; +extern crate rustc_expand; +extern crate rustc_parse as parse; +extern crate rustc_session; +extern crate rustc_span; + +use crate::common::eq::SpanlessEq; +use quote::quote; +use rayon::iter::{IntoParallelIterator, ParallelIterator}; +use rustc_ast::ast::{ + AngleBracketedArg, AngleBracketedArgs, Crate, GenericArg, GenericParamKind, Generics, +}; +use rustc_ast::mut_visit::{self, MutVisitor}; +use rustc_errors::PResult; +use rustc_session::parse::ParseSess; +use rustc_span::source_map::FilePathMapping; +use rustc_span::FileName; +use std::fs; +use std::panic; +use std::path::Path; +use std::process; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; +use walkdir::{DirEntry, WalkDir}; + +#[macro_use] +mod macros; + +#[allow(dead_code)] +mod common; + +mod repo; + +#[test] +fn test_round_trip() { + common::rayon_init(); + repo::clone_rust(); + let abort_after = common::abort_after(); + if abort_after == 0 { + panic!("Skipping all round_trip tests"); + } + + let failed = AtomicUsize::new(0); + + WalkDir::new("tests/rust") + .sort_by(|a, b| a.file_name().cmp(b.file_name())) + .into_iter() + .filter_entry(repo::base_dir_filter) + .collect::<Result<Vec<DirEntry>, walkdir::Error>>() + .unwrap() + .into_par_iter() + .for_each(|entry| { + let path = entry.path(); + if !path.is_dir() { + test(path, &failed, abort_after); + } + }); + + let failed = failed.load(Ordering::SeqCst); + if failed > 0 { + panic!("{} failures", failed); + } +} + +fn test(path: &Path, failed: &AtomicUsize, abort_after: usize) { + let content = fs::read_to_string(path).unwrap(); + + let start = Instant::now(); + let (krate, elapsed) = match syn::parse_file(&content) { + Ok(krate) => (krate, start.elapsed()), + Err(msg) => { + errorf!("=== {}: syn failed to parse\n{:?}\n", path.display(), msg); + let prev_failed = failed.fetch_add(1, Ordering::SeqCst); + if prev_failed + 1 >= abort_after { + process::exit(1); + } + return; + } + }; + let back = quote!(#krate).to_string(); + let edition = repo::edition(path).parse().unwrap(); + + rustc_span::with_session_globals(edition, || { + let equal = match panic::catch_unwind(|| { + let sess = ParseSess::new(FilePathMapping::empty()); + let before = match librustc_parse(content, &sess) { + Ok(before) => before, + Err(mut diagnostic) => { + diagnostic.cancel(); + if diagnostic + .message() + .starts_with("file not found for module") + { + errorf!("=== {}: ignore\n", path.display()); + } else { + errorf!( + "=== {}: ignore - librustc failed to parse original content: {}\n", + path.display(), + diagnostic.message(), + ); + } + return Err(true); + } + }; + let after = match librustc_parse(back, &sess) { + Ok(after) => after, + Err(mut diagnostic) => { + errorf!("=== {}: librustc failed to parse", path.display()); + diagnostic.emit(); + return Err(false); + } + }; + Ok((before, after)) + }) { + Err(_) => { + errorf!("=== {}: ignoring librustc panic\n", path.display()); + true + } + Ok(Err(equal)) => equal, + Ok(Ok((mut before, mut after))) => { + normalize(&mut before); + normalize(&mut after); + if SpanlessEq::eq(&before, &after) { + errorf!( + "=== {}: pass in {}ms\n", + path.display(), + elapsed.as_secs() * 1000 + u64::from(elapsed.subsec_nanos()) / 1_000_000 + ); + true + } else { + errorf!( + "=== {}: FAIL\nbefore: {:#?}\nafter: {:#?}\n", + path.display(), + before, + after, + ); + false + } + } + }; + if !equal { + let prev_failed = failed.fetch_add(1, Ordering::SeqCst); + if prev_failed + 1 >= abort_after { + process::exit(1); + } + } + }); +} + +fn librustc_parse(content: String, sess: &ParseSess) -> PResult<Crate> { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let counter = COUNTER.fetch_add(1, Ordering::Relaxed); + let name = FileName::Custom(format!("test_round_trip{}", counter)); + parse::parse_crate_from_source_str(name, content, sess) +} + +fn normalize(krate: &mut Crate) { + struct NormalizeVisitor; + + impl MutVisitor for NormalizeVisitor { + fn visit_angle_bracketed_parameter_data(&mut self, e: &mut AngleBracketedArgs) { + #[derive(Ord, PartialOrd, Eq, PartialEq)] + enum Group { + Lifetimes, + TypesAndConsts, + Constraints, + } + e.args.sort_by_key(|arg| match arg { + AngleBracketedArg::Arg(arg) => match arg { + GenericArg::Lifetime(_) => Group::Lifetimes, + GenericArg::Type(_) | GenericArg::Const(_) => Group::TypesAndConsts, + }, + AngleBracketedArg::Constraint(_) => Group::Constraints, + }); + mut_visit::noop_visit_angle_bracketed_parameter_data(e, self); + } + + fn visit_generics(&mut self, e: &mut Generics) { + #[derive(Ord, PartialOrd, Eq, PartialEq)] + enum Group { + Lifetimes, + TypesAndConsts, + } + e.params.sort_by_key(|param| match param.kind { + GenericParamKind::Lifetime => Group::Lifetimes, + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { + Group::TypesAndConsts + } + }); + mut_visit::noop_visit_generics(e, self); + } + } + + NormalizeVisitor.visit_crate(krate); +} diff --git a/tests/test_shebang.rs b/tests/test_shebang.rs new file mode 100644 index 00000000..dc26b9aa --- /dev/null +++ b/tests/test_shebang.rs @@ -0,0 +1,59 @@ +#[macro_use] +mod macros; + +#[test] +fn test_basic() { + let content = "#!/usr/bin/env rustx\nfn main() {}"; + let file = syn::parse_file(content).unwrap(); + snapshot!(file, @r###" + File { + shebang: Some("#!/usr/bin/env rustx"), + items: [ + Item::Fn { + vis: Inherited, + sig: Signature { + ident: "main", + generics: Generics, + output: Default, + }, + block: Block, + }, + ], + } + "###); +} + +#[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###" + File { + attrs: [ + Attribute { + style: Inner, + path: Path { + segments: [ + PathSegment { + ident: "allow", + arguments: None, + }, + ], + }, + tokens: TokenStream(`(dead_code)`), + }, + ], + items: [ + Item::Fn { + vis: Inherited, + sig: Signature { + ident: "main", + generics: Generics, + output: Default, + }, + block: Block, + }, + ], + } + "###); +} diff --git a/1.0.7/tests/test_should_parse.rs b/tests/test_should_parse.rs index d4f7ac34..180d8599 100644 --- a/1.0.7/tests/test_should_parse.rs +++ b/tests/test_should_parse.rs @@ -1,5 +1,3 @@ -mod features; - macro_rules! should_parse { ($name:ident, { $($in:tt)* }) => { #[test] diff --git a/1.0.7/tests/test_size.rs b/tests/test_size.rs index 386d4df8..01e84011 100644 --- a/1.0.7/tests/test_size.rs +++ b/tests/test_size.rs @@ -1,7 +1,5 @@ #![cfg(target_pointer_width = "64")] -mod features; - use std::mem; use syn::*; diff --git a/tests/test_stmt.rs b/tests/test_stmt.rs new file mode 100644 index 00000000..943d856e --- /dev/null +++ b/tests/test_stmt.rs @@ -0,0 +1,74 @@ +#[macro_use] +mod macros; + +use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; +use std::iter::FromIterator; +use syn::Stmt; + +#[test] +fn test_raw_operator() { + let stmt = syn::parse_str::<Stmt>("let _ = &raw const x;").unwrap(); + + snapshot!(stmt, @r###" + Local(Local { + pat: Pat::Wild, + init: Some(Verbatim(`& raw const x`)), + }) + "###); +} + +#[test] +fn test_raw_variable() { + let stmt = syn::parse_str::<Stmt>("let _ = &raw;").unwrap(); + + snapshot!(stmt, @r###" + Local(Local { + pat: Pat::Wild, + init: Some(Expr::Reference { + expr: Expr::Path { + path: Path { + segments: [ + PathSegment { + ident: "raw", + arguments: None, + }, + ], + }, + }, + }), + }) + "###); +} + +#[test] +fn test_raw_invalid() { + assert!(syn::parse_str::<Stmt>("let _ = &raw x;").is_err()); +} + +#[test] +fn test_none_group() { + // <Ø async fn f() {} Ø> + let tokens = TokenStream::from_iter(vec![TokenTree::Group(Group::new( + Delimiter::None, + TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("async", Span::call_site())), + TokenTree::Ident(Ident::new("fn", Span::call_site())), + TokenTree::Ident(Ident::new("f", Span::call_site())), + TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::new())), + TokenTree::Group(Group::new(Delimiter::Brace, TokenStream::new())), + ]), + ))]); + + snapshot!(tokens as Stmt, @r###" + Item(Item::Fn { + vis: Inherited, + sig: Signature { + asyncness: Some, + ident: "f", + generics: Generics, + output: Default, + }, + block: Block, + }) + "###); +} diff --git a/1.0.7/tests/test_token_trees.rs b/tests/test_token_trees.rs index 5d7610bb..5b00448a 100644 --- a/1.0.7/tests/test_token_trees.rs +++ b/tests/test_token_trees.rs @@ -1,5 +1,3 @@ -mod features; - #[macro_use] mod macros; @@ -17,7 +15,11 @@ fn test_struct() { } "; - snapshot!(input as TokenStream, @"`# [ derive ( Debug , Clone ) ] pub struct Item { pub ident : Ident , pub attrs : Vec < Attribute >, }`"); + snapshot!(input as TokenStream, @r###" + TokenStream( + `# [derive (Debug , Clone)] pub struct Item { pub ident : Ident , pub attrs : Vec < Attribute >, }`, + ) + "###); } #[test] diff --git a/tests/test_ty.rs b/tests/test_ty.rs new file mode 100644 index 00000000..7e20dd99 --- /dev/null +++ b/tests/test_ty.rs @@ -0,0 +1,219 @@ +#[macro_use] +mod macros; + +use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree}; +use quote::quote; +use std::iter::FromIterator; +use syn::Type; + +#[test] +fn test_mut_self() { + syn::parse_str::<Type>("fn(mut self)").unwrap(); + syn::parse_str::<Type>("fn(mut self: ())").unwrap(); + syn::parse_str::<Type>("fn(mut self: ...)").unwrap_err(); + syn::parse_str::<Type>("fn(mut self: mut self)").unwrap_err(); + syn::parse_str::<Type>("fn(mut self::T)").unwrap_err(); +} + +#[test] +fn test_macro_variable_type() { + // mimics the token stream corresponding to `$ty<T>` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, quote! { ty })), + TokenTree::Punct(Punct::new('<', Spacing::Alone)), + TokenTree::Ident(Ident::new("T", Span::call_site())), + TokenTree::Punct(Punct::new('>', Spacing::Alone)), + ]); + + snapshot!(tokens as Type, @r###" + Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "ty", + arguments: PathArguments::AngleBracketed { + args: [ + Type(Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "T", + arguments: None, + }, + ], + }, + }), + ], + }, + }, + ], + }, + } + "###); + + // mimics the token stream corresponding to `$ty::<T>` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, quote! { ty })), + TokenTree::Punct(Punct::new(':', Spacing::Joint)), + TokenTree::Punct(Punct::new(':', Spacing::Alone)), + TokenTree::Punct(Punct::new('<', Spacing::Alone)), + TokenTree::Ident(Ident::new("T", Span::call_site())), + TokenTree::Punct(Punct::new('>', Spacing::Alone)), + ]); + + snapshot!(tokens as Type, @r###" + Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "ty", + arguments: PathArguments::AngleBracketed { + colon2_token: Some, + args: [ + Type(Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "T", + arguments: None, + }, + ], + }, + }), + ], + }, + }, + ], + }, + } + "###); +} + +#[test] +fn test_group_angle_brackets() { + // mimics the token stream corresponding to `Option<$ty>` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("Option", Span::call_site())), + TokenTree::Punct(Punct::new('<', Spacing::Alone)), + TokenTree::Group(Group::new(Delimiter::None, quote! { Vec<u8> })), + TokenTree::Punct(Punct::new('>', Spacing::Alone)), + ]); + + snapshot!(tokens as Type, @r###" + Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "Option", + arguments: PathArguments::AngleBracketed { + args: [ + Type(Type::Group { + elem: Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "Vec", + arguments: PathArguments::AngleBracketed { + args: [ + Type(Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "u8", + arguments: None, + }, + ], + }, + }), + ], + }, + }, + ], + }, + }, + }), + ], + }, + }, + ], + }, + } + "###); +} + +#[test] +fn test_group_colons() { + // mimics the token stream corresponding to `$ty::Item` + let tokens = TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, quote! { Vec<u8> })), + TokenTree::Punct(Punct::new(':', Spacing::Joint)), + TokenTree::Punct(Punct::new(':', Spacing::Alone)), + TokenTree::Ident(Ident::new("Item", Span::call_site())), + ]); + + snapshot!(tokens as Type, @r###" + Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "Vec", + arguments: PathArguments::AngleBracketed { + args: [ + Type(Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "u8", + arguments: None, + }, + ], + }, + }), + ], + }, + }, + PathSegment { + ident: "Item", + arguments: None, + }, + ], + }, + } + "###); + + let tokens = TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, quote! { [T] })), + TokenTree::Punct(Punct::new(':', Spacing::Joint)), + TokenTree::Punct(Punct::new(':', Spacing::Alone)), + TokenTree::Ident(Ident::new("Element", Span::call_site())), + ]); + + snapshot!(tokens as Type, @r###" + Type::Path { + qself: Some(QSelf { + ty: Type::Slice { + elem: Type::Path { + path: Path { + segments: [ + PathSegment { + ident: "T", + arguments: None, + }, + ], + }, + }, + }, + position: 0, + }), + path: Path { + leading_colon: Some, + segments: [ + PathSegment { + ident: "Element", + arguments: None, + }, + ], + }, + } + "###); +} diff --git a/tests/test_visibility.rs b/tests/test_visibility.rs new file mode 100644 index 00000000..7b2c00ba --- /dev/null +++ b/tests/test_visibility.rs @@ -0,0 +1,148 @@ +#[macro_use] +mod macros; + +use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::iter::FromIterator; +use syn::parse::{Parse, ParseStream}; +use syn::{DeriveInput, Result, Visibility}; + +#[derive(Debug)] +struct VisRest { + vis: Visibility, + rest: TokenStream, +} + +impl Parse for VisRest { + fn parse(input: ParseStream) -> Result<Self> { + Ok(VisRest { + vis: input.parse()?, + rest: input.parse()?, + }) + } +} + +macro_rules! assert_vis_parse { + ($input:expr, Ok($p:pat)) => { + assert_vis_parse!($input, Ok($p) + ""); + }; + + ($input:expr, Ok($p:pat) + $rest:expr) => { + let expected = $rest.parse::<TokenStream>().unwrap(); + let parse: VisRest = syn::parse_str($input).unwrap(); + + match parse.vis { + $p => {} + _ => panic!("Expected {}, got {:?}", stringify!($p), parse.vis), + } + + // NOTE: Round-trips through `to_string` to avoid potential whitespace + // diffs. + assert_eq!(parse.rest.to_string(), expected.to_string()); + }; + + ($input:expr, Err) => { + syn::parse2::<VisRest>($input.parse().unwrap()).unwrap_err(); + }; +} + +#[test] +fn test_pub() { + assert_vis_parse!("pub", Ok(Visibility::Public(_))); +} + +#[test] +fn test_crate() { + assert_vis_parse!("crate", Ok(Visibility::Crate(_))); +} + +#[test] +fn test_inherited() { + assert_vis_parse!("", Ok(Visibility::Inherited)); +} + +#[test] +fn test_in() { + assert_vis_parse!("pub(in foo::bar)", Ok(Visibility::Restricted(_))); +} + +#[test] +fn test_pub_crate() { + assert_vis_parse!("pub(crate)", Ok(Visibility::Restricted(_))); +} + +#[test] +fn test_pub_self() { + assert_vis_parse!("pub(self)", Ok(Visibility::Restricted(_))); +} + +#[test] +fn test_pub_super() { + assert_vis_parse!("pub(super)", Ok(Visibility::Restricted(_))); +} + +#[test] +fn test_missing_in() { + assert_vis_parse!("pub(foo::bar)", Ok(Visibility::Public(_)) + "(foo::bar)"); +} + +#[test] +fn test_missing_in_path() { + assert_vis_parse!("pub(in)", Err); +} + +#[test] +fn test_crate_path() { + assert_vis_parse!( + "pub(crate::A, crate::B)", + Ok(Visibility::Public(_)) + "(crate::A, crate::B)" + ); +} + +#[test] +fn test_junk_after_in() { + assert_vis_parse!("pub(in some::path @@garbage)", Err); +} + +#[test] +fn test_empty_group_vis() { + // mimics `struct S { $vis $field: () }` where $vis is empty + let tokens = TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("struct", Span::call_site())), + TokenTree::Ident(Ident::new("S", Span::call_site())), + TokenTree::Group(Group::new( + Delimiter::Brace, + TokenStream::from_iter(vec![ + TokenTree::Group(Group::new(Delimiter::None, TokenStream::new())), + TokenTree::Group(Group::new( + Delimiter::None, + TokenStream::from_iter(vec![TokenTree::Ident(Ident::new( + "f", + Span::call_site(), + ))]), + )), + TokenTree::Punct(Punct::new(':', Spacing::Alone)), + TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::new())), + ]), + )), + ]); + + snapshot!(tokens as DeriveInput, @r###" + DeriveInput { + vis: Inherited, + ident: "S", + generics: Generics, + data: Data::Struct { + fields: Fields::Named { + named: [ + Field { + vis: Inherited, + ident: Some("f"), + colon_token: Some, + ty: Type::Tuple, + }, + ], + }, + }, + } + "###); +} diff --git a/1.0.7/tests/zzz_stable.rs b/tests/zzz_stable.rs index 6c768f27..a1a670d9 100644 --- a/1.0.7/tests/zzz_stable.rs +++ b/tests/zzz_stable.rs @@ -8,7 +8,7 @@ const MSG: &str = "\ ‖ WARNING: ‖ This is not a nightly compiler so not all tests were able to ‖ run. Syn includes tests that compare Syn's parser against the -‖ compiler's parser, which requires access to unstable libsyntax +‖ compiler's parser, which requires access to unstable librustc ‖ data structures and a nightly compiler. ‖ "; |