JosephStoneCellAI commited on
Commit
5b9eba7
·
verified ·
1 Parent(s): e5fd5f2

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/.github/FUNDING.yml +1 -0
  2. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/.github/workflows/ci.yml +147 -0
  3. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/backtrace.rs +410 -0
  4. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/chain.rs +102 -0
  5. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/context.rs +193 -0
  6. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/ensure.rs +935 -0
  7. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/error.rs +1086 -0
  8. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/fmt.rs +158 -0
  9. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/kind.rs +121 -0
  10. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/lib.rs +728 -0
  11. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/macros.rs +245 -0
  12. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/nightly.rs +58 -0
  13. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/ptr.rs +187 -0
  14. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/wrapper.rs +84 -0
  15. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/common/mod.rs +14 -0
  16. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/compiletest.rs +7 -0
  17. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/drop/mod.rs +53 -0
  18. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_autotrait.rs +34 -0
  19. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_backtrace.rs +15 -0
  20. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_boxed.rs +45 -0
  21. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_chain.rs +69 -0
  22. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_context.rs +172 -0
  23. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_convert.rs +46 -0
  24. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_downcast.rs +123 -0
  25. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_ensure.rs +756 -0
  26. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_ffi.rs +19 -0
  27. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_fmt.rs +93 -0
  28. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_macros.rs +97 -0
  29. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_repr.rs +30 -0
  30. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_source.rs +62 -0
  31. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/chained-comparison.rs +8 -0
  32. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/chained-comparison.stderr +10 -0
  33. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/empty-ensure.rs +6 -0
  34. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/empty-ensure.stderr +12 -0
  35. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/ensure-nonbool.rs +40 -0
  36. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/ensure-nonbool.stderr +113 -0
  37. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/must-use.rs +11 -0
  38. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/must-use.stderr +15 -0
  39. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/no-impl.rs +8 -0
  40. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/no-impl.stderr +32 -0
  41. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/temporary-value.rs +5 -0
  42. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/temporary-value.stderr +15 -0
  43. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/wrong-interpolation.rs +5 -0
  44. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/wrong-interpolation.stderr +5 -0
  45. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_02_parse.rs +17 -0
  46. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_02_validate.md +29 -0
  47. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_02_validate.rs +36 -0
  48. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_03_relations.md +53 -0
  49. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_03_relations.rs +78 -0
  50. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_04_custom.md +52 -0
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/.github/FUNDING.yml ADDED
@@ -0,0 +1 @@
 
 
1
+ github: dtolnay
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/.github/workflows/ci.yml ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+ workflow_dispatch:
7
+ schedule: [cron: "40 1 * * *"]
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ env:
13
+ RUSTFLAGS: -Dwarnings
14
+
15
+ jobs:
16
+ pre_ci:
17
+ uses: dtolnay/.github/.github/workflows/pre_ci.yml@master
18
+
19
+ test:
20
+ name: Rust ${{matrix.rust}}
21
+ needs: pre_ci
22
+ if: needs.pre_ci.outputs.continue
23
+ runs-on: ubuntu-latest
24
+ strategy:
25
+ fail-fast: false
26
+ matrix:
27
+ rust: [nightly, beta, stable, 1.82.0, 1.80.0, 1.76.0]
28
+ timeout-minutes: 45
29
+ steps:
30
+ - uses: actions/checkout@v6
31
+ - uses: dtolnay/rust-toolchain@master
32
+ with:
33
+ toolchain: ${{matrix.rust}}
34
+ components: rust-src
35
+ - name: Enable type layout randomization
36
+ run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV
37
+ if: matrix.rust == 'nightly'
38
+ - name: Enable nightly-only tests
39
+ run: echo RUSTFLAGS=${RUSTFLAGS}\ --cfg=anyhow_nightly_testing >> $GITHUB_ENV
40
+ if: matrix.rust == 'nightly'
41
+ - run: cargo test
42
+ - run: cargo check --no-default-features
43
+ - run: cargo check --features backtrace
44
+ if: matrix.rust != '1.80.0' && matrix.rust != '1.76.0'
45
+ - uses: actions/upload-artifact@v6
46
+ if: matrix.rust == 'nightly' && always()
47
+ with:
48
+ name: Cargo.lock
49
+ path: Cargo.lock
50
+ continue-on-error: true
51
+
52
+ build:
53
+ name: Rust ${{matrix.rust}}
54
+ needs: pre_ci
55
+ if: needs.pre_ci.outputs.continue
56
+ runs-on: ubuntu-latest
57
+ strategy:
58
+ fail-fast: false
59
+ matrix:
60
+ rust: [1.68.0]
61
+ timeout-minutes: 45
62
+ steps:
63
+ - uses: actions/checkout@v6
64
+ - uses: dtolnay/rust-toolchain@master
65
+ with:
66
+ toolchain: ${{matrix.rust}}
67
+ components: rust-src
68
+ - run: cargo check --manifest-path tests/crate/Cargo.toml
69
+ - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features
70
+
71
+ minimal:
72
+ name: Minimal versions
73
+ needs: pre_ci
74
+ if: needs.pre_ci.outputs.continue
75
+ runs-on: ubuntu-latest
76
+ timeout-minutes: 45
77
+ steps:
78
+ - uses: actions/checkout@v6
79
+ - uses: dtolnay/rust-toolchain@nightly
80
+ - run: cargo generate-lockfile -Z minimal-versions
81
+ - run: cargo check --locked --features backtrace
82
+
83
+ windows:
84
+ name: Windows
85
+ needs: pre_ci
86
+ if: needs.pre_ci.outputs.continue
87
+ runs-on: windows-latest
88
+ timeout-minutes: 45
89
+ steps:
90
+ - uses: actions/checkout@v6
91
+ - uses: dtolnay/rust-toolchain@stable
92
+ with:
93
+ components: rust-src
94
+ - run: cargo check --features backtrace
95
+
96
+ doc:
97
+ name: Documentation
98
+ needs: pre_ci
99
+ if: needs.pre_ci.outputs.continue
100
+ runs-on: ubuntu-latest
101
+ timeout-minutes: 45
102
+ env:
103
+ RUSTDOCFLAGS: -Dwarnings
104
+ steps:
105
+ - uses: actions/checkout@v6
106
+ - uses: dtolnay/rust-toolchain@nightly
107
+ with:
108
+ components: rust-src
109
+ - uses: dtolnay/install@cargo-docs-rs
110
+ - run: cargo docs-rs
111
+
112
+ clippy:
113
+ name: Clippy
114
+ runs-on: ubuntu-latest
115
+ if: github.event_name != 'pull_request'
116
+ timeout-minutes: 45
117
+ steps:
118
+ - uses: actions/checkout@v6
119
+ - uses: dtolnay/rust-toolchain@nightly
120
+ with:
121
+ components: clippy, rust-src
122
+ - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic
123
+
124
+ miri:
125
+ name: Miri
126
+ needs: pre_ci
127
+ if: needs.pre_ci.outputs.continue
128
+ runs-on: ubuntu-latest
129
+ timeout-minutes: 45
130
+ steps:
131
+ - uses: actions/checkout@v6
132
+ - uses: dtolnay/rust-toolchain@miri
133
+ - run: cargo miri setup
134
+ - run: cargo miri test
135
+ env:
136
+ MIRIFLAGS: -Zmiri-strict-provenance
137
+
138
+ outdated:
139
+ name: Outdated
140
+ runs-on: ubuntu-latest
141
+ if: github.event_name != 'pull_request'
142
+ timeout-minutes: 45
143
+ steps:
144
+ - uses: actions/checkout@v6
145
+ - uses: dtolnay/rust-toolchain@stable
146
+ - uses: dtolnay/install@cargo-outdated
147
+ - run: cargo outdated --workspace --exit-code 1
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/backtrace.rs ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #[cfg(std_backtrace)]
2
+ pub(crate) use std::backtrace::{Backtrace, BacktraceStatus};
3
+
4
+ #[cfg(all(not(std_backtrace), feature = "backtrace"))]
5
+ pub(crate) use self::capture::{Backtrace, BacktraceStatus};
6
+
7
+ #[cfg(not(any(std_backtrace, feature = "backtrace")))]
8
+ pub(crate) enum Backtrace {}
9
+
10
+ #[cfg(std_backtrace)]
11
+ macro_rules! impl_backtrace {
12
+ () => {
13
+ std::backtrace::Backtrace
14
+ };
15
+ }
16
+
17
+ #[cfg(all(not(std_backtrace), feature = "backtrace"))]
18
+ macro_rules! impl_backtrace {
19
+ () => {
20
+ impl core::fmt::Debug + core::fmt::Display
21
+ };
22
+ }
23
+
24
+ #[cfg(any(std_backtrace, feature = "backtrace"))]
25
+ macro_rules! backtrace {
26
+ () => {
27
+ Some(crate::backtrace::Backtrace::capture())
28
+ };
29
+ }
30
+
31
+ #[cfg(not(any(std_backtrace, feature = "backtrace")))]
32
+ macro_rules! backtrace {
33
+ () => {
34
+ None
35
+ };
36
+ }
37
+
38
+ #[cfg(error_generic_member_access)]
39
+ macro_rules! backtrace_if_absent {
40
+ ($err:expr) => {
41
+ match $crate::nightly::request_ref_backtrace($err as &dyn core::error::Error) {
42
+ Some(_) => None,
43
+ None => backtrace!(),
44
+ }
45
+ };
46
+ }
47
+
48
+ #[cfg(all(
49
+ any(feature = "std", not(anyhow_no_core_error)),
50
+ not(error_generic_member_access),
51
+ any(std_backtrace, feature = "backtrace")
52
+ ))]
53
+ macro_rules! backtrace_if_absent {
54
+ ($err:expr) => {
55
+ backtrace!()
56
+ };
57
+ }
58
+
59
+ #[cfg(all(
60
+ any(feature = "std", not(anyhow_no_core_error)),
61
+ not(std_backtrace),
62
+ not(feature = "backtrace"),
63
+ ))]
64
+ macro_rules! backtrace_if_absent {
65
+ ($err:expr) => {
66
+ None
67
+ };
68
+ }
69
+
70
+ #[cfg(all(not(std_backtrace), feature = "backtrace"))]
71
+ mod capture {
72
+ use alloc::borrow::{Cow, ToOwned as _};
73
+ use alloc::vec::Vec;
74
+ use backtrace::{BacktraceFmt, BytesOrWideString, Frame, PrintFmt, SymbolName};
75
+ use core::cell::UnsafeCell;
76
+ use core::fmt::{self, Debug, Display};
77
+ use core::sync::atomic::{AtomicUsize, Ordering};
78
+ use std::env;
79
+ use std::path::{self, Path, PathBuf};
80
+ use std::sync::Once;
81
+
82
+ pub(crate) struct Backtrace {
83
+ inner: Inner,
84
+ }
85
+
86
+ pub(crate) enum BacktraceStatus {
87
+ Unsupported,
88
+ Disabled,
89
+ Captured,
90
+ }
91
+
92
+ enum Inner {
93
+ Unsupported,
94
+ Disabled,
95
+ Captured(LazilyResolvedCapture),
96
+ }
97
+
98
+ struct Capture {
99
+ actual_start: usize,
100
+ resolved: bool,
101
+ frames: Vec<BacktraceFrame>,
102
+ }
103
+
104
+ struct BacktraceFrame {
105
+ frame: Frame,
106
+ symbols: Vec<BacktraceSymbol>,
107
+ }
108
+
109
+ struct BacktraceSymbol {
110
+ name: Option<Vec<u8>>,
111
+ filename: Option<BytesOrWide>,
112
+ lineno: Option<u32>,
113
+ colno: Option<u32>,
114
+ }
115
+
116
+ enum BytesOrWide {
117
+ Bytes(Vec<u8>),
118
+ Wide(Vec<u16>),
119
+ }
120
+
121
+ impl Debug for Backtrace {
122
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
123
+ let capture = match &self.inner {
124
+ Inner::Unsupported => return fmt.write_str("<unsupported>"),
125
+ Inner::Disabled => return fmt.write_str("<disabled>"),
126
+ Inner::Captured(c) => c.force(),
127
+ };
128
+
129
+ let frames = &capture.frames[capture.actual_start..];
130
+
131
+ write!(fmt, "Backtrace ")?;
132
+
133
+ let mut dbg = fmt.debug_list();
134
+
135
+ for frame in frames {
136
+ if frame.frame.ip().is_null() {
137
+ continue;
138
+ }
139
+
140
+ dbg.entries(&frame.symbols);
141
+ }
142
+
143
+ dbg.finish()
144
+ }
145
+ }
146
+
147
+ impl Debug for BacktraceFrame {
148
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
149
+ let mut dbg = fmt.debug_list();
150
+ dbg.entries(&self.symbols);
151
+ dbg.finish()
152
+ }
153
+ }
154
+
155
+ impl Debug for BacktraceSymbol {
156
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
157
+ write!(fmt, "{{ ")?;
158
+
159
+ if let Some(fn_name) = self.name.as_ref().map(|b| SymbolName::new(b)) {
160
+ write!(fmt, "fn: \"{:#}\"", fn_name)?;
161
+ } else {
162
+ write!(fmt, "fn: <unknown>")?;
163
+ }
164
+
165
+ if let Some(fname) = self.filename.as_ref() {
166
+ write!(fmt, ", file: \"{:?}\"", fname)?;
167
+ }
168
+
169
+ if let Some(line) = self.lineno {
170
+ write!(fmt, ", line: {:?}", line)?;
171
+ }
172
+
173
+ write!(fmt, " }}")
174
+ }
175
+ }
176
+
177
+ impl Debug for BytesOrWide {
178
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
179
+ output_filename(
180
+ fmt,
181
+ match self {
182
+ BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
183
+ BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
184
+ },
185
+ PrintFmt::Short,
186
+ env::current_dir().as_ref().ok(),
187
+ )
188
+ }
189
+ }
190
+
191
+ impl Backtrace {
192
+ fn enabled() -> bool {
193
+ static ENABLED: AtomicUsize = AtomicUsize::new(0);
194
+ match ENABLED.load(Ordering::Relaxed) {
195
+ 0 => {}
196
+ 1 => return false,
197
+ _ => return true,
198
+ }
199
+ let enabled = match env::var_os("RUST_LIB_BACKTRACE") {
200
+ Some(s) => s != "0",
201
+ None => match env::var_os("RUST_BACKTRACE") {
202
+ Some(s) => s != "0",
203
+ None => false,
204
+ },
205
+ };
206
+ ENABLED.store(enabled as usize + 1, Ordering::Relaxed);
207
+ enabled
208
+ }
209
+
210
+ #[inline(never)] // want to make sure there's a frame here to remove
211
+ pub(crate) fn capture() -> Backtrace {
212
+ if Backtrace::enabled() {
213
+ Backtrace::create(Backtrace::capture as usize)
214
+ } else {
215
+ let inner = Inner::Disabled;
216
+ Backtrace { inner }
217
+ }
218
+ }
219
+
220
+ // Capture a backtrace which starts just before the function addressed
221
+ // by `ip`
222
+ fn create(ip: usize) -> Backtrace {
223
+ let mut frames = Vec::new();
224
+ let mut actual_start = None;
225
+ backtrace::trace(|frame| {
226
+ frames.push(BacktraceFrame {
227
+ frame: frame.clone(),
228
+ symbols: Vec::new(),
229
+ });
230
+ if frame.symbol_address() as usize == ip && actual_start.is_none() {
231
+ actual_start = Some(frames.len() + 1);
232
+ }
233
+ true
234
+ });
235
+
236
+ // If no frames came out, assume that this is an unsupported platform
237
+ // since `backtrace` doesn't provide a way of learning this right
238
+ // now, and this should be a good enough approximation.
239
+ let inner = if frames.is_empty() {
240
+ Inner::Unsupported
241
+ } else {
242
+ Inner::Captured(LazilyResolvedCapture::new(Capture {
243
+ actual_start: actual_start.unwrap_or(0),
244
+ frames,
245
+ resolved: false,
246
+ }))
247
+ };
248
+
249
+ Backtrace { inner }
250
+ }
251
+
252
+ pub(crate) fn status(&self) -> BacktraceStatus {
253
+ match self.inner {
254
+ Inner::Unsupported => BacktraceStatus::Unsupported,
255
+ Inner::Disabled => BacktraceStatus::Disabled,
256
+ Inner::Captured(_) => BacktraceStatus::Captured,
257
+ }
258
+ }
259
+ }
260
+
261
+ impl Display for Backtrace {
262
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
263
+ let capture = match &self.inner {
264
+ Inner::Unsupported => return fmt.write_str("unsupported backtrace"),
265
+ Inner::Disabled => return fmt.write_str("disabled backtrace"),
266
+ Inner::Captured(c) => c.force(),
267
+ };
268
+
269
+ let full = fmt.alternate();
270
+ let (frames, style) = if full {
271
+ (&capture.frames[..], PrintFmt::Full)
272
+ } else {
273
+ (&capture.frames[capture.actual_start..], PrintFmt::Short)
274
+ };
275
+
276
+ // When printing paths we try to strip the cwd if it exists,
277
+ // otherwise we just print the path as-is. Note that we also only do
278
+ // this for the short format, because if it's full we presumably
279
+ // want to print everything.
280
+ let cwd = env::current_dir();
281
+ let mut print_path = move |fmt: &mut fmt::Formatter, path: BytesOrWideString| {
282
+ output_filename(fmt, path, style, cwd.as_ref().ok())
283
+ };
284
+
285
+ let mut f = BacktraceFmt::new(fmt, style, &mut print_path);
286
+ f.add_context()?;
287
+ for frame in frames {
288
+ let mut f = f.frame();
289
+ if frame.symbols.is_empty() {
290
+ f.print_raw(frame.frame.ip(), None, None, None)?;
291
+ } else {
292
+ for symbol in frame.symbols.iter() {
293
+ f.print_raw_with_column(
294
+ frame.frame.ip(),
295
+ symbol.name.as_ref().map(|b| SymbolName::new(b)),
296
+ symbol.filename.as_ref().map(|b| match b {
297
+ BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
298
+ BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
299
+ }),
300
+ symbol.lineno,
301
+ symbol.colno,
302
+ )?;
303
+ }
304
+ }
305
+ }
306
+ f.finish()?;
307
+ Ok(())
308
+ }
309
+ }
310
+
311
+ struct LazilyResolvedCapture {
312
+ sync: Once,
313
+ capture: UnsafeCell<Capture>,
314
+ }
315
+
316
+ impl LazilyResolvedCapture {
317
+ fn new(capture: Capture) -> Self {
318
+ LazilyResolvedCapture {
319
+ sync: Once::new(),
320
+ capture: UnsafeCell::new(capture),
321
+ }
322
+ }
323
+
324
+ fn force(&self) -> &Capture {
325
+ self.sync.call_once(|| {
326
+ // Safety: This exclusive reference can't overlap with any
327
+ // others. `Once` guarantees callers will block until this
328
+ // closure returns. `Once` also guarantees only a single caller
329
+ // will enter this closure.
330
+ unsafe { &mut *self.capture.get() }.resolve();
331
+ });
332
+
333
+ // Safety: This shared reference can't overlap with the exclusive
334
+ // reference above.
335
+ unsafe { &*self.capture.get() }
336
+ }
337
+ }
338
+
339
+ // Safety: Access to the inner value is synchronized using a thread-safe
340
+ // `Once`. So long as `Capture` is `Sync`, `LazilyResolvedCapture` is too
341
+ unsafe impl Sync for LazilyResolvedCapture where Capture: Sync {}
342
+
343
+ impl Capture {
344
+ fn resolve(&mut self) {
345
+ // If we're already resolved, nothing to do!
346
+ if self.resolved {
347
+ return;
348
+ }
349
+ self.resolved = true;
350
+
351
+ for frame in self.frames.iter_mut() {
352
+ let symbols = &mut frame.symbols;
353
+ let frame = &frame.frame;
354
+ backtrace::resolve_frame(frame, |symbol| {
355
+ symbols.push(BacktraceSymbol {
356
+ name: symbol.name().map(|m| m.as_bytes().to_vec()),
357
+ filename: symbol.filename_raw().map(|b| match b {
358
+ BytesOrWideString::Bytes(b) => BytesOrWide::Bytes(b.to_owned()),
359
+ BytesOrWideString::Wide(b) => BytesOrWide::Wide(b.to_owned()),
360
+ }),
361
+ lineno: symbol.lineno(),
362
+ colno: symbol.colno(),
363
+ });
364
+ });
365
+ }
366
+ }
367
+ }
368
+
369
+ // Prints the filename of the backtrace frame.
370
+ fn output_filename(
371
+ fmt: &mut fmt::Formatter,
372
+ bows: BytesOrWideString,
373
+ print_fmt: PrintFmt,
374
+ cwd: Option<&PathBuf>,
375
+ ) -> fmt::Result {
376
+ let file: Cow<Path> = match bows {
377
+ #[cfg(unix)]
378
+ BytesOrWideString::Bytes(bytes) => {
379
+ use std::os::unix::ffi::OsStrExt;
380
+ Path::new(std::ffi::OsStr::from_bytes(bytes)).into()
381
+ }
382
+ #[cfg(not(unix))]
383
+ BytesOrWideString::Bytes(bytes) => {
384
+ Path::new(std::str::from_utf8(bytes).unwrap_or("<unknown>")).into()
385
+ }
386
+ #[cfg(windows)]
387
+ BytesOrWideString::Wide(wide) => {
388
+ use std::os::windows::ffi::OsStringExt;
389
+ Cow::Owned(std::ffi::OsString::from_wide(wide).into())
390
+ }
391
+ #[cfg(not(windows))]
392
+ BytesOrWideString::Wide(_wide) => Path::new("<unknown>").into(),
393
+ };
394
+ if print_fmt == PrintFmt::Short && file.is_absolute() {
395
+ if let Some(cwd) = cwd {
396
+ if let Ok(stripped) = file.strip_prefix(&cwd) {
397
+ if let Some(s) = stripped.to_str() {
398
+ return write!(fmt, ".{}{}", path::MAIN_SEPARATOR, s);
399
+ }
400
+ }
401
+ }
402
+ }
403
+ Display::fmt(&file.display(), fmt)
404
+ }
405
+ }
406
+
407
+ fn _assert_send_sync() {
408
+ fn assert<T: Send + Sync>() {}
409
+ assert::<Backtrace>();
410
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/chain.rs ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use self::ChainState::*;
2
+ use crate::StdError;
3
+
4
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
5
+ use alloc::vec::{self, Vec};
6
+
7
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
8
+ pub(crate) use crate::Chain;
9
+
10
+ #[cfg(all(not(feature = "std"), anyhow_no_core_error))]
11
+ pub(crate) struct Chain<'a> {
12
+ state: ChainState<'a>,
13
+ }
14
+
15
+ #[derive(Clone)]
16
+ pub(crate) enum ChainState<'a> {
17
+ Linked {
18
+ next: Option<&'a (dyn StdError + 'static)>,
19
+ },
20
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
21
+ Buffered {
22
+ rest: vec::IntoIter<&'a (dyn StdError + 'static)>,
23
+ },
24
+ }
25
+
26
+ impl<'a> Chain<'a> {
27
+ #[cold]
28
+ pub fn new(head: &'a (dyn StdError + 'static)) -> Self {
29
+ Chain {
30
+ state: ChainState::Linked { next: Some(head) },
31
+ }
32
+ }
33
+ }
34
+
35
+ impl<'a> Iterator for Chain<'a> {
36
+ type Item = &'a (dyn StdError + 'static);
37
+
38
+ fn next(&mut self) -> Option<Self::Item> {
39
+ match &mut self.state {
40
+ Linked { next } => {
41
+ let error = (*next)?;
42
+ *next = error.source();
43
+ Some(error)
44
+ }
45
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
46
+ Buffered { rest } => rest.next(),
47
+ }
48
+ }
49
+
50
+ fn size_hint(&self) -> (usize, Option<usize>) {
51
+ let len = self.len();
52
+ (len, Some(len))
53
+ }
54
+ }
55
+
56
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
57
+ impl DoubleEndedIterator for Chain<'_> {
58
+ fn next_back(&mut self) -> Option<Self::Item> {
59
+ match &mut self.state {
60
+ Linked { mut next } => {
61
+ let mut rest = Vec::new();
62
+ while let Some(cause) = next {
63
+ next = cause.source();
64
+ rest.push(cause);
65
+ }
66
+ let mut rest = rest.into_iter();
67
+ let last = rest.next_back();
68
+ self.state = Buffered { rest };
69
+ last
70
+ }
71
+ Buffered { rest } => rest.next_back(),
72
+ }
73
+ }
74
+ }
75
+
76
+ impl ExactSizeIterator for Chain<'_> {
77
+ fn len(&self) -> usize {
78
+ match &self.state {
79
+ Linked { mut next } => {
80
+ let mut len = 0;
81
+ while let Some(cause) = next {
82
+ next = cause.source();
83
+ len += 1;
84
+ }
85
+ len
86
+ }
87
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
88
+ Buffered { rest } => rest.len(),
89
+ }
90
+ }
91
+ }
92
+
93
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
94
+ impl Default for Chain<'_> {
95
+ fn default() -> Self {
96
+ Chain {
97
+ state: ChainState::Buffered {
98
+ rest: Vec::new().into_iter(),
99
+ },
100
+ }
101
+ }
102
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/context.rs ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::error::ContextError;
2
+ use crate::{Context, Error, StdError};
3
+ use core::convert::Infallible;
4
+ use core::fmt::{self, Debug, Display, Write};
5
+
6
+ #[cfg(error_generic_member_access)]
7
+ use crate::nightly::{self, Request};
8
+
9
+ mod ext {
10
+ use super::*;
11
+
12
+ pub trait StdError {
13
+ fn ext_context<C>(self, context: C) -> Error
14
+ where
15
+ C: Display + Send + Sync + 'static;
16
+ }
17
+
18
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
19
+ impl<E> StdError for E
20
+ where
21
+ E: crate::StdError + Send + Sync + 'static,
22
+ {
23
+ fn ext_context<C>(self, context: C) -> Error
24
+ where
25
+ C: Display + Send + Sync + 'static,
26
+ {
27
+ let backtrace = backtrace_if_absent!(&self);
28
+ Error::construct_from_context(context, self, backtrace)
29
+ }
30
+ }
31
+
32
+ impl StdError for Error {
33
+ fn ext_context<C>(self, context: C) -> Error
34
+ where
35
+ C: Display + Send + Sync + 'static,
36
+ {
37
+ self.context(context)
38
+ }
39
+ }
40
+ }
41
+
42
+ impl<T, E> Context<T, E> for Result<T, E>
43
+ where
44
+ E: ext::StdError + Send + Sync + 'static,
45
+ {
46
+ fn context<C>(self, context: C) -> Result<T, Error>
47
+ where
48
+ C: Display + Send + Sync + 'static,
49
+ {
50
+ // Not using map_err to save 2 useless frames off the captured backtrace
51
+ // in ext_context.
52
+ match self {
53
+ Ok(ok) => Ok(ok),
54
+ Err(error) => Err(error.ext_context(context)),
55
+ }
56
+ }
57
+
58
+ fn with_context<C, F>(self, context: F) -> Result<T, Error>
59
+ where
60
+ C: Display + Send + Sync + 'static,
61
+ F: FnOnce() -> C,
62
+ {
63
+ match self {
64
+ Ok(ok) => Ok(ok),
65
+ Err(error) => Err(error.ext_context(context())),
66
+ }
67
+ }
68
+ }
69
+
70
+ /// ```
71
+ /// # type T = ();
72
+ /// #
73
+ /// use anyhow::{Context, Result};
74
+ ///
75
+ /// fn maybe_get() -> Option<T> {
76
+ /// # const IGNORE: &str = stringify! {
77
+ /// ...
78
+ /// # };
79
+ /// # unimplemented!()
80
+ /// }
81
+ ///
82
+ /// fn demo() -> Result<()> {
83
+ /// let t = maybe_get().context("there is no T")?;
84
+ /// # const IGNORE: &str = stringify! {
85
+ /// ...
86
+ /// # };
87
+ /// # unimplemented!()
88
+ /// }
89
+ /// ```
90
+ impl<T> Context<T, Infallible> for Option<T> {
91
+ fn context<C>(self, context: C) -> Result<T, Error>
92
+ where
93
+ C: Display + Send + Sync + 'static,
94
+ {
95
+ // Not using ok_or_else to save 2 useless frames off the captured
96
+ // backtrace.
97
+ match self {
98
+ Some(ok) => Ok(ok),
99
+ None => Err(Error::construct_from_display(context, backtrace!())),
100
+ }
101
+ }
102
+
103
+ fn with_context<C, F>(self, context: F) -> Result<T, Error>
104
+ where
105
+ C: Display + Send + Sync + 'static,
106
+ F: FnOnce() -> C,
107
+ {
108
+ match self {
109
+ Some(ok) => Ok(ok),
110
+ None => Err(Error::construct_from_display(context(), backtrace!())),
111
+ }
112
+ }
113
+ }
114
+
115
+ impl<C, E> Debug for ContextError<C, E>
116
+ where
117
+ C: Display,
118
+ E: Debug,
119
+ {
120
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
121
+ f.debug_struct("Error")
122
+ .field("context", &Quoted(&self.context))
123
+ .field("source", &self.error)
124
+ .finish()
125
+ }
126
+ }
127
+
128
+ impl<C, E> Display for ContextError<C, E>
129
+ where
130
+ C: Display,
131
+ {
132
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133
+ Display::fmt(&self.context, f)
134
+ }
135
+ }
136
+
137
+ impl<C, E> StdError for ContextError<C, E>
138
+ where
139
+ C: Display,
140
+ E: StdError + 'static,
141
+ {
142
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
143
+ Some(&self.error)
144
+ }
145
+
146
+ #[cfg(error_generic_member_access)]
147
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
148
+ nightly::provide(&self.error, request);
149
+ }
150
+ }
151
+
152
+ impl<C> StdError for ContextError<C, Error>
153
+ where
154
+ C: Display,
155
+ {
156
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
157
+ Some(unsafe { crate::ErrorImpl::error(self.error.inner.by_ref()) })
158
+ }
159
+
160
+ #[cfg(error_generic_member_access)]
161
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
162
+ Error::provide(&self.error, request);
163
+ }
164
+ }
165
+
166
+ struct Quoted<C>(C);
167
+
168
+ impl<C> Debug for Quoted<C>
169
+ where
170
+ C: Display,
171
+ {
172
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
173
+ formatter.write_char('"')?;
174
+ Quoted(&mut *formatter).write_fmt(format_args!("{}", self.0))?;
175
+ formatter.write_char('"')?;
176
+ Ok(())
177
+ }
178
+ }
179
+
180
+ impl Write for Quoted<&mut fmt::Formatter<'_>> {
181
+ fn write_str(&mut self, s: &str) -> fmt::Result {
182
+ Display::fmt(&s.escape_debug(), self.0)
183
+ }
184
+ }
185
+
186
+ pub(crate) mod private {
187
+ use super::*;
188
+
189
+ pub trait Sealed {}
190
+
191
+ impl<T, E> Sealed for Result<T, E> where E: ext::StdError {}
192
+ impl<T> Sealed for Option<T> {}
193
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/ensure.rs ADDED
@@ -0,0 +1,935 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::Error;
2
+ use alloc::string::String;
3
+ use core::fmt::{self, Debug, Write};
4
+ use core::mem::MaybeUninit;
5
+ use core::ptr;
6
+ use core::slice;
7
+ use core::str;
8
+
9
+ #[doc(hidden)]
10
+ pub trait BothDebug {
11
+ fn __dispatch_ensure(self, msg: &'static str) -> Error;
12
+ }
13
+
14
+ impl<A, B> BothDebug for (A, B)
15
+ where
16
+ A: Debug,
17
+ B: Debug,
18
+ {
19
+ fn __dispatch_ensure(self, msg: &'static str) -> Error {
20
+ render(msg, &self.0, &self.1)
21
+ }
22
+ }
23
+
24
+ #[doc(hidden)]
25
+ pub trait NotBothDebug {
26
+ fn __dispatch_ensure(self, msg: &'static str) -> Error;
27
+ }
28
+
29
+ impl<A, B> NotBothDebug for &(A, B) {
30
+ fn __dispatch_ensure(self, msg: &'static str) -> Error {
31
+ Error::msg(msg)
32
+ }
33
+ }
34
+
35
+ struct Buf {
36
+ bytes: [MaybeUninit<u8>; 40],
37
+ written: usize,
38
+ }
39
+
40
+ impl Buf {
41
+ fn new() -> Self {
42
+ Buf {
43
+ bytes: [MaybeUninit::uninit(); 40],
44
+ written: 0,
45
+ }
46
+ }
47
+
48
+ fn as_str(&self) -> &str {
49
+ unsafe {
50
+ str::from_utf8_unchecked(slice::from_raw_parts(
51
+ self.bytes.as_ptr().cast::<u8>(),
52
+ self.written,
53
+ ))
54
+ }
55
+ }
56
+ }
57
+
58
+ impl Write for Buf {
59
+ fn write_str(&mut self, s: &str) -> fmt::Result {
60
+ if s.bytes().any(|b| b == b' ' || b == b'\n') {
61
+ return Err(fmt::Error);
62
+ }
63
+
64
+ let remaining = self.bytes.len() - self.written;
65
+ if s.len() > remaining {
66
+ return Err(fmt::Error);
67
+ }
68
+
69
+ unsafe {
70
+ ptr::copy_nonoverlapping(
71
+ s.as_ptr(),
72
+ self.bytes.as_mut_ptr().add(self.written).cast::<u8>(),
73
+ s.len(),
74
+ );
75
+ }
76
+ self.written += s.len();
77
+ Ok(())
78
+ }
79
+ }
80
+
81
+ fn render(msg: &'static str, lhs: &dyn Debug, rhs: &dyn Debug) -> Error {
82
+ let mut lhs_buf = Buf::new();
83
+ if fmt::write(&mut lhs_buf, format_args!("{:?}", lhs)).is_ok() {
84
+ let mut rhs_buf = Buf::new();
85
+ if fmt::write(&mut rhs_buf, format_args!("{:?}", rhs)).is_ok() {
86
+ let lhs_str = lhs_buf.as_str();
87
+ let rhs_str = rhs_buf.as_str();
88
+ // "{msg} ({lhs} vs {rhs})"
89
+ let len = msg.len() + 2 + lhs_str.len() + 4 + rhs_str.len() + 1;
90
+ let mut string = String::with_capacity(len);
91
+ string.push_str(msg);
92
+ string.push_str(" (");
93
+ string.push_str(lhs_str);
94
+ string.push_str(" vs ");
95
+ string.push_str(rhs_str);
96
+ string.push(')');
97
+ return Error::msg(string);
98
+ }
99
+ }
100
+ Error::msg(msg)
101
+ }
102
+
103
+ #[doc(hidden)]
104
+ #[macro_export]
105
+ macro_rules! __parse_ensure {
106
+ (atom () $bail:tt $fuel:tt {($($rhs:tt)+) ($($lhs:tt)+) $op:tt} $dup:tt $(,)?) => {
107
+ $crate::__fancy_ensure!($($lhs)+, $op, $($rhs)+)
108
+ };
109
+
110
+ // low precedence control flow constructs
111
+
112
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt return $($rest:tt)*) => {
113
+ $crate::__fallback_ensure!($($bail)*)
114
+ };
115
+
116
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt break $($rest:tt)*) => {
117
+ $crate::__fallback_ensure!($($bail)*)
118
+ };
119
+
120
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt continue $($rest:tt)*) => {
121
+ $crate::__fallback_ensure!($($bail)*)
122
+ };
123
+
124
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt yield $($rest:tt)*) => {
125
+ $crate::__fallback_ensure!($($bail)*)
126
+ };
127
+
128
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt move $($rest:tt)*) => {
129
+ $crate::__fallback_ensure!($($bail)*)
130
+ };
131
+
132
+ // unary operators
133
+
134
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($deref:tt $($dup:tt)*) * $($rest:tt)*) => {
135
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $deref) $($parse)*} ($($rest)*) $($rest)*)
136
+ };
137
+
138
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($not:tt $($dup:tt)*) ! $($rest:tt)*) => {
139
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $not) $($parse)*} ($($rest)*) $($rest)*)
140
+ };
141
+
142
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($neg:tt $($dup:tt)*) - $($rest:tt)*) => {
143
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $neg) $($parse)*} ($($rest)*) $($rest)*)
144
+ };
145
+
146
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($let:tt $($dup:tt)*) let $($rest:tt)*) => {
147
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $let) $($parse)*} ($($rest)*) $($rest)*)
148
+ };
149
+
150
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($lifetime:tt $colon:tt $($dup:tt)*) $label:lifetime : $($rest:tt)*) => {
151
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $lifetime $colon) $($parse)*} ($($rest)*) $($rest)*)
152
+ };
153
+
154
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $mut:tt $($dup:tt)*) &mut $($rest:tt)*) => {
155
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $and $mut) $($parse)*} ($($rest)*) $($rest)*)
156
+ };
157
+
158
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $raw:tt $mut:tt $($dup:tt)*) &raw mut $($rest:tt)*) => {
159
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $and $raw $mut) $($parse)*} ($($rest)*) $($rest)*)
160
+ };
161
+
162
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $raw:tt $const:tt $($dup:tt)*) &raw const $($rest:tt)*) => {
163
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $and $raw $const) $($parse)*} ($($rest)*) $($rest)*)
164
+ };
165
+
166
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) & $($rest:tt)*) => {
167
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
168
+ };
169
+
170
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $mut:tt $($dup:tt)*) &&mut $($rest:tt)*) => {
171
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $andand $mut) $($parse)*} ($($rest)*) $($rest)*)
172
+ };
173
+
174
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $raw:tt $mut:tt $($dup:tt)*) &&raw mut $($rest:tt)*) => {
175
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $andand $raw $mut) $($parse)*} ($($rest)*) $($rest)*)
176
+ };
177
+
178
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $raw:tt $const:tt $($dup:tt)*) &&raw const $($rest:tt)*) => {
179
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $andand $raw $const) $($parse)*} ($($rest)*) $($rest)*)
180
+ };
181
+
182
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $($dup:tt)*) && $($rest:tt)*) => {
183
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $andand) $($parse)*} ($($rest)*) $($rest)*)
184
+ };
185
+
186
+ // control flow constructs
187
+
188
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($if:tt $($dup:tt)*) if $($rest:tt)*) => {
189
+ $crate::__parse_ensure!(0 (cond $stack) $bail ($($fuel)*) {($($buf)* $if) $($parse)*} ($($rest)*) $($rest)*)
190
+ };
191
+
192
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($match:tt $($dup:tt)*) match $($rest:tt)*) => {
193
+ $crate::__parse_ensure!(0 (cond $stack) $bail ($($fuel)*) {($($buf)* $match) $($parse)*} ($($rest)*) $($rest)*)
194
+ };
195
+
196
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($while:tt $($dup:tt)*) while $($rest:tt)*) => {
197
+ $crate::__parse_ensure!(0 (cond $stack) $bail ($($fuel)*) {($($buf)* $while) $($parse)*} ($($rest)*) $($rest)*)
198
+ };
199
+
200
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($for:tt $($dup:tt)*) for $($rest:tt)*) => {
201
+ $crate::__parse_ensure!(pat (cond $stack) $bail ($($fuel)*) {($($buf)* $for) $($parse)*} ($($rest)*) $($rest)*)
202
+ };
203
+
204
+ (atom (cond $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($block:tt)*} $($rest:tt)*) => {
205
+ $crate::__parse_ensure!(cond $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
206
+ };
207
+
208
+ (cond $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($else:tt $if:tt $($dup:tt)*) else if $($rest:tt)*) => {
209
+ $crate::__parse_ensure!(0 (cond $stack) $bail ($($fuel)*) {($($buf)* $else $if) $($parse)*} ($($rest)*) $($rest)*)
210
+ };
211
+
212
+ (cond $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($else:tt $brace:tt $($dup:tt)*) else {$($block:tt)*} $($rest:tt)*) => {
213
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $else $brace) $($parse)*} ($($rest)*) $($rest)*)
214
+ };
215
+
216
+ (cond $stack:tt $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
217
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) $parse $dup $($rest)*)
218
+ };
219
+
220
+ // atomic expressions
221
+
222
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($content:tt)*) $($rest:tt)*) => {
223
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
224
+ };
225
+
226
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bracket:tt $($dup:tt)*) [$($array:tt)*] $($rest:tt)*) => {
227
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $bracket) $($parse)*} ($($rest)*) $($rest)*)
228
+ };
229
+
230
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($block:tt)*} $($rest:tt)*) => {
231
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
232
+ };
233
+
234
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($loop:tt $block:tt $($dup:tt)*) loop {$($body:tt)*} $($rest:tt)*) => {
235
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $loop $block) $($parse)*} ($($rest)*) $($rest)*)
236
+ };
237
+
238
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($async:tt $block:tt $($dup:tt)*) async {$($body:tt)*} $($rest:tt)*) => {
239
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $async $block) $($parse)*} ($($rest)*) $($rest)*)
240
+ };
241
+
242
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($async:tt $move:tt $block:tt $($dup:tt)*) async move {$($body:tt)*} $($rest:tt)*) => {
243
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $async $move $block) $($parse)*} ($($rest)*) $($rest)*)
244
+ };
245
+
246
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($unsafe:tt $block:tt $($dup:tt)*) unsafe {$($body:tt)*} $($rest:tt)*) => {
247
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $unsafe $block) $($parse)*} ($($rest)*) $($rest)*)
248
+ };
249
+
250
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($const:tt $block:tt $($dup:tt)*) const {$($body:tt)*} $($rest:tt)*) => {
251
+ // TODO: this is mostly useless due to https://github.com/rust-lang/rust/issues/86730
252
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $const $block) $($parse)*} ($($rest)*) $($rest)*)
253
+ };
254
+
255
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($literal:tt $($dup:tt)*) $lit:literal $($rest:tt)*) => {
256
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $literal) $($parse)*} ($($rest)*) $($rest)*)
257
+ };
258
+
259
+ // path expressions
260
+
261
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
262
+ $crate::__parse_ensure!(epath (atom $stack) $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
263
+ };
264
+
265
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ident:tt $($dup:tt)*) $i:ident $($rest:tt)*) => {
266
+ $crate::__parse_ensure!(epath (atom $stack) $bail ($($fuel)*) {($($buf)* $ident) $($parse)*} ($($rest)*) $($rest)*)
267
+ };
268
+
269
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) < $($rest:tt)*) => {
270
+ $crate::__parse_ensure!(type (qpath (epath (atom $stack))) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
271
+ };
272
+
273
+ (epath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: < $($rest:tt)*) => {
274
+ $crate::__parse_ensure!(generic (epath $stack) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
275
+ };
276
+
277
+ (epath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: << $($rest:tt)*) => {
278
+ $crate::__parse_ensure!(type (qpath (tpath (arglist (epath $stack)))) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
279
+ };
280
+
281
+ (epath $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt :: <- - $($rest:tt)*) => {
282
+ $crate::__fallback_ensure!($($bail)*)
283
+ };
284
+
285
+ (epath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $larrow:tt $($dup:tt)*) :: <- $lit:literal $($rest:tt)*) => {
286
+ $crate::__parse_ensure!(generic (epath $stack) $bail ($($fuel)*) {($($buf)* $colons $larrow) $($parse)*} ($($dup)*) $($dup)*)
287
+ };
288
+
289
+ (epath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
290
+ $crate::__parse_ensure!(epath $stack $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
291
+ };
292
+
293
+ (epath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! ($($mac:tt)*) $($rest:tt)*) => {
294
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
295
+ };
296
+
297
+ (epath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! [$($mac:tt)*] $($rest:tt)*) => {
298
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
299
+ };
300
+
301
+ (epath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! {$($mac:tt)*} $($rest:tt)*) => {
302
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
303
+ };
304
+
305
+ (epath (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
306
+ $crate::__parse_ensure!($pop (split $stack) $bail ($($fuel)*) $parse $dup $($rest)*)
307
+ };
308
+
309
+ (epath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
310
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) $parse $dup $($rest)*)
311
+ };
312
+
313
+ // trailer expressions
314
+
315
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($call:tt)*) $($rest:tt)*) => {
316
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
317
+ };
318
+
319
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bracket:tt $($dup:tt)*) [$($index:tt)*] $($rest:tt)*) => {
320
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $bracket) $($parse)*} ($($rest)*) $($rest)*)
321
+ };
322
+
323
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($init:tt)*} $($rest:tt)*) => {
324
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
325
+ };
326
+
327
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($question:tt $($dup:tt)*) ? $($rest:tt)*) => {
328
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $question) $($parse)*} ($($rest)*) $($rest)*)
329
+ };
330
+
331
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $ident:tt $colons:tt $langle:tt $($dup:tt)*) . $i:ident :: < $($rest:tt)*) => {
332
+ $crate::__parse_ensure!(generic (atom $stack) $bail ($($fuel)*) {($($buf)* $dot $ident $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
333
+ };
334
+
335
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $ident:tt $colons:tt $langle:tt $($dup:tt)*) . $i:ident :: << $($rest:tt)*) => {
336
+ $crate::__parse_ensure!(type (qpath (tpath (arglist (atom $stack)))) $bail ($($fuel)*) {($($buf)* $dot $ident $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
337
+ };
338
+
339
+ (atom $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt . $i:ident :: <- - $($rest:tt)*) => {
340
+ $crate::__fallback_ensure!($($bail)*)
341
+ };
342
+
343
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $ident:tt $colons:tt $larrow:tt $($dup:tt)*) . $i:ident :: <- $lit:literal $($rest:tt)*) => {
344
+ $crate::__parse_ensure!(generic (atom $stack) $bail ($($fuel)*) {($($buf)* $dot $ident $colons $larrow) $($parse)*} ($($dup)*) $($dup)*)
345
+ };
346
+
347
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $field:tt $($dup:tt)*) . $i:ident $($rest:tt)*) => {
348
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $dot $field) $($parse)*} ($($rest)*) $($rest)*)
349
+ };
350
+
351
+ (atom $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt . - $($rest:tt)*) => {
352
+ $crate::__fallback_ensure!($($bail)*)
353
+ };
354
+
355
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $index:tt $($dup:tt)*) . $lit:literal $($rest:tt)*) => {
356
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $dot $index) $($parse)*} ($($rest)*) $($rest)*)
357
+ };
358
+
359
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($as:tt $($dup:tt)*) as $($rest:tt)*) => {
360
+ $crate::__parse_ensure!(type (atom $stack) $bail ($($fuel)*) {($($buf)* $as) $($parse)*} ($($rest)*) $($rest)*)
361
+ };
362
+
363
+ // types
364
+
365
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bracket:tt $($dup:tt)*) [$($content:tt)*] $($rest:tt)*) => {
366
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bracket) $($parse)*} ($($rest)*) $($rest)*)
367
+ };
368
+
369
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($content:tt)*) $($rest:tt)*) => {
370
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
371
+ };
372
+
373
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($star:tt $const:tt $($dup:tt)*) *const $($rest:tt)*) => {
374
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $star $const) $($parse)*} ($($rest)*) $($rest)*)
375
+ };
376
+
377
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($star:tt $mut:tt $($dup:tt)*) *mut $($rest:tt)*) => {
378
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $star $mut) $($parse)*} ($($rest)*) $($rest)*)
379
+ };
380
+
381
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $lifetime:tt $mut:tt $($dup:tt)*) & $l:lifetime mut $($rest:tt)*) => {
382
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $lifetime $mut) $($parse)*} ($($rest)*) $($rest)*)
383
+ };
384
+
385
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $mut:tt $($dup:tt)*) & mut $($rest:tt)*) => {
386
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $mut) $($parse)*} ($($rest)*) $($rest)*)
387
+ };
388
+
389
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $lifetime:tt $($dup:tt)*) & $l:lifetime $($rest:tt)*) => {
390
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $lifetime) $($parse)*} ($($rest)*) $($rest)*)
391
+ };
392
+
393
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) & $($rest:tt)*) => {
394
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
395
+ };
396
+
397
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $lifetime:tt $mut:tt $($dup:tt)*) && $l:lifetime mut $($rest:tt)*) => {
398
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $lifetime $mut) $($parse)*} ($($rest)*) $($rest)*)
399
+ };
400
+
401
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $mut:tt $($dup:tt)*) && mut $($rest:tt)*) => {
402
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $mut) $($parse)*} ($($rest)*) $($rest)*)
403
+ };
404
+
405
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $lifetime:tt $($dup:tt)*) && $l:lifetime $($rest:tt)*) => {
406
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $lifetime) $($parse)*} ($($rest)*) $($rest)*)
407
+ };
408
+
409
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) && $($rest:tt)*) => {
410
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
411
+ };
412
+
413
+ (type $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt unsafe extern - $($rest:tt)*) => {
414
+ $crate::__fallback_ensure!($($bail)*)
415
+ };
416
+
417
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($unsafe:tt $(extern $($abi:literal)?)? fn $($dup:tt)*) unsafe $($rest:tt)*) => {
418
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $unsafe) $($parse)*} ($($rest)*) $($rest)*)
419
+ };
420
+
421
+ (type $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt extern - $($rest:tt)*) => {
422
+ $crate::__fallback_ensure!($($bail)*)
423
+ };
424
+
425
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($extern:tt $abi:tt fn $($dup:tt)*) extern $lit:literal $($rest:tt)*) => {
426
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $extern $abi) $($parse)*} ($($rest)*) $($rest)*)
427
+ };
428
+
429
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($extern:tt fn $($dup:tt)*) extern $($rest:tt)*) => {
430
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $extern) $($parse)*} ($($rest)*) $($rest)*)
431
+ };
432
+
433
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($fn:tt $paren:tt $arrow:tt $($dup:tt)*) fn ($($args:tt)*) -> $($rest:tt)*) => {
434
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $fn $paren $arrow) $($parse)*} ($($rest)*) $($rest)*)
435
+ };
436
+
437
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($fn:tt $paren:tt $($dup:tt)*) fn ($($args:tt)*) $($rest:tt)*) => {
438
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $fn $paren) $($parse)*} ($($rest)*) $($rest)*)
439
+ };
440
+
441
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($impl:tt $($dup:tt)*) impl $($rest:tt)*) => {
442
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $impl) $($parse)*} ($($rest)*) $($rest)*)
443
+ };
444
+
445
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dyn:tt $($dup:tt)*) dyn $($rest:tt)*) => {
446
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $dyn) $($parse)*} ($($rest)*) $($rest)*)
447
+ };
448
+
449
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($wild:tt $($dup:tt)*) _ $($rest:tt)*) => {
450
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $wild) $($parse)*} ($($rest)*) $($rest)*)
451
+ };
452
+
453
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($never:tt $($dup:tt)*) ! $($rest:tt)*) => {
454
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $never) $($parse)*} ($($rest)*) $($rest)*)
455
+ };
456
+
457
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($for:tt $langle:tt $($dup:tt)*) for < $($rest:tt)*) => {
458
+ $crate::__parse_ensure!(generic (type $stack) $bail ($($fuel)*) {($($buf)* $for $langle) $($parse)*} ($($rest)*) $($rest)*)
459
+ };
460
+
461
+ // path types
462
+
463
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
464
+ $crate::__parse_ensure!(tpath $stack $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
465
+ };
466
+
467
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ident:tt $($dup:tt)*) $i:ident $($rest:tt)*) => {
468
+ $crate::__parse_ensure!(tpath $stack $bail ($($fuel)*) {($($buf)* $ident) $($parse)*} ($($rest)*) $($rest)*)
469
+ };
470
+
471
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) < $($rest:tt)*) => {
472
+ $crate::__parse_ensure!(type (qpath (tpath $stack)) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
473
+ };
474
+
475
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) < $($rest:tt)*) => {
476
+ $crate::__parse_ensure!(generic (tpath $stack) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
477
+ };
478
+
479
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) << $($rest:tt)*) => {
480
+ $crate::__parse_ensure!(type (qpath (tpath (arglist (tpath $stack)))) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
481
+ };
482
+
483
+ (tpath $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt <- - $($rest:tt)*) => {
484
+ $crate::__fallback_ensure!($($bail)*)
485
+ };
486
+
487
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($larrow:tt $($dup:tt)*) <- $lit:literal $($rest:tt)*) => {
488
+ $crate::__parse_ensure!(generic (tpath $stack) $bail ($($fuel)*) {($($buf)* $larrow) $($parse)*} ($($dup)*) $($dup)*)
489
+ };
490
+
491
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: < $($rest:tt)*) => {
492
+ $crate::__parse_ensure!(generic (tpath $stack) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
493
+ };
494
+
495
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: << $($rest:tt)*) => {
496
+ $crate::__parse_ensure!(type (qpath (tpath (arglist (tpath $stack)))) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
497
+ };
498
+
499
+ (tpath $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt :: <- - $($rest:tt)*) => {
500
+ $crate::__fallback_ensure!($($bail)*)
501
+ };
502
+
503
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $larrow:tt $($dup:tt)*) :: <- $lit:literal $($rest:tt)*) => {
504
+ $crate::__parse_ensure!(generic (tpath $stack) $bail ($($fuel)*) {($($buf)* $colons $larrow) $($parse)*} ($($dup)*) $($dup)*)
505
+ };
506
+
507
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
508
+ $crate::__parse_ensure!(tpath $stack $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
509
+ };
510
+
511
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $arrow:tt $($dup:tt)*) ($($args:tt)*) -> $($rest:tt)*) => {
512
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $paren $arrow) $($parse)*} ($($rest)*) $($rest)*)
513
+ };
514
+
515
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($args:tt)*) $($rest:tt)*) => {
516
+ $crate::__parse_ensure!(object $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
517
+ };
518
+
519
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $paren:tt $arrow:tt $($dup:tt)*) :: ($($args:tt)*) -> $($rest:tt)*) => {
520
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $colons $paren $arrow) $($parse)*} ($($rest)*) $($rest)*)
521
+ };
522
+
523
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $paren:tt $($dup:tt)*) :: ($($args:tt)*) $($rest:tt)*) => {
524
+ $crate::__parse_ensure!(object $stack $bail ($($fuel)*) {($($buf)* $colons $paren) $($parse)*} ($($rest)*) $($rest)*)
525
+ };
526
+
527
+ (tpath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! ($($mac:tt)*) $($rest:tt)*) => {
528
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
529
+ };
530
+
531
+ (tpath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! [$($mac:tt)*] $($rest:tt)*) => {
532
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
533
+ };
534
+
535
+ (tpath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! {$($mac:tt)*} $($rest:tt)*) => {
536
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
537
+ };
538
+
539
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
540
+ $crate::__parse_ensure!(object $stack $bail ($($fuel)*) $parse $dup $($rest)*)
541
+ };
542
+
543
+ // qualified paths
544
+
545
+ (qpath (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $colons:tt $ident:tt $($dup:tt)*) >> :: $i:ident $($rest:tt)*) => {
546
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
547
+ };
548
+
549
+ (qpath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $colons:tt $ident:tt $($dup:tt)*) > :: $i:ident $($rest:tt)*) => {
550
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
551
+ };
552
+
553
+ (qpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($as:tt $($dup:tt)*) as $($rest:tt)*) => {
554
+ $crate::__parse_ensure!(type (qpath $stack) $bail ($($fuel)*) {($($buf)* $as) $($parse)*} ($($rest)*) $($rest)*)
555
+ };
556
+
557
+ // trait objects
558
+
559
+ (object (arglist $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($plus:tt $colons:tt $ident:tt $($dup:tt)*) + :: $i:ident $($rest:tt)*) => {
560
+ $crate::__parse_ensure!(tpath (arglist $stack) $bail ($($fuel)*) {($($buf)* $plus $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
561
+ };
562
+
563
+ (object (arglist $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($plus:tt $ident:tt $($dup:tt)*) + $i:ident $($rest:tt)*) => {
564
+ $crate::__parse_ensure!(tpath (arglist $stack) $bail ($($fuel)*) {($($buf)* $plus $ident) $($parse)*} ($($rest)*) $($rest)*)
565
+ };
566
+
567
+ (object (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
568
+ $crate::__parse_ensure!($pop (split $stack) $bail ($($fuel)*) $parse $dup $($rest)*)
569
+ };
570
+
571
+ (object ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
572
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) $parse $dup $($rest)*)
573
+ };
574
+
575
+ // angle bracketed generic arguments
576
+
577
+ (generic (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
578
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle) $($parse)*} ($($rest)*) $($rest)*)
579
+ };
580
+
581
+ (generic ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) > $($rest:tt)*) => {
582
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle) $($parse)*} ($($rest)*) $($rest)*)
583
+ };
584
+
585
+ (generic ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
586
+ $crate::__parse_ensure!($pop (split $stack) $bail ($($fuel)*) {($($buf)*) $($parse)*} ($rangle $($rest)*) $rangle $($rest)*)
587
+ };
588
+
589
+ (generic $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt - - $($rest:tt)*) => {
590
+ $crate::__fallback_ensure!($($bail)*)
591
+ };
592
+
593
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($neg:tt $($dup:tt)*) - $lit:literal $($rest:tt)*) => {
594
+ $crate::__parse_ensure!(generic $stack $bail ($($fuel)*) {($($buf)* $neg) $($parse)*} ($($dup)*) $($dup)*)
595
+ };
596
+
597
+ (generic $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt - $($rest:tt)*) => {
598
+ $crate::__fallback_ensure!($($bail)*)
599
+ };
600
+
601
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($literal:tt $($dup:tt)*) $lit:literal $($rest:tt)*) => {
602
+ $crate::__parse_ensure!(arglist $stack $bail ($($fuel)*) {($($buf)* $literal) $($parse)*} ($($rest)*) $($rest)*)
603
+ };
604
+
605
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($block:tt)*} $($rest:tt)*) => {
606
+ $crate::__parse_ensure!(arglist $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
607
+ };
608
+
609
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($lifetime:tt $($dup:tt)*) $l:lifetime $($rest:tt)*) => {
610
+ $crate::__parse_ensure!(arglist $stack $bail ($($fuel)*) {($($buf)* $lifetime) $($parse)*} ($($rest)*) $($rest)*)
611
+ };
612
+
613
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($assoc:tt $eq:tt $($dup:tt)*) $ident:ident = $($rest:tt)*) => {
614
+ $crate::__parse_ensure!(type (arglist $stack) $bail ($($fuel)*) {($($buf)* $assoc $eq) $($parse)*} ($($rest)*) $($rest)*)
615
+ };
616
+
617
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
618
+ $crate::__parse_ensure!(type (arglist $stack) $bail ($($fuel)*) $parse $dup $($rest)*)
619
+ };
620
+
621
+ (arglist $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($comma:tt $($dup:tt)*) , $($rest:tt)*) => {
622
+ $crate::__parse_ensure!(generic $stack $bail ($($fuel)*) {($($buf)* $comma) $($parse)*} ($($rest)*) $($rest)*)
623
+ };
624
+
625
+ (arglist (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
626
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)*) $rangle $($parse)*} ($($rest)*) $($rest)*)
627
+ };
628
+
629
+ (arglist ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) > $($rest:tt)*) => {
630
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle) $($parse)*} ($($rest)*) $($rest)*)
631
+ };
632
+
633
+ (arglist ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
634
+ $crate::__parse_ensure!($pop (split $stack) $bail ($($fuel)*) {($($buf)*) $($parse)*} ($rangle $($rest)*) $rangle $($rest)*)
635
+ };
636
+
637
+ // patterns
638
+
639
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($pipe:tt $($dup:tt)*) | $($rest:tt)*) => {
640
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $pipe) $($parse)*} ($($rest)*) $($rest)*)
641
+ };
642
+
643
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($eq:tt $($dup:tt)*) = $($rest:tt)*) => {
644
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $eq) $($parse)*} ($($rest)*) $($rest)*)
645
+ };
646
+
647
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($in:tt $($dup:tt)*) in $($rest:tt)*) => {
648
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $in) $($parse)*} ($($rest)*) $($rest)*)
649
+ };
650
+
651
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ref:tt $($dup:tt)*) ref $($rest:tt)*) => {
652
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $ref) $($parse)*} ($($rest)*) $($rest)*)
653
+ };
654
+
655
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($mut:tt $($dup:tt)*) mut $($rest:tt)*) => {
656
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $mut) $($parse)*} ($($rest)*) $($rest)*)
657
+ };
658
+
659
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($at:tt $($dup:tt)*) @ $($rest:tt)*) => {
660
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $at) $($parse)*} ($($rest)*) $($rest)*)
661
+ };
662
+
663
+ (pat $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt - - $($rest:tt)*) => {
664
+ $crate::__fallback_ensure!($($bail)*)
665
+ };
666
+
667
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($neg:tt $($dup:tt)*) - $lit:literal $($rest:tt)*) => {
668
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $neg) $($parse)*} ($($dup)*) $($dup)*)
669
+ };
670
+
671
+ (pat $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt - $($rest:tt)*) => {
672
+ $crate::__fallback_ensure!($($bail)*)
673
+ };
674
+
675
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($literal:tt $($dup:tt)*) $lit:literal $($rest:tt)*) => {
676
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $literal) $($parse)*} ($($rest)*) $($rest)*)
677
+ };
678
+
679
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($range:tt $($dup:tt)*) .. $($rest:tt)*) => {
680
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $range) $($parse)*} ($($rest)*) $($rest)*)
681
+ };
682
+
683
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($range:tt $($dup:tt)*) ..= $($rest:tt)*) => {
684
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $range) $($parse)*} ($($rest)*) $($rest)*)
685
+ };
686
+
687
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) & $($rest:tt)*) => {
688
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
689
+ };
690
+
691
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $($dup:tt)*) && $($rest:tt)*) => {
692
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $andand) $($parse)*} ($($rest)*) $($rest)*)
693
+ };
694
+
695
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($content:tt)*) $($rest:tt)*) => {
696
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
697
+ };
698
+
699
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bracket:tt $($dup:tt)*) [$($content:tt)*] $($rest:tt)*) => {
700
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $bracket) $($parse)*} ($($rest)*) $($rest)*)
701
+ };
702
+
703
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($content:tt)*} $($rest:tt)*) => {
704
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
705
+ };
706
+
707
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($wild:tt $($dup:tt)*) _ $($rest:tt)*) => {
708
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $wild) $($parse)*} ($($rest)*) $($rest)*)
709
+ };
710
+
711
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
712
+ $crate::__parse_ensure!(epath (pat $stack) $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
713
+ };
714
+
715
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ident:tt $($dup:tt)*) $i:ident $($rest:tt)*) => {
716
+ $crate::__parse_ensure!(epath (pat $stack) $bail ($($fuel)*) {($($buf)* $ident) $($parse)*} ($($rest)*) $($rest)*)
717
+ };
718
+
719
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) < $($rest:tt)*) => {
720
+ $crate::__parse_ensure!(type (qpath (epath (pat $stack))) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
721
+ };
722
+
723
+ // comparison binary operators
724
+
725
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($eq:tt $($dup:tt)*) == $($rest:tt)*) => {
726
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $eq} ($($rest)*) $($rest)*)
727
+ };
728
+
729
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($eq:tt $($dup:tt)*) == $($rest:tt)*) => {
730
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $eq) $($parse)*} ($($rest)*) $($rest)*)
731
+ };
732
+
733
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($le:tt $($dup:tt)*) <= $($rest:tt)*) => {
734
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $le} ($($rest)*) $($rest)*)
735
+ };
736
+
737
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($le:tt $($dup:tt)*) <= $($rest:tt)*) => {
738
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $le) $($parse)*} ($($rest)*) $($rest)*)
739
+ };
740
+
741
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($lt:tt $($dup:tt)*) < $($rest:tt)*) => {
742
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $lt} ($($rest)*) $($rest)*)
743
+ };
744
+
745
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($lt:tt $($dup:tt)*) < $($rest:tt)*) => {
746
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $lt) $($parse)*} ($($rest)*) $($rest)*)
747
+ };
748
+
749
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ne:tt $($dup:tt)*) != $($rest:tt)*) => {
750
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $ne} ($($rest)*) $($rest)*)
751
+ };
752
+
753
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($ne:tt $($dup:tt)*) != $($rest:tt)*) => {
754
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $ne) $($parse)*} ($($rest)*) $($rest)*)
755
+ };
756
+
757
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ge:tt $($dup:tt)*) >= $($rest:tt)*) => {
758
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $ge} ($($rest)*) $($rest)*)
759
+ };
760
+
761
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($ge:tt $($dup:tt)*) >= $($rest:tt)*) => {
762
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $ge) $($parse)*} ($($rest)*) $($rest)*)
763
+ };
764
+
765
+ (atom (split ()) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt >> $($rest:tt)*) => {
766
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)* > ) > } ($($rest)*) $($rest)*)
767
+ };
768
+
769
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($gt:tt $($dup:tt)*) > $($rest:tt)*) => {
770
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $gt} ($($rest)*) $($rest)*)
771
+ };
772
+
773
+ (atom (split $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
774
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $rangle) $($parse)*} ($($rest)*) $($rest)*)
775
+ };
776
+
777
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($gt:tt $($dup:tt)*) > $($rest:tt)*) => {
778
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $gt) $($parse)*} ($($rest)*) $($rest)*)
779
+ };
780
+
781
+ // high precedence binary operators
782
+
783
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($add:tt $($dup:tt)*) + $($rest:tt)*) => {
784
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $add) $($parse)*} ($($rest)*) $($rest)*)
785
+ };
786
+
787
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($sub:tt $($dup:tt)*) - $($rest:tt)*) => {
788
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $sub) $($parse)*} ($($rest)*) $($rest)*)
789
+ };
790
+
791
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($mul:tt $($dup:tt)*) * $($rest:tt)*) => {
792
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $mul) $($parse)*} ($($rest)*) $($rest)*)
793
+ };
794
+
795
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($div:tt $($dup:tt)*) / $($rest:tt)*) => {
796
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $div) $($parse)*} ($($rest)*) $($rest)*)
797
+ };
798
+
799
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rem:tt $($dup:tt)*) % $($rest:tt)*) => {
800
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $rem) $($parse)*} ($($rest)*) $($rest)*)
801
+ };
802
+
803
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitxor:tt $($dup:tt)*) ^ $($rest:tt)*) => {
804
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $bitxor) $($parse)*} ($($rest)*) $($rest)*)
805
+ };
806
+
807
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitand:tt $($dup:tt)*) & $($rest:tt)*) => {
808
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $bitand) $($parse)*} ($($rest)*) $($rest)*)
809
+ };
810
+
811
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitor:tt $($dup:tt)*) | $($rest:tt)*) => {
812
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $bitor) $($parse)*} ($($rest)*) $($rest)*)
813
+ };
814
+
815
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($shl:tt $($dup:tt)*) << $($rest:tt)*) => {
816
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $shl) $($parse)*} ($($rest)*) $($rest)*)
817
+ };
818
+
819
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($shr:tt $($dup:tt)*) >> $($rest:tt)*) => {
820
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $shr) $($parse)*} ($($rest)*) $($rest)*)
821
+ };
822
+
823
+ // low precedence binary operators
824
+
825
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) && $($rest:tt)*) => {
826
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
827
+ };
828
+
829
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($or:tt $($dup:tt)*) || $($rest:tt)*) => {
830
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $or) $($parse)*} ($($rest)*) $($rest)*)
831
+ };
832
+
833
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($assign:tt $($dup:tt)*) = $($rest:tt)*) => {
834
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $assign) $($parse)*} ($($rest)*) $($rest)*)
835
+ };
836
+
837
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($addeq:tt $($dup:tt)*) += $($rest:tt)*) => {
838
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $addeq) $($parse)*} ($($rest)*) $($rest)*)
839
+ };
840
+
841
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($subeq:tt $($dup:tt)*) -= $($rest:tt)*) => {
842
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $subeq) $($parse)*} ($($rest)*) $($rest)*)
843
+ };
844
+
845
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($muleq:tt $($dup:tt)*) *= $($rest:tt)*) => {
846
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $muleq) $($parse)*} ($($rest)*) $($rest)*)
847
+ };
848
+
849
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($diveq:tt $($dup:tt)*) /= $($rest:tt)*) => {
850
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $diveq) $($parse)*} ($($rest)*) $($rest)*)
851
+ };
852
+
853
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($remeq:tt $($dup:tt)*) %= $($rest:tt)*) => {
854
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $remeq) $($parse)*} ($($rest)*) $($rest)*)
855
+ };
856
+
857
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitxoreq:tt $($dup:tt)*) ^= $($rest:tt)*) => {
858
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $bitxoreq) $($parse)*} ($($rest)*) $($rest)*)
859
+ };
860
+
861
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitandeq:tt $($dup:tt)*) &= $($rest:tt)*) => {
862
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $bitandeq) $($parse)*} ($($rest)*) $($rest)*)
863
+ };
864
+
865
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitoreq:tt $($dup:tt)*) |= $($rest:tt)*) => {
866
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $bitoreq) $($parse)*} ($($rest)*) $($rest)*)
867
+ };
868
+
869
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($shleq:tt $($dup:tt)*) <<= $($rest:tt)*) => {
870
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $shleq) $($parse)*} ($($rest)*) $($rest)*)
871
+ };
872
+
873
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($shreq:tt $($dup:tt)*) >>= $($rest:tt)*) => {
874
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $shreq) $($parse)*} ($($rest)*) $($rest)*)
875
+ };
876
+
877
+ // unrecognized expression
878
+
879
+ ($state:tt $stack:tt ($($bail:tt)*) $($rest:tt)*) => {
880
+ $crate::__fallback_ensure!($($bail)*)
881
+ };
882
+ }
883
+
884
+ #[doc(hidden)]
885
+ #[macro_export]
886
+ macro_rules! __fancy_ensure {
887
+ ($lhs:expr, $op:tt, $rhs:expr) => {
888
+ match (&$lhs, &$rhs) {
889
+ (lhs, rhs) => {
890
+ if !(lhs $op rhs) {
891
+ #[allow(unused_imports)]
892
+ use $crate::__private::{BothDebug, NotBothDebug};
893
+ return Err((lhs, rhs).__dispatch_ensure(
894
+ $crate::__private::concat!(
895
+ "Condition failed: `",
896
+ $crate::__private::stringify!($lhs),
897
+ " ",
898
+ $crate::__private::stringify!($op),
899
+ " ",
900
+ $crate::__private::stringify!($rhs),
901
+ "`",
902
+ ),
903
+ ));
904
+ }
905
+ }
906
+ }
907
+ };
908
+ }
909
+
910
+ #[doc(hidden)]
911
+ #[macro_export]
912
+ macro_rules! __fallback_ensure {
913
+ ($cond:expr $(,)?) => {
914
+ if $crate::__private::not($cond) {
915
+ return $crate::__private::Err($crate::Error::msg(
916
+ $crate::__private::concat!("Condition failed: `", $crate::__private::stringify!($cond), "`")
917
+ ));
918
+ }
919
+ };
920
+ ($cond:expr, $msg:literal $(,)?) => {
921
+ if $crate::__private::not($cond) {
922
+ return $crate::__private::Err($crate::__anyhow!($msg));
923
+ }
924
+ };
925
+ ($cond:expr, $err:expr $(,)?) => {
926
+ if $crate::__private::not($cond) {
927
+ return $crate::__private::Err($crate::__anyhow!($err));
928
+ }
929
+ };
930
+ ($cond:expr, $fmt:expr, $($arg:tt)*) => {
931
+ if $crate::__private::not($cond) {
932
+ return $crate::__private::Err($crate::__anyhow!($fmt, $($arg)*));
933
+ }
934
+ };
935
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/error.rs ADDED
@@ -0,0 +1,1086 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::backtrace::Backtrace;
2
+ use crate::chain::Chain;
3
+ #[cfg(error_generic_member_access)]
4
+ use crate::nightly::{self, Request};
5
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
6
+ use crate::ptr::Mut;
7
+ use crate::ptr::{Own, Ref};
8
+ use crate::{Error, StdError};
9
+ use alloc::boxed::Box;
10
+ use core::any::TypeId;
11
+ use core::fmt::{self, Debug, Display};
12
+ use core::mem::ManuallyDrop;
13
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
14
+ use core::ops::{Deref, DerefMut};
15
+ use core::panic::{RefUnwindSafe, UnwindSafe};
16
+ use core::ptr;
17
+ use core::ptr::NonNull;
18
+
19
+ impl Error {
20
+ /// Create a new error object from any error type.
21
+ ///
22
+ /// The error type must be threadsafe and `'static`, so that the `Error`
23
+ /// will be as well.
24
+ ///
25
+ /// If the error type does not provide a backtrace, a backtrace will be
26
+ /// created here to ensure that a backtrace exists.
27
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
28
+ #[cold]
29
+ #[must_use]
30
+ pub fn new<E>(error: E) -> Self
31
+ where
32
+ E: StdError + Send + Sync + 'static,
33
+ {
34
+ let backtrace = backtrace_if_absent!(&error);
35
+ Error::construct_from_std(error, backtrace)
36
+ }
37
+
38
+ /// Create a new error object from a printable error message.
39
+ ///
40
+ /// If the argument implements std::error::Error, prefer `Error::new`
41
+ /// instead which preserves the underlying error's cause chain and
42
+ /// backtrace. If the argument may or may not implement std::error::Error
43
+ /// now or in the future, use `anyhow!(err)` which handles either way
44
+ /// correctly.
45
+ ///
46
+ /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally
47
+ /// convenient in places where a function is preferable over a macro, such
48
+ /// as iterator or stream combinators:
49
+ ///
50
+ /// ```
51
+ /// # mod ffi {
52
+ /// # pub struct Input;
53
+ /// # pub struct Output;
54
+ /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {
55
+ /// # unimplemented!()
56
+ /// # }
57
+ /// # }
58
+ /// #
59
+ /// # use ffi::{Input, Output};
60
+ /// #
61
+ /// use anyhow::{Error, Result};
62
+ /// use futures::stream::{Stream, StreamExt, TryStreamExt};
63
+ ///
64
+ /// async fn demo<S>(stream: S) -> Result<Vec<Output>>
65
+ /// where
66
+ /// S: Stream<Item = Input>,
67
+ /// {
68
+ /// stream
69
+ /// .then(ffi::do_some_work) // returns Result<Output, &str>
70
+ /// .map_err(Error::msg)
71
+ /// .try_collect()
72
+ /// .await
73
+ /// }
74
+ /// ```
75
+ #[cold]
76
+ #[must_use]
77
+ pub fn msg<M>(message: M) -> Self
78
+ where
79
+ M: Display + Debug + Send + Sync + 'static,
80
+ {
81
+ Error::construct_from_adhoc(message, backtrace!())
82
+ }
83
+
84
+ /// Construct an error object from a type-erased standard library error.
85
+ ///
86
+ /// This is mostly useful for interop with other error libraries.
87
+ ///
88
+ /// # Example
89
+ ///
90
+ /// Here is a skeleton of a library that provides its own error abstraction.
91
+ /// The pair of `From` impls provide bidirectional support for `?`
92
+ /// conversion between `Report` and `anyhow::Error`.
93
+ ///
94
+ /// ```
95
+ /// use std::error::Error as StdError;
96
+ ///
97
+ /// pub struct Report {/* ... */}
98
+ ///
99
+ /// impl<E> From<E> for Report
100
+ /// where
101
+ /// E: Into<anyhow::Error>,
102
+ /// Result<(), E>: anyhow::Context<(), E>,
103
+ /// {
104
+ /// fn from(error: E) -> Self {
105
+ /// let anyhow_error: anyhow::Error = error.into();
106
+ /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = anyhow_error.into();
107
+ /// Report::from_boxed(boxed_error)
108
+ /// }
109
+ /// }
110
+ ///
111
+ /// impl From<Report> for anyhow::Error {
112
+ /// fn from(report: Report) -> Self {
113
+ /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = report.into_boxed();
114
+ /// anyhow::Error::from_boxed(boxed_error)
115
+ /// }
116
+ /// }
117
+ ///
118
+ /// impl Report {
119
+ /// fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {
120
+ /// todo!()
121
+ /// }
122
+ /// fn into_boxed(self) -> Box<dyn StdError + Send + Sync + 'static> {
123
+ /// todo!()
124
+ /// }
125
+ /// }
126
+ ///
127
+ /// // Example usage: can use `?` in both directions.
128
+ /// fn a() -> anyhow::Result<()> {
129
+ /// b()?;
130
+ /// Ok(())
131
+ /// }
132
+ /// fn b() -> Result<(), Report> {
133
+ /// a()?;
134
+ /// Ok(())
135
+ /// }
136
+ /// ```
137
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
138
+ #[cold]
139
+ #[must_use]
140
+ pub fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {
141
+ let backtrace = backtrace_if_absent!(&*boxed_error);
142
+ Error::construct_from_boxed(boxed_error, backtrace)
143
+ }
144
+
145
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
146
+ #[cold]
147
+ pub(crate) fn construct_from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self
148
+ where
149
+ E: StdError + Send + Sync + 'static,
150
+ {
151
+ let vtable = &ErrorVTable {
152
+ object_drop: object_drop::<E>,
153
+ object_ref: object_ref::<E>,
154
+ object_boxed: object_boxed::<E>,
155
+ object_reallocate_boxed: object_reallocate_boxed::<E>,
156
+ object_downcast: object_downcast::<E>,
157
+ object_drop_rest: object_drop_front::<E>,
158
+ #[cfg(all(
159
+ not(error_generic_member_access),
160
+ any(std_backtrace, feature = "backtrace")
161
+ ))]
162
+ object_backtrace: no_backtrace,
163
+ };
164
+
165
+ // Safety: passing vtable that operates on the right type E.
166
+ unsafe { Error::construct(error, vtable, backtrace) }
167
+ }
168
+
169
+ #[cold]
170
+ pub(crate) fn construct_from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self
171
+ where
172
+ M: Display + Debug + Send + Sync + 'static,
173
+ {
174
+ use crate::wrapper::MessageError;
175
+ let error: MessageError<M> = MessageError(message);
176
+ let vtable = &ErrorVTable {
177
+ object_drop: object_drop::<MessageError<M>>,
178
+ object_ref: object_ref::<MessageError<M>>,
179
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
180
+ object_boxed: object_boxed::<MessageError<M>>,
181
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
182
+ object_reallocate_boxed: object_reallocate_boxed::<MessageError<M>>,
183
+ object_downcast: object_downcast::<M>,
184
+ object_drop_rest: object_drop_front::<M>,
185
+ #[cfg(all(
186
+ not(error_generic_member_access),
187
+ any(std_backtrace, feature = "backtrace")
188
+ ))]
189
+ object_backtrace: no_backtrace,
190
+ };
191
+
192
+ // Safety: MessageError is repr(transparent) so it is okay for the
193
+ // vtable to allow casting the MessageError<M> to M.
194
+ unsafe { Error::construct(error, vtable, backtrace) }
195
+ }
196
+
197
+ #[cold]
198
+ pub(crate) fn construct_from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self
199
+ where
200
+ M: Display + Send + Sync + 'static,
201
+ {
202
+ use crate::wrapper::DisplayError;
203
+ let error: DisplayError<M> = DisplayError(message);
204
+ let vtable = &ErrorVTable {
205
+ object_drop: object_drop::<DisplayError<M>>,
206
+ object_ref: object_ref::<DisplayError<M>>,
207
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
208
+ object_boxed: object_boxed::<DisplayError<M>>,
209
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
210
+ object_reallocate_boxed: object_reallocate_boxed::<DisplayError<M>>,
211
+ object_downcast: object_downcast::<M>,
212
+ object_drop_rest: object_drop_front::<M>,
213
+ #[cfg(all(
214
+ not(error_generic_member_access),
215
+ any(std_backtrace, feature = "backtrace")
216
+ ))]
217
+ object_backtrace: no_backtrace,
218
+ };
219
+
220
+ // Safety: DisplayError is repr(transparent) so it is okay for the
221
+ // vtable to allow casting the DisplayError<M> to M.
222
+ unsafe { Error::construct(error, vtable, backtrace) }
223
+ }
224
+
225
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
226
+ #[cold]
227
+ pub(crate) fn construct_from_context<C, E>(
228
+ context: C,
229
+ error: E,
230
+ backtrace: Option<Backtrace>,
231
+ ) -> Self
232
+ where
233
+ C: Display + Send + Sync + 'static,
234
+ E: StdError + Send + Sync + 'static,
235
+ {
236
+ let error: ContextError<C, E> = ContextError { context, error };
237
+
238
+ let vtable = &ErrorVTable {
239
+ object_drop: object_drop::<ContextError<C, E>>,
240
+ object_ref: object_ref::<ContextError<C, E>>,
241
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
242
+ object_boxed: object_boxed::<ContextError<C, E>>,
243
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
244
+ object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, E>>,
245
+ object_downcast: context_downcast::<C, E>,
246
+ object_drop_rest: context_drop_rest::<C, E>,
247
+ #[cfg(all(
248
+ not(error_generic_member_access),
249
+ any(std_backtrace, feature = "backtrace")
250
+ ))]
251
+ object_backtrace: no_backtrace,
252
+ };
253
+
254
+ // Safety: passing vtable that operates on the right type.
255
+ unsafe { Error::construct(error, vtable, backtrace) }
256
+ }
257
+
258
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
259
+ #[cold]
260
+ pub(crate) fn construct_from_boxed(
261
+ error: Box<dyn StdError + Send + Sync>,
262
+ backtrace: Option<Backtrace>,
263
+ ) -> Self {
264
+ use crate::wrapper::BoxedError;
265
+ let error = BoxedError(error);
266
+ let vtable = &ErrorVTable {
267
+ object_drop: object_drop::<BoxedError>,
268
+ object_ref: object_ref::<BoxedError>,
269
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
270
+ object_boxed: object_boxed::<BoxedError>,
271
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
272
+ object_reallocate_boxed: object_reallocate_boxed::<BoxedError>,
273
+ object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,
274
+ object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,
275
+ #[cfg(all(
276
+ not(error_generic_member_access),
277
+ any(std_backtrace, feature = "backtrace")
278
+ ))]
279
+ object_backtrace: no_backtrace,
280
+ };
281
+
282
+ // Safety: BoxedError is repr(transparent) so it is okay for the vtable
283
+ // to allow casting to Box<dyn StdError + Send + Sync>.
284
+ unsafe { Error::construct(error, vtable, backtrace) }
285
+ }
286
+
287
+ // Takes backtrace as argument rather than capturing it here so that the
288
+ // user sees one fewer layer of wrapping noise in the backtrace.
289
+ //
290
+ // Unsafe because the given vtable must have sensible behavior on the error
291
+ // value of type E.
292
+ #[cold]
293
+ unsafe fn construct<E>(
294
+ error: E,
295
+ vtable: &'static ErrorVTable,
296
+ backtrace: Option<Backtrace>,
297
+ ) -> Self
298
+ where
299
+ E: StdError + Send + Sync + 'static,
300
+ {
301
+ let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {
302
+ vtable,
303
+ backtrace,
304
+ _object: error,
305
+ });
306
+ // Erase the concrete type of E from the compile-time type system. This
307
+ // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to
308
+ // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the
309
+ // result is a thin pointer. The necessary behavior for manipulating the
310
+ // underlying ErrorImpl<E> is preserved in the vtable provided by the
311
+ // caller rather than a builtin fat pointer vtable.
312
+ let inner = Own::new(inner).cast::<ErrorImpl>();
313
+ Error { inner }
314
+ }
315
+
316
+ /// Wrap the error value with additional context.
317
+ ///
318
+ /// For attaching context to a `Result` as it is propagated, the
319
+ /// [`Context`][crate::Context] extension trait may be more convenient than
320
+ /// this function.
321
+ ///
322
+ /// The primary reason to use `error.context(...)` instead of
323
+ /// `result.context(...)` via the `Context` trait would be if the context
324
+ /// needs to depend on some data held by the underlying error:
325
+ ///
326
+ /// ```
327
+ /// # use std::fmt::{self, Debug, Display};
328
+ /// #
329
+ /// # type T = ();
330
+ /// #
331
+ /// # impl std::error::Error for ParseError {}
332
+ /// # impl Debug for ParseError {
333
+ /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
334
+ /// # unimplemented!()
335
+ /// # }
336
+ /// # }
337
+ /// # impl Display for ParseError {
338
+ /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
339
+ /// # unimplemented!()
340
+ /// # }
341
+ /// # }
342
+ /// #
343
+ /// use anyhow::Result;
344
+ /// use std::fs::File;
345
+ /// use std::path::Path;
346
+ ///
347
+ /// struct ParseError {
348
+ /// line: usize,
349
+ /// column: usize,
350
+ /// }
351
+ ///
352
+ /// fn parse_impl(file: File) -> Result<T, ParseError> {
353
+ /// # const IGNORE: &str = stringify! {
354
+ /// ...
355
+ /// # };
356
+ /// # unimplemented!()
357
+ /// }
358
+ ///
359
+ /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {
360
+ /// let file = File::open(&path)?;
361
+ /// parse_impl(file).map_err(|error| {
362
+ /// let context = format!(
363
+ /// "only the first {} lines of {} are valid",
364
+ /// error.line, path.as_ref().display(),
365
+ /// );
366
+ /// anyhow::Error::new(error).context(context)
367
+ /// })
368
+ /// }
369
+ /// ```
370
+ #[cold]
371
+ #[must_use]
372
+ pub fn context<C>(self, context: C) -> Self
373
+ where
374
+ C: Display + Send + Sync + 'static,
375
+ {
376
+ let error: ContextError<C, Error> = ContextError {
377
+ context,
378
+ error: self,
379
+ };
380
+
381
+ let vtable = &ErrorVTable {
382
+ object_drop: object_drop::<ContextError<C, Error>>,
383
+ object_ref: object_ref::<ContextError<C, Error>>,
384
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
385
+ object_boxed: object_boxed::<ContextError<C, Error>>,
386
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
387
+ object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, Error>>,
388
+ object_downcast: context_chain_downcast::<C>,
389
+ object_drop_rest: context_chain_drop_rest::<C>,
390
+ #[cfg(all(
391
+ not(error_generic_member_access),
392
+ any(std_backtrace, feature = "backtrace")
393
+ ))]
394
+ object_backtrace: context_backtrace::<C>,
395
+ };
396
+
397
+ // As the cause is anyhow::Error, we already have a backtrace for it.
398
+ let backtrace = None;
399
+
400
+ // Safety: passing vtable that operates on the right type.
401
+ unsafe { Error::construct(error, vtable, backtrace) }
402
+ }
403
+
404
+ /// Get the backtrace for this Error.
405
+ ///
406
+ /// In order for the backtrace to be meaningful, one of the two environment
407
+ /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined
408
+ /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat
409
+ /// expensive to capture in Rust, so we don't necessarily want to be
410
+ /// capturing them all over the place all the time.
411
+ ///
412
+ /// - If you want panics and errors to both have backtraces, set
413
+ /// `RUST_BACKTRACE=1`;
414
+ /// - If you want only errors to have backtraces, set
415
+ /// `RUST_LIB_BACKTRACE=1`;
416
+ /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and
417
+ /// `RUST_LIB_BACKTRACE=0`.
418
+ ///
419
+ /// # Stability
420
+ ///
421
+ /// Standard library backtraces are only available when using Rust &ge;
422
+ /// 1.65. On older compilers, this function is only available if the crate's
423
+ /// "backtrace" feature is enabled, and will use the `backtrace` crate as
424
+ /// the underlying backtrace implementation. The return type of this
425
+ /// function on old compilers is `&(impl Debug + Display)`.
426
+ ///
427
+ /// ```toml
428
+ /// [dependencies]
429
+ /// anyhow = { version = "1.0", features = ["backtrace"] }
430
+ /// ```
431
+ #[cfg(any(std_backtrace, feature = "backtrace"))]
432
+ pub fn backtrace(&self) -> &impl_backtrace!() {
433
+ unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }
434
+ }
435
+
436
+ /// An iterator of the chain of source errors contained by this Error.
437
+ ///
438
+ /// This iterator will visit every error in the cause chain of this error
439
+ /// object, beginning with the error that this error object was created
440
+ /// from.
441
+ ///
442
+ /// # Example
443
+ ///
444
+ /// ```
445
+ /// use anyhow::Error;
446
+ /// use std::io;
447
+ ///
448
+ /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
449
+ /// for cause in error.chain() {
450
+ /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {
451
+ /// return Some(io_error.kind());
452
+ /// }
453
+ /// }
454
+ /// None
455
+ /// }
456
+ /// ```
457
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
458
+ #[cold]
459
+ pub fn chain(&self) -> Chain {
460
+ unsafe { ErrorImpl::chain(self.inner.by_ref()) }
461
+ }
462
+
463
+ /// The lowest level cause of this error &mdash; this error's cause's
464
+ /// cause's cause etc.
465
+ ///
466
+ /// The root cause is the last error in the iterator produced by
467
+ /// [`chain()`][Error::chain].
468
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
469
+ #[allow(clippy::double_ended_iterator_last)]
470
+ pub fn root_cause(&self) -> &(dyn StdError + 'static) {
471
+ self.chain().last().unwrap()
472
+ }
473
+
474
+ /// Returns true if `E` is the type held by this error object.
475
+ ///
476
+ /// For errors with context, this method returns true if `E` matches the
477
+ /// type of the context `C` **or** the type of the error on which the
478
+ /// context has been attached. For details about the interaction between
479
+ /// context and downcasting, [see here].
480
+ ///
481
+ /// [see here]: crate::Context#effect-on-downcasting
482
+ pub fn is<E>(&self) -> bool
483
+ where
484
+ E: Display + Debug + Send + Sync + 'static,
485
+ {
486
+ self.downcast_ref::<E>().is_some()
487
+ }
488
+
489
+ /// Attempt to downcast the error object to a concrete type.
490
+ pub fn downcast<E>(mut self) -> Result<E, Self>
491
+ where
492
+ E: Display + Debug + Send + Sync + 'static,
493
+ {
494
+ let target = TypeId::of::<E>();
495
+ let inner = self.inner.by_mut();
496
+ unsafe {
497
+ // Use vtable to find NonNull<()> which points to a value of type E
498
+ // somewhere inside the data structure.
499
+ let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {
500
+ Some(addr) => addr.by_mut().extend(),
501
+ None => return Err(self),
502
+ };
503
+
504
+ // Prepare to read E out of the data structure. We'll drop the rest
505
+ // of the data structure separately so that E is not dropped.
506
+ let outer = ManuallyDrop::new(self);
507
+
508
+ // Read E from where the vtable found it.
509
+ let error = addr.cast::<E>().read();
510
+
511
+ // Drop rest of the data structure outside of E.
512
+ (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);
513
+
514
+ Ok(error)
515
+ }
516
+ }
517
+
518
+ /// Downcast this error object by reference.
519
+ ///
520
+ /// # Example
521
+ ///
522
+ /// ```
523
+ /// # use anyhow::anyhow;
524
+ /// # use std::fmt::{self, Display};
525
+ /// # use std::task::Poll;
526
+ /// #
527
+ /// # #[derive(Debug)]
528
+ /// # enum DataStoreError {
529
+ /// # Censored(()),
530
+ /// # }
531
+ /// #
532
+ /// # impl Display for DataStoreError {
533
+ /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
534
+ /// # unimplemented!()
535
+ /// # }
536
+ /// # }
537
+ /// #
538
+ /// # impl std::error::Error for DataStoreError {}
539
+ /// #
540
+ /// # const REDACTED_CONTENT: () = ();
541
+ /// #
542
+ /// # let error = anyhow!("...");
543
+ /// # let root_cause = &error;
544
+ /// #
545
+ /// # let ret =
546
+ /// // If the error was caused by redaction, then return a tombstone instead
547
+ /// // of the content.
548
+ /// match root_cause.downcast_ref::<DataStoreError>() {
549
+ /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),
550
+ /// None => Err(error),
551
+ /// }
552
+ /// # ;
553
+ /// ```
554
+ pub fn downcast_ref<E>(&self) -> Option<&E>
555
+ where
556
+ E: Display + Debug + Send + Sync + 'static,
557
+ {
558
+ let target = TypeId::of::<E>();
559
+ unsafe {
560
+ // Use vtable to find NonNull<()> which points to a value of type E
561
+ // somewhere inside the data structure.
562
+ let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;
563
+ Some(addr.cast::<E>().deref())
564
+ }
565
+ }
566
+
567
+ /// Downcast this error object by mutable reference.
568
+ pub fn downcast_mut<E>(&mut self) -> Option<&mut E>
569
+ where
570
+ E: Display + Debug + Send + Sync + 'static,
571
+ {
572
+ let target = TypeId::of::<E>();
573
+ unsafe {
574
+ // Use vtable to find NonNull<()> which points to a value of type E
575
+ // somewhere inside the data structure.
576
+ let addr =
577
+ (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();
578
+ Some(addr.cast::<E>().deref_mut())
579
+ }
580
+ }
581
+
582
+ /// Convert to a standard library error trait object.
583
+ ///
584
+ /// This is implemented as a cheap pointer cast that does not allocate or
585
+ /// deallocate memory. Like [`anyhow::Error::from_boxed`], it's useful for
586
+ /// interop with other error libraries.
587
+ ///
588
+ /// The same conversion is also available as
589
+ /// <code style="display:inline;white-space:normal;">impl From&lt;anyhow::Error&gt;
590
+ /// for Box&lt;dyn Error + Send + Sync + &apos;static&gt;</code>.
591
+ ///
592
+ /// If a backtrace was collected during construction of the `anyhow::Error`,
593
+ /// that backtrace remains accessible using the standard library `Error`
594
+ /// trait's provider API, but as a consequence, the resulting boxed error
595
+ /// can no longer be downcast to its original underlying type.
596
+ ///
597
+ /// ```
598
+ #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify! {")]
599
+ /// #![feature(error_generic_member_access)]
600
+ ///
601
+ /// use anyhow::anyhow;
602
+ /// use std::backtrace::Backtrace;
603
+ /// use thiserror::Error;
604
+ ///
605
+ /// #[derive(Error, Debug)]
606
+ /// #[error("...")]
607
+ /// struct MyError;
608
+ ///
609
+ /// let anyhow_error = anyhow!(MyError);
610
+ /// println!("{}", anyhow_error.backtrace()); // has Backtrace
611
+ /// assert!(anyhow_error.downcast_ref::<MyError>().is_some()); // can downcast
612
+ ///
613
+ /// let boxed_dyn_error = anyhow_error.into_boxed_dyn_error();
614
+ /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_some()); // has Backtrace
615
+ /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_none()); // can no longer downcast
616
+ #[cfg_attr(not(error_generic_member_access), doc = "# };")]
617
+ /// ```
618
+ ///
619
+ /// [`anyhow::Error::from_boxed`]: Self::from_boxed
620
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
621
+ #[must_use]
622
+ pub fn into_boxed_dyn_error(self) -> Box<dyn StdError + Send + Sync + 'static> {
623
+ let outer = ManuallyDrop::new(self);
624
+ unsafe {
625
+ // Use vtable to attach ErrorImpl<E>'s native StdError vtable for
626
+ // the right original type E.
627
+ (vtable(outer.inner.ptr).object_boxed)(outer.inner)
628
+ }
629
+ }
630
+
631
+ /// Convert to a standard library error trait object.
632
+ ///
633
+ /// Unlike `self.into_boxed_dyn_error()`, this method relocates the
634
+ /// underlying error into a new allocation in order to make it downcastable
635
+ /// to `&E` or `Box<E>` for its original underlying error type. Any
636
+ /// backtrace collected during construction of the `anyhow::Error` is
637
+ /// discarded.
638
+ ///
639
+ /// ```
640
+ #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify!{")]
641
+ /// #![feature(error_generic_member_access)]
642
+ ///
643
+ /// use anyhow::anyhow;
644
+ /// use std::backtrace::Backtrace;
645
+ /// use thiserror::Error;
646
+ ///
647
+ /// #[derive(Error, Debug)]
648
+ /// #[error("...")]
649
+ /// struct MyError;
650
+ ///
651
+ /// let anyhow_error = anyhow!(MyError);
652
+ /// println!("{}", anyhow_error.backtrace()); // has Backtrace
653
+ /// assert!(anyhow_error.downcast_ref::<MyError>().is_some()); // can downcast
654
+ ///
655
+ /// let boxed_dyn_error = anyhow_error.reallocate_into_boxed_dyn_error_without_backtrace();
656
+ /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_none()); // Backtrace lost
657
+ /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_some()); // can downcast to &MyError
658
+ /// assert!(boxed_dyn_error.downcast::<MyError>().is_ok()); // can downcast to Box<MyError>
659
+ #[cfg_attr(not(error_generic_member_access), doc = "# };")]
660
+ /// ```
661
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
662
+ #[must_use]
663
+ pub fn reallocate_into_boxed_dyn_error_without_backtrace(
664
+ self,
665
+ ) -> Box<dyn StdError + Send + Sync + 'static> {
666
+ let outer = ManuallyDrop::new(self);
667
+ unsafe {
668
+ // Use vtable to attach E's native StdError vtable for the right
669
+ // original type E.
670
+ (vtable(outer.inner.ptr).object_reallocate_boxed)(outer.inner)
671
+ }
672
+ }
673
+
674
+ #[cfg(error_generic_member_access)]
675
+ pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {
676
+ unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }
677
+ }
678
+
679
+ // Called by thiserror when you have `#[source] anyhow::Error`. This provide
680
+ // implementation includes the anyhow::Error's Backtrace if any, unlike
681
+ // deref'ing to dyn Error where the provide implementation would include
682
+ // only the original error's Backtrace from before it got wrapped into an
683
+ // anyhow::Error.
684
+ #[cfg(error_generic_member_access)]
685
+ #[doc(hidden)]
686
+ pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {
687
+ Self::provide(self, request);
688
+ }
689
+ }
690
+
691
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
692
+ impl<E> From<E> for Error
693
+ where
694
+ E: StdError + Send + Sync + 'static,
695
+ {
696
+ #[cold]
697
+ fn from(error: E) -> Self {
698
+ let backtrace = backtrace_if_absent!(&error);
699
+ Error::construct_from_std(error, backtrace)
700
+ }
701
+ }
702
+
703
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
704
+ impl Deref for Error {
705
+ type Target = dyn StdError + Send + Sync + 'static;
706
+
707
+ fn deref(&self) -> &Self::Target {
708
+ unsafe { ErrorImpl::error(self.inner.by_ref()) }
709
+ }
710
+ }
711
+
712
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
713
+ impl DerefMut for Error {
714
+ fn deref_mut(&mut self) -> &mut Self::Target {
715
+ unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }
716
+ }
717
+ }
718
+
719
+ impl Display for Error {
720
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
721
+ unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }
722
+ }
723
+ }
724
+
725
+ impl Debug for Error {
726
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
727
+ unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }
728
+ }
729
+ }
730
+
731
+ impl Drop for Error {
732
+ fn drop(&mut self) {
733
+ unsafe {
734
+ // Invoke the vtable's drop behavior.
735
+ (vtable(self.inner.ptr).object_drop)(self.inner);
736
+ }
737
+ }
738
+ }
739
+
740
+ struct ErrorVTable {
741
+ object_drop: unsafe fn(Own<ErrorImpl>),
742
+ object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,
743
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
744
+ object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,
745
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
746
+ object_reallocate_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,
747
+ object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,
748
+ object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),
749
+ #[cfg(all(
750
+ not(error_generic_member_access),
751
+ any(std_backtrace, feature = "backtrace")
752
+ ))]
753
+ object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,
754
+ }
755
+
756
+ // Safety: requires layout of *e to match ErrorImpl<E>.
757
+ unsafe fn object_drop<E>(e: Own<ErrorImpl>) {
758
+ // Cast back to ErrorImpl<E> so that the allocator receives the correct
759
+ // Layout to deallocate the Box's memory.
760
+ let unerased_own = e.cast::<ErrorImpl<E>>();
761
+ drop(unsafe { unerased_own.boxed() });
762
+ }
763
+
764
+ // Safety: requires layout of *e to match ErrorImpl<E>.
765
+ unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {
766
+ // Drop the fields of ErrorImpl other than E as well as the Box allocation,
767
+ // without dropping E itself. This is used by downcast after doing a
768
+ // ptr::read to take ownership of the E.
769
+ let _ = target;
770
+ let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();
771
+ drop(unsafe { unerased_own.boxed() });
772
+ }
773
+
774
+ // Safety: requires layout of *e to match ErrorImpl<E>.
775
+ unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>
776
+ where
777
+ E: StdError + Send + Sync + 'static,
778
+ {
779
+ // Attach E's native StdError vtable onto a pointer to self._object.
780
+ let unerased_ref = e.cast::<ErrorImpl<E>>();
781
+ Ref::from_raw(unsafe {
782
+ NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object).cast_mut())
783
+ })
784
+ }
785
+
786
+ // Safety: requires layout of *e to match ErrorImpl<E>.
787
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
788
+ unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>
789
+ where
790
+ E: StdError + Send + Sync + 'static,
791
+ {
792
+ // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.
793
+ let unerased_own = e.cast::<ErrorImpl<E>>();
794
+ unsafe { unerased_own.boxed() }
795
+ }
796
+
797
+ // Safety: requires layout of *e to match ErrorImpl<E>.
798
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
799
+ unsafe fn object_reallocate_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>
800
+ where
801
+ E: StdError + Send + Sync + 'static,
802
+ {
803
+ // Attach E's native StdError vtable.
804
+ let unerased_own = e.cast::<ErrorImpl<E>>();
805
+ Box::new(unsafe { unerased_own.boxed() }._object)
806
+ }
807
+
808
+ // Safety: requires layout of *e to match ErrorImpl<E>.
809
+ unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
810
+ where
811
+ E: 'static,
812
+ {
813
+ if TypeId::of::<E>() == target {
814
+ // Caller is looking for an E pointer and e is ErrorImpl<E>, take a
815
+ // pointer to its E field.
816
+ let unerased_ref = e.cast::<ErrorImpl<E>>();
817
+ Some(
818
+ Ref::from_raw(unsafe {
819
+ NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object).cast_mut())
820
+ })
821
+ .cast::<()>(),
822
+ )
823
+ } else {
824
+ None
825
+ }
826
+ }
827
+
828
+ #[cfg(all(
829
+ not(error_generic_member_access),
830
+ any(std_backtrace, feature = "backtrace")
831
+ ))]
832
+ fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {
833
+ let _ = e;
834
+ None
835
+ }
836
+
837
+ // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.
838
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
839
+ unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
840
+ where
841
+ C: 'static,
842
+ E: 'static,
843
+ {
844
+ if TypeId::of::<C>() == target {
845
+ let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();
846
+ let unerased = unsafe { unerased_ref.deref() };
847
+ Some(Ref::new(&unerased._object.context).cast::<()>())
848
+ } else if TypeId::of::<E>() == target {
849
+ let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();
850
+ let unerased = unsafe { unerased_ref.deref() };
851
+ Some(Ref::new(&unerased._object.error).cast::<()>())
852
+ } else {
853
+ None
854
+ }
855
+ }
856
+
857
+ // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.
858
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
859
+ unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)
860
+ where
861
+ C: 'static,
862
+ E: 'static,
863
+ {
864
+ // Called after downcasting by value to either the C or the E and doing a
865
+ // ptr::read to take ownership of that value.
866
+ if TypeId::of::<C>() == target {
867
+ let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();
868
+ drop(unsafe { unerased_own.boxed() });
869
+ } else {
870
+ let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();
871
+ drop(unsafe { unerased_own.boxed() });
872
+ }
873
+ }
874
+
875
+ // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
876
+ unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
877
+ where
878
+ C: 'static,
879
+ {
880
+ let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();
881
+ let unerased = unsafe { unerased_ref.deref() };
882
+ if TypeId::of::<C>() == target {
883
+ Some(Ref::new(&unerased._object.context).cast::<()>())
884
+ } else {
885
+ // Recurse down the context chain per the inner error's vtable.
886
+ let source = &unerased._object.error;
887
+ unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }
888
+ }
889
+ }
890
+
891
+ // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
892
+ unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)
893
+ where
894
+ C: 'static,
895
+ {
896
+ // Called after downcasting by value to either the C or one of the causes
897
+ // and doing a ptr::read to take ownership of that value.
898
+ if TypeId::of::<C>() == target {
899
+ let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();
900
+ // Drop the entire rest of the data structure rooted in the next Error.
901
+ drop(unsafe { unerased_own.boxed() });
902
+ } else {
903
+ let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();
904
+ let unerased = unsafe { unerased_own.boxed() };
905
+ // Read the Own<ErrorImpl> from the next error.
906
+ let inner = unerased._object.error.inner;
907
+ drop(unerased);
908
+ let vtable = unsafe { vtable(inner.ptr) };
909
+ // Recursively drop the next error using the same target typeid.
910
+ unsafe { (vtable.object_drop_rest)(inner, target) };
911
+ }
912
+ }
913
+
914
+ // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
915
+ #[cfg(all(
916
+ not(error_generic_member_access),
917
+ any(std_backtrace, feature = "backtrace")
918
+ ))]
919
+ #[allow(clippy::unnecessary_wraps)]
920
+ unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>
921
+ where
922
+ C: 'static,
923
+ {
924
+ let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();
925
+ let unerased = unsafe { unerased_ref.deref() };
926
+ let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };
927
+ Some(backtrace)
928
+ }
929
+
930
+ // NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor
931
+ // of raw pointers and `NonNull`.
932
+ // repr C to ensure that E remains in the final position.
933
+ #[repr(C)]
934
+ pub(crate) struct ErrorImpl<E = ()> {
935
+ vtable: &'static ErrorVTable,
936
+ backtrace: Option<Backtrace>,
937
+ // NOTE: Don't use directly. Use only through vtable. Erased type may have
938
+ // different alignment.
939
+ _object: E,
940
+ }
941
+
942
+ // Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but
943
+ // avoids converting `p` into a reference.
944
+ unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {
945
+ // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.
946
+ unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }
947
+ }
948
+
949
+ // repr C to ensure that ContextError<C, E> has the same layout as
950
+ // ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.
951
+ #[repr(C)]
952
+ pub(crate) struct ContextError<C, E> {
953
+ pub context: C,
954
+ pub error: E,
955
+ }
956
+
957
+ impl<E> ErrorImpl<E> {
958
+ fn erase(&self) -> Ref<ErrorImpl> {
959
+ // Erase the concrete type of E but preserve the vtable in self.vtable
960
+ // for manipulating the resulting thin pointer. This is analogous to an
961
+ // unsize coercion.
962
+ Ref::new(self).cast::<ErrorImpl>()
963
+ }
964
+ }
965
+
966
+ impl ErrorImpl {
967
+ pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {
968
+ // Use vtable to attach E's native StdError vtable for the right
969
+ // original type E.
970
+ unsafe { (vtable(this.ptr).object_ref)(this).deref() }
971
+ }
972
+
973
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
974
+ pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {
975
+ // Use vtable to attach E's native StdError vtable for the right
976
+ // original type E.
977
+ unsafe {
978
+ (vtable(this.ptr).object_ref)(this.by_ref())
979
+ .by_mut()
980
+ .deref_mut()
981
+ }
982
+ }
983
+
984
+ #[cfg(any(std_backtrace, feature = "backtrace"))]
985
+ pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {
986
+ // This unwrap can only panic if the underlying error's backtrace method
987
+ // is nondeterministic, which would only happen in maliciously
988
+ // constructed code.
989
+ unsafe { this.deref() }
990
+ .backtrace
991
+ .as_ref()
992
+ .or_else(|| {
993
+ #[cfg(error_generic_member_access)]
994
+ return nightly::request_ref_backtrace(unsafe { Self::error(this) });
995
+ #[cfg(not(error_generic_member_access))]
996
+ return unsafe { (vtable(this.ptr).object_backtrace)(this) };
997
+ })
998
+ .expect("backtrace capture failed")
999
+ }
1000
+
1001
+ #[cfg(error_generic_member_access)]
1002
+ unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {
1003
+ if let Some(backtrace) = unsafe { &this.deref().backtrace } {
1004
+ nightly::provide_ref_backtrace(request, backtrace);
1005
+ }
1006
+ nightly::provide(unsafe { Self::error(this) }, request);
1007
+ }
1008
+
1009
+ #[cold]
1010
+ pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {
1011
+ Chain::new(unsafe { Self::error(this) })
1012
+ }
1013
+ }
1014
+
1015
+ impl<E> StdError for ErrorImpl<E>
1016
+ where
1017
+ E: StdError,
1018
+ {
1019
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
1020
+ unsafe { ErrorImpl::error(self.erase()).source() }
1021
+ }
1022
+
1023
+ #[cfg(error_generic_member_access)]
1024
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
1025
+ unsafe { ErrorImpl::provide(self.erase(), request) }
1026
+ }
1027
+ }
1028
+
1029
+ impl<E> Debug for ErrorImpl<E>
1030
+ where
1031
+ E: Debug,
1032
+ {
1033
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1034
+ unsafe { ErrorImpl::debug(self.erase(), formatter) }
1035
+ }
1036
+ }
1037
+
1038
+ impl<E> Display for ErrorImpl<E>
1039
+ where
1040
+ E: Display,
1041
+ {
1042
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1043
+ unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }
1044
+ }
1045
+ }
1046
+
1047
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
1048
+ impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {
1049
+ #[cold]
1050
+ fn from(error: Error) -> Self {
1051
+ error.into_boxed_dyn_error()
1052
+ }
1053
+ }
1054
+
1055
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
1056
+ impl From<Error> for Box<dyn StdError + Send + 'static> {
1057
+ #[cold]
1058
+ fn from(error: Error) -> Self {
1059
+ error.into_boxed_dyn_error()
1060
+ }
1061
+ }
1062
+
1063
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
1064
+ impl From<Error> for Box<dyn StdError + 'static> {
1065
+ #[cold]
1066
+ fn from(error: Error) -> Self {
1067
+ error.into_boxed_dyn_error()
1068
+ }
1069
+ }
1070
+
1071
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
1072
+ impl AsRef<dyn StdError + Send + Sync> for Error {
1073
+ fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {
1074
+ &**self
1075
+ }
1076
+ }
1077
+
1078
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
1079
+ impl AsRef<dyn StdError> for Error {
1080
+ fn as_ref(&self) -> &(dyn StdError + 'static) {
1081
+ &**self
1082
+ }
1083
+ }
1084
+
1085
+ impl UnwindSafe for Error {}
1086
+ impl RefUnwindSafe for Error {}
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/fmt.rs ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::chain::Chain;
2
+ use crate::error::ErrorImpl;
3
+ use crate::ptr::Ref;
4
+ use core::fmt::{self, Debug, Write};
5
+
6
+ impl ErrorImpl {
7
+ pub(crate) unsafe fn display(this: Ref<Self>, f: &mut fmt::Formatter) -> fmt::Result {
8
+ write!(f, "{}", unsafe { Self::error(this) })?;
9
+
10
+ if f.alternate() {
11
+ let chain = unsafe { Self::chain(this) };
12
+ for cause in chain.skip(1) {
13
+ write!(f, ": {}", cause)?;
14
+ }
15
+ }
16
+
17
+ Ok(())
18
+ }
19
+
20
+ pub(crate) unsafe fn debug(this: Ref<Self>, f: &mut fmt::Formatter) -> fmt::Result {
21
+ let error = unsafe { Self::error(this) };
22
+
23
+ if f.alternate() {
24
+ return Debug::fmt(error, f);
25
+ }
26
+
27
+ write!(f, "{}", error)?;
28
+
29
+ if let Some(cause) = error.source() {
30
+ write!(f, "\n\nCaused by:")?;
31
+ let multiple = cause.source().is_some();
32
+ for (n, error) in Chain::new(cause).enumerate() {
33
+ writeln!(f)?;
34
+ let mut indented = Indented {
35
+ inner: f,
36
+ number: if multiple { Some(n) } else { None },
37
+ started: false,
38
+ };
39
+ write!(indented, "{}", error)?;
40
+ }
41
+ }
42
+
43
+ #[cfg(any(std_backtrace, feature = "backtrace"))]
44
+ {
45
+ use crate::backtrace::BacktraceStatus;
46
+ use alloc::string::ToString;
47
+
48
+ let backtrace = unsafe { Self::backtrace(this) };
49
+ if let BacktraceStatus::Captured = backtrace.status() {
50
+ let mut backtrace = backtrace.to_string();
51
+ write!(f, "\n\n")?;
52
+ if backtrace.starts_with("stack backtrace:") {
53
+ // Capitalize to match "Caused by:"
54
+ backtrace.replace_range(0..1, "S");
55
+ } else {
56
+ // "stack backtrace:" prefix was removed in
57
+ // https://github.com/rust-lang/backtrace-rs/pull/286
58
+ writeln!(f, "Stack backtrace:")?;
59
+ }
60
+ backtrace.truncate(backtrace.trim_end().len());
61
+ write!(f, "{}", backtrace)?;
62
+ }
63
+ }
64
+
65
+ Ok(())
66
+ }
67
+ }
68
+
69
+ struct Indented<'a, D> {
70
+ inner: &'a mut D,
71
+ number: Option<usize>,
72
+ started: bool,
73
+ }
74
+
75
+ impl<T> Write for Indented<'_, T>
76
+ where
77
+ T: Write,
78
+ {
79
+ fn write_str(&mut self, s: &str) -> fmt::Result {
80
+ for (i, line) in s.split('\n').enumerate() {
81
+ if !self.started {
82
+ self.started = true;
83
+ match self.number {
84
+ Some(number) => write!(self.inner, "{: >5}: ", number)?,
85
+ None => self.inner.write_str(" ")?,
86
+ }
87
+ } else if i > 0 {
88
+ self.inner.write_char('\n')?;
89
+ if self.number.is_some() {
90
+ self.inner.write_str(" ")?;
91
+ } else {
92
+ self.inner.write_str(" ")?;
93
+ }
94
+ }
95
+
96
+ self.inner.write_str(line)?;
97
+ }
98
+
99
+ Ok(())
100
+ }
101
+ }
102
+
103
+ #[cfg(test)]
104
+ mod tests {
105
+ use super::*;
106
+ use alloc::string::String;
107
+
108
+ #[test]
109
+ fn one_digit() {
110
+ let input = "verify\nthis";
111
+ let expected = " 2: verify\n this";
112
+ let mut output = String::new();
113
+
114
+ Indented {
115
+ inner: &mut output,
116
+ number: Some(2),
117
+ started: false,
118
+ }
119
+ .write_str(input)
120
+ .unwrap();
121
+
122
+ assert_eq!(expected, output);
123
+ }
124
+
125
+ #[test]
126
+ fn two_digits() {
127
+ let input = "verify\nthis";
128
+ let expected = " 12: verify\n this";
129
+ let mut output = String::new();
130
+
131
+ Indented {
132
+ inner: &mut output,
133
+ number: Some(12),
134
+ started: false,
135
+ }
136
+ .write_str(input)
137
+ .unwrap();
138
+
139
+ assert_eq!(expected, output);
140
+ }
141
+
142
+ #[test]
143
+ fn no_digits() {
144
+ let input = "verify\nthis";
145
+ let expected = " verify\n this";
146
+ let mut output = String::new();
147
+
148
+ Indented {
149
+ inner: &mut output,
150
+ number: None,
151
+ started: false,
152
+ }
153
+ .write_str(input)
154
+ .unwrap();
155
+
156
+ assert_eq!(expected, output);
157
+ }
158
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/kind.rs ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Tagged dispatch mechanism for resolving the behavior of `anyhow!($expr)`.
2
+ //
3
+ // When anyhow! is given a single expr argument to turn into anyhow::Error, we
4
+ // want the resulting Error to pick up the input's implementation of source()
5
+ // and backtrace() if it has a std::error::Error impl, otherwise require nothing
6
+ // more than Display and Debug.
7
+ //
8
+ // Expressed in terms of specialization, we want something like:
9
+ //
10
+ // trait AnyhowNew {
11
+ // fn new(self) -> Error;
12
+ // }
13
+ //
14
+ // impl<T> AnyhowNew for T
15
+ // where
16
+ // T: Display + Debug + Send + Sync + 'static,
17
+ // {
18
+ // default fn new(self) -> Error {
19
+ // /* no std error impl */
20
+ // }
21
+ // }
22
+ //
23
+ // impl<T> AnyhowNew for T
24
+ // where
25
+ // T: std::error::Error + Send + Sync + 'static,
26
+ // {
27
+ // fn new(self) -> Error {
28
+ // /* use std error's source() and backtrace() */
29
+ // }
30
+ // }
31
+ //
32
+ // Since specialization is not stable yet, instead we rely on autoref behavior
33
+ // of method resolution to perform tagged dispatch. Here we have two traits
34
+ // AdhocKind and TraitKind that both have an anyhow_kind() method. AdhocKind is
35
+ // implemented whether or not the caller's type has a std error impl, while
36
+ // TraitKind is implemented only when a std error impl does exist. The ambiguity
37
+ // is resolved by AdhocKind requiring an extra autoref so that it has lower
38
+ // precedence.
39
+ //
40
+ // The anyhow! macro will set up the call in this form:
41
+ //
42
+ // #[allow(unused_imports)]
43
+ // use $crate::__private::{AdhocKind, TraitKind};
44
+ // let error = $msg;
45
+ // (&error).anyhow_kind().new(error)
46
+
47
+ use crate::Error;
48
+ use core::fmt::{Debug, Display};
49
+
50
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
51
+ use crate::StdError;
52
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
53
+ use alloc::boxed::Box;
54
+
55
+ pub struct Adhoc;
56
+
57
+ #[doc(hidden)]
58
+ pub trait AdhocKind: Sized {
59
+ #[inline]
60
+ fn anyhow_kind(&self) -> Adhoc {
61
+ Adhoc
62
+ }
63
+ }
64
+
65
+ impl<T> AdhocKind for &T where T: ?Sized + Display + Debug + Send + Sync + 'static {}
66
+
67
+ impl Adhoc {
68
+ #[cold]
69
+ pub fn new<M>(self, message: M) -> Error
70
+ where
71
+ M: Display + Debug + Send + Sync + 'static,
72
+ {
73
+ Error::construct_from_adhoc(message, backtrace!())
74
+ }
75
+ }
76
+
77
+ pub struct Trait;
78
+
79
+ #[doc(hidden)]
80
+ pub trait TraitKind: Sized {
81
+ #[inline]
82
+ fn anyhow_kind(&self) -> Trait {
83
+ Trait
84
+ }
85
+ }
86
+
87
+ impl<E> TraitKind for E where E: Into<Error> {}
88
+
89
+ impl Trait {
90
+ #[cold]
91
+ pub fn new<E>(self, error: E) -> Error
92
+ where
93
+ E: Into<Error>,
94
+ {
95
+ error.into()
96
+ }
97
+ }
98
+
99
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
100
+ pub struct Boxed;
101
+
102
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
103
+ #[doc(hidden)]
104
+ pub trait BoxedKind: Sized {
105
+ #[inline]
106
+ fn anyhow_kind(&self) -> Boxed {
107
+ Boxed
108
+ }
109
+ }
110
+
111
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
112
+ impl BoxedKind for Box<dyn StdError + Send + Sync> {}
113
+
114
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
115
+ impl Boxed {
116
+ #[cold]
117
+ pub fn new(self, error: Box<dyn StdError + Send + Sync>) -> Error {
118
+ let backtrace = backtrace_if_absent!(&*error);
119
+ Error::construct_from_boxed(error, backtrace)
120
+ }
121
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/lib.rs ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! [![github]](https://github.com/dtolnay/anyhow)&ensp;[![crates-io]](https://crates.io/crates/anyhow)&ensp;[![docs-rs]](https://docs.rs/anyhow)
2
+ //!
3
+ //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4
+ //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5
+ //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6
+ //!
7
+ //! <br>
8
+ //!
9
+ //! This library provides [`anyhow::Error`][Error], a trait object based error
10
+ //! type for easy idiomatic error handling in Rust applications.
11
+ //!
12
+ //! <br>
13
+ //!
14
+ //! # Details
15
+ //!
16
+ //! - Use `Result<T, anyhow::Error>`, or equivalently `anyhow::Result<T>`, as
17
+ //! the return type of any fallible function.
18
+ //!
19
+ //! Within the function, use `?` to easily propagate any error that implements
20
+ //! the [`std::error::Error`] trait.
21
+ //!
22
+ //! ```
23
+ //! # pub trait Deserialize {}
24
+ //! #
25
+ //! # mod serde_json {
26
+ //! # use super::Deserialize;
27
+ //! # use std::io;
28
+ //! #
29
+ //! # pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {
30
+ //! # unimplemented!()
31
+ //! # }
32
+ //! # }
33
+ //! #
34
+ //! # struct ClusterMap;
35
+ //! #
36
+ //! # impl Deserialize for ClusterMap {}
37
+ //! #
38
+ //! use anyhow::Result;
39
+ //!
40
+ //! fn get_cluster_info() -> Result<ClusterMap> {
41
+ //! let config = std::fs::read_to_string("cluster.json")?;
42
+ //! let map: ClusterMap = serde_json::from_str(&config)?;
43
+ //! Ok(map)
44
+ //! }
45
+ //! #
46
+ //! # fn main() {}
47
+ //! ```
48
+ //!
49
+ //! - Attach context to help the person troubleshooting the error understand
50
+ //! where things went wrong. A low-level error like "No such file or
51
+ //! directory" can be annoying to debug without more context about what higher
52
+ //! level step the application was in the middle of.
53
+ //!
54
+ //! ```
55
+ //! # struct It;
56
+ //! #
57
+ //! # impl It {
58
+ //! # fn detach(&self) -> Result<()> {
59
+ //! # unimplemented!()
60
+ //! # }
61
+ //! # }
62
+ //! #
63
+ //! use anyhow::{Context, Result};
64
+ //!
65
+ //! fn main() -> Result<()> {
66
+ //! # return Ok(());
67
+ //! #
68
+ //! # const _: &str = stringify! {
69
+ //! ...
70
+ //! # };
71
+ //! #
72
+ //! # let it = It;
73
+ //! # let path = "./path/to/instrs.json";
74
+ //! #
75
+ //! it.detach().context("Failed to detach the important thing")?;
76
+ //!
77
+ //! let content = std::fs::read(path)
78
+ //! .with_context(|| format!("Failed to read instrs from {}", path))?;
79
+ //! #
80
+ //! # const _: &str = stringify! {
81
+ //! ...
82
+ //! # };
83
+ //! #
84
+ //! # Ok(())
85
+ //! }
86
+ //! ```
87
+ //!
88
+ //! ```console
89
+ //! Error: Failed to read instrs from ./path/to/instrs.json
90
+ //!
91
+ //! Caused by:
92
+ //! No such file or directory (os error 2)
93
+ //! ```
94
+ //!
95
+ //! - Downcasting is supported and can be by value, by shared reference, or by
96
+ //! mutable reference as needed.
97
+ //!
98
+ //! ```
99
+ //! # use anyhow::anyhow;
100
+ //! # use std::fmt::{self, Display};
101
+ //! # use std::task::Poll;
102
+ //! #
103
+ //! # #[derive(Debug)]
104
+ //! # enum DataStoreError {
105
+ //! # Censored(()),
106
+ //! # }
107
+ //! #
108
+ //! # impl Display for DataStoreError {
109
+ //! # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
110
+ //! # unimplemented!()
111
+ //! # }
112
+ //! # }
113
+ //! #
114
+ //! # impl std::error::Error for DataStoreError {}
115
+ //! #
116
+ //! # const REDACTED_CONTENT: () = ();
117
+ //! #
118
+ //! # let error = anyhow!("...");
119
+ //! # let root_cause = &error;
120
+ //! #
121
+ //! # let ret =
122
+ //! // If the error was caused by redaction, then return a
123
+ //! // tombstone instead of the content.
124
+ //! match root_cause.downcast_ref::<DataStoreError>() {
125
+ //! Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),
126
+ //! None => Err(error),
127
+ //! }
128
+ //! # ;
129
+ //! ```
130
+ //!
131
+ //! - If using Rust &ge; 1.65, a backtrace is captured and printed with the
132
+ //! error if the underlying error type does not already provide its own. In
133
+ //! order to see backtraces, they must be enabled through the environment
134
+ //! variables described in [`std::backtrace`]:
135
+ //!
136
+ //! - If you want panics and errors to both have backtraces, set
137
+ //! `RUST_BACKTRACE=1`;
138
+ //! - If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`;
139
+ //! - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and
140
+ //! `RUST_LIB_BACKTRACE=0`.
141
+ //!
142
+ //! [`std::backtrace`]: std::backtrace#environment-variables
143
+ //!
144
+ //! - Anyhow works with any error type that has an impl of `std::error::Error`,
145
+ //! including ones defined in your crate. We do not bundle a `derive(Error)`
146
+ //! macro but you can write the impls yourself or use a standalone macro like
147
+ //! [thiserror].
148
+ //!
149
+ //! [thiserror]: https://github.com/dtolnay/thiserror
150
+ //!
151
+ //! ```
152
+ //! use thiserror::Error;
153
+ //!
154
+ //! #[derive(Error, Debug)]
155
+ //! pub enum FormatError {
156
+ //! #[error("Invalid header (expected {expected:?}, got {found:?})")]
157
+ //! InvalidHeader {
158
+ //! expected: String,
159
+ //! found: String,
160
+ //! },
161
+ //! #[error("Missing attribute: {0}")]
162
+ //! MissingAttribute(String),
163
+ //! }
164
+ //! ```
165
+ //!
166
+ //! - One-off error messages can be constructed using the `anyhow!` macro, which
167
+ //! supports string interpolation and produces an `anyhow::Error`.
168
+ //!
169
+ //! ```
170
+ //! # use anyhow::{anyhow, Result};
171
+ //! #
172
+ //! # fn demo() -> Result<()> {
173
+ //! # let missing = "...";
174
+ //! return Err(anyhow!("Missing attribute: {}", missing));
175
+ //! # Ok(())
176
+ //! # }
177
+ //! ```
178
+ //!
179
+ //! A `bail!` macro is provided as a shorthand for the same early return.
180
+ //!
181
+ //! ```
182
+ //! # use anyhow::{bail, Result};
183
+ //! #
184
+ //! # fn demo() -> Result<()> {
185
+ //! # let missing = "...";
186
+ //! bail!("Missing attribute: {}", missing);
187
+ //! # Ok(())
188
+ //! # }
189
+ //! ```
190
+ //!
191
+ //! <br>
192
+ //!
193
+ //! # No-std support
194
+ //!
195
+ //! In no_std mode, almost all of the same API is available and works the same
196
+ //! way. To depend on Anyhow in no_std mode, disable our default enabled "std"
197
+ //! feature in Cargo.toml. A global allocator is required.
198
+ //!
199
+ //! ```toml
200
+ //! [dependencies]
201
+ //! anyhow = { version = "1.0", default-features = false }
202
+ //! ```
203
+ //!
204
+ //! With versions of Rust older than 1.81, no_std mode may require an additional
205
+ //! `.map_err(Error::msg)` when working with a non-Anyhow error type inside a
206
+ //! function that returns Anyhow's error type, as the trait that `?`-based error
207
+ //! conversions are defined by is only available in std in those old versions.
208
+
209
+ #![doc(html_root_url = "https://docs.rs/anyhow/1.0.101")]
210
+ #![cfg_attr(error_generic_member_access, feature(error_generic_member_access))]
211
+ #![no_std]
212
+ #![deny(dead_code, unsafe_op_in_unsafe_fn, unused_imports, unused_mut)]
213
+ #![allow(
214
+ clippy::doc_markdown,
215
+ clippy::elidable_lifetime_names,
216
+ clippy::enum_glob_use,
217
+ clippy::explicit_auto_deref,
218
+ clippy::extra_unused_type_parameters,
219
+ clippy::incompatible_msrv,
220
+ clippy::let_underscore_untyped,
221
+ clippy::missing_errors_doc,
222
+ clippy::missing_panics_doc,
223
+ clippy::module_name_repetitions,
224
+ clippy::must_use_candidate,
225
+ clippy::needless_doctest_main,
226
+ clippy::needless_lifetimes,
227
+ clippy::new_ret_no_self,
228
+ clippy::redundant_else,
229
+ clippy::return_self_not_must_use,
230
+ clippy::struct_field_names,
231
+ clippy::uninlined_format_args,
232
+ clippy::unused_self,
233
+ clippy::used_underscore_binding,
234
+ clippy::wildcard_imports,
235
+ clippy::wrong_self_convention
236
+ )]
237
+ #![allow(unknown_lints, mismatched_lifetime_syntaxes)]
238
+
239
+ #[cfg(all(
240
+ anyhow_nightly_testing,
241
+ feature = "std",
242
+ not(error_generic_member_access)
243
+ ))]
244
+ compile_error!("Build script probe failed to compile.");
245
+
246
+ extern crate alloc;
247
+
248
+ #[cfg(feature = "std")]
249
+ extern crate std;
250
+
251
+ #[macro_use]
252
+ mod backtrace;
253
+ mod chain;
254
+ mod context;
255
+ mod ensure;
256
+ mod error;
257
+ mod fmt;
258
+ mod kind;
259
+ mod macros;
260
+ #[cfg(error_generic_member_access)]
261
+ mod nightly;
262
+ mod ptr;
263
+ mod wrapper;
264
+
265
+ use crate::error::ErrorImpl;
266
+ use crate::ptr::Own;
267
+ use core::fmt::Display;
268
+
269
+ #[cfg(all(not(feature = "std"), anyhow_no_core_error))]
270
+ use core::fmt::Debug;
271
+
272
+ #[cfg(feature = "std")]
273
+ use std::error::Error as StdError;
274
+
275
+ #[cfg(not(any(feature = "std", anyhow_no_core_error)))]
276
+ use core::error::Error as StdError;
277
+
278
+ #[cfg(all(not(feature = "std"), anyhow_no_core_error))]
279
+ trait StdError: Debug + Display {
280
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
281
+ None
282
+ }
283
+ }
284
+
285
+ #[doc(no_inline)]
286
+ pub use anyhow as format_err;
287
+
288
+ /// The `Error` type, a wrapper around a dynamic error type.
289
+ ///
290
+ /// `Error` works a lot like `Box<dyn std::error::Error>`, but with these
291
+ /// differences:
292
+ ///
293
+ /// - `Error` requires that the error is `Send`, `Sync`, and `'static`.
294
+ /// - `Error` guarantees that a backtrace is available, even if the underlying
295
+ /// error type does not provide one.
296
+ /// - `Error` is represented as a narrow pointer &mdash; exactly one word in
297
+ /// size instead of two.
298
+ ///
299
+ /// <br>
300
+ ///
301
+ /// # Display representations
302
+ ///
303
+ /// When you print an error object using "{}" or to_string(), only the outermost
304
+ /// underlying error or context is printed, not any of the lower level causes.
305
+ /// This is exactly as if you had called the Display impl of the error from
306
+ /// which you constructed your anyhow::Error.
307
+ ///
308
+ /// ```console
309
+ /// Failed to read instrs from ./path/to/instrs.json
310
+ /// ```
311
+ ///
312
+ /// To print causes as well using anyhow's default formatting of causes, use the
313
+ /// alternate selector "{:#}".
314
+ ///
315
+ /// ```console
316
+ /// Failed to read instrs from ./path/to/instrs.json: No such file or directory (os error 2)
317
+ /// ```
318
+ ///
319
+ /// The Debug format "{:?}" includes your backtrace if one was captured. Note
320
+ /// that this is the representation you get by default if you return an error
321
+ /// from `fn main` instead of printing it explicitly yourself.
322
+ ///
323
+ /// ```console
324
+ /// Error: Failed to read instrs from ./path/to/instrs.json
325
+ ///
326
+ /// Caused by:
327
+ /// No such file or directory (os error 2)
328
+ /// ```
329
+ ///
330
+ /// and if there is a backtrace available:
331
+ ///
332
+ /// ```console
333
+ /// Error: Failed to read instrs from ./path/to/instrs.json
334
+ ///
335
+ /// Caused by:
336
+ /// No such file or directory (os error 2)
337
+ ///
338
+ /// Stack backtrace:
339
+ /// 0: <E as anyhow::context::ext::StdError>::ext_context
340
+ /// at /git/anyhow/src/backtrace.rs:26
341
+ /// 1: core::result::Result<T,E>::map_err
342
+ /// at /git/rustc/src/libcore/result.rs:596
343
+ /// 2: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::with_context
344
+ /// at /git/anyhow/src/context.rs:58
345
+ /// 3: testing::main
346
+ /// at src/main.rs:5
347
+ /// 4: std::rt::lang_start
348
+ /// at /git/rustc/src/libstd/rt.rs:61
349
+ /// 5: main
350
+ /// 6: __libc_start_main
351
+ /// 7: _start
352
+ /// ```
353
+ ///
354
+ /// To see a conventional struct-style Debug representation, use "{:#?}".
355
+ ///
356
+ /// ```console
357
+ /// Error {
358
+ /// context: "Failed to read instrs from ./path/to/instrs.json",
359
+ /// source: Os {
360
+ /// code: 2,
361
+ /// kind: NotFound,
362
+ /// message: "No such file or directory",
363
+ /// },
364
+ /// }
365
+ /// ```
366
+ ///
367
+ /// If none of the built-in representations are appropriate and you would prefer
368
+ /// to render the error and its cause chain yourself, it can be done something
369
+ /// like this:
370
+ ///
371
+ /// ```
372
+ /// use anyhow::{Context, Result};
373
+ ///
374
+ /// fn main() {
375
+ /// if let Err(err) = try_main() {
376
+ /// eprintln!("ERROR: {}", err);
377
+ /// err.chain().skip(1).for_each(|cause| eprintln!("because: {}", cause));
378
+ /// std::process::exit(1);
379
+ /// }
380
+ /// }
381
+ ///
382
+ /// fn try_main() -> Result<()> {
383
+ /// # const IGNORE: &str = stringify! {
384
+ /// ...
385
+ /// # };
386
+ /// # Ok(())
387
+ /// }
388
+ /// ```
389
+ #[repr(transparent)]
390
+ pub struct Error {
391
+ inner: Own<ErrorImpl>,
392
+ }
393
+
394
+ /// Iterator of a chain of source errors.
395
+ ///
396
+ /// This type is the iterator returned by [`Error::chain`].
397
+ ///
398
+ /// # Example
399
+ ///
400
+ /// ```
401
+ /// use anyhow::Error;
402
+ /// use std::io;
403
+ ///
404
+ /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
405
+ /// for cause in error.chain() {
406
+ /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {
407
+ /// return Some(io_error.kind());
408
+ /// }
409
+ /// }
410
+ /// None
411
+ /// }
412
+ /// ```
413
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
414
+ #[derive(Clone)]
415
+ pub struct Chain<'a> {
416
+ state: crate::chain::ChainState<'a>,
417
+ }
418
+
419
+ /// `Result<T, Error>`
420
+ ///
421
+ /// This is a reasonable return type to use throughout your application but also
422
+ /// for `fn main`; if you do, failures will be printed along with any
423
+ /// [context][Context] and a backtrace if one was captured.
424
+ ///
425
+ /// `anyhow::Result` may be used with one *or* two type parameters.
426
+ ///
427
+ /// ```rust
428
+ /// use anyhow::Result;
429
+ ///
430
+ /// # const IGNORE: &str = stringify! {
431
+ /// fn demo1() -> Result<T> {...}
432
+ /// // ^ equivalent to std::result::Result<T, anyhow::Error>
433
+ ///
434
+ /// fn demo2() -> Result<T, OtherError> {...}
435
+ /// // ^ equivalent to std::result::Result<T, OtherError>
436
+ /// # };
437
+ /// ```
438
+ ///
439
+ /// # Example
440
+ ///
441
+ /// ```
442
+ /// # pub trait Deserialize {}
443
+ /// #
444
+ /// # mod serde_json {
445
+ /// # use super::Deserialize;
446
+ /// # use std::io;
447
+ /// #
448
+ /// # pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {
449
+ /// # unimplemented!()
450
+ /// # }
451
+ /// # }
452
+ /// #
453
+ /// # #[derive(Debug)]
454
+ /// # struct ClusterMap;
455
+ /// #
456
+ /// # impl Deserialize for ClusterMap {}
457
+ /// #
458
+ /// use anyhow::Result;
459
+ ///
460
+ /// fn main() -> Result<()> {
461
+ /// # return Ok(());
462
+ /// let config = std::fs::read_to_string("cluster.json")?;
463
+ /// let map: ClusterMap = serde_json::from_str(&config)?;
464
+ /// println!("cluster info: {:#?}", map);
465
+ /// Ok(())
466
+ /// }
467
+ /// ```
468
+ pub type Result<T, E = Error> = core::result::Result<T, E>;
469
+
470
+ /// Provides the `context` method for `Result`.
471
+ ///
472
+ /// This trait is sealed and cannot be implemented for types outside of
473
+ /// `anyhow`.
474
+ ///
475
+ /// <br>
476
+ ///
477
+ /// # Example
478
+ ///
479
+ /// ```
480
+ /// use anyhow::{Context, Result};
481
+ /// use std::fs;
482
+ /// use std::path::PathBuf;
483
+ ///
484
+ /// pub struct ImportantThing {
485
+ /// path: PathBuf,
486
+ /// }
487
+ ///
488
+ /// impl ImportantThing {
489
+ /// # const IGNORE: &'static str = stringify! {
490
+ /// pub fn detach(&mut self) -> Result<()> {...}
491
+ /// # };
492
+ /// # fn detach(&mut self) -> Result<()> {
493
+ /// # unimplemented!()
494
+ /// # }
495
+ /// }
496
+ ///
497
+ /// pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {
498
+ /// it.detach().context("Failed to detach the important thing")?;
499
+ ///
500
+ /// let path = &it.path;
501
+ /// let content = fs::read(path)
502
+ /// .with_context(|| format!("Failed to read instrs from {}", path.display()))?;
503
+ ///
504
+ /// Ok(content)
505
+ /// }
506
+ /// ```
507
+ ///
508
+ /// When printed, the outermost context would be printed first and the lower
509
+ /// level underlying causes would be enumerated below.
510
+ ///
511
+ /// ```console
512
+ /// Error: Failed to read instrs from ./path/to/instrs.json
513
+ ///
514
+ /// Caused by:
515
+ /// No such file or directory (os error 2)
516
+ /// ```
517
+ ///
518
+ /// Refer to the [Display representations] documentation for other forms in
519
+ /// which this context chain can be rendered.
520
+ ///
521
+ /// [Display representations]: Error#display-representations
522
+ ///
523
+ /// <br>
524
+ ///
525
+ /// # Effect on downcasting
526
+ ///
527
+ /// After attaching context of type `C` onto an error of type `E`, the resulting
528
+ /// `anyhow::Error` may be downcast to `C` **or** to `E`.
529
+ ///
530
+ /// That is, in codebases that rely on downcasting, Anyhow's context supports
531
+ /// both of the following use cases:
532
+ ///
533
+ /// - **Attaching context whose type is insignificant onto errors whose type
534
+ /// is used in downcasts.**
535
+ ///
536
+ /// In other error libraries whose context is not designed this way, it can
537
+ /// be risky to introduce context to existing code because new context might
538
+ /// break existing working downcasts. In Anyhow, any downcast that worked
539
+ /// before adding context will continue to work after you add a context, so
540
+ /// you should freely add human-readable context to errors wherever it would
541
+ /// be helpful.
542
+ ///
543
+ /// ```
544
+ /// # use anyhow::bail;
545
+ /// # use thiserror::Error;
546
+ /// #
547
+ /// # #[derive(Error, Debug)]
548
+ /// # #[error("???")]
549
+ /// # struct SuspiciousError;
550
+ /// #
551
+ /// # fn helper() -> Result<()> {
552
+ /// # bail!(SuspiciousError);
553
+ /// # }
554
+ /// #
555
+ /// use anyhow::{Context, Result};
556
+ ///
557
+ /// fn do_it() -> Result<()> {
558
+ /// helper().context("Failed to complete the work")?;
559
+ /// # const IGNORE: &str = stringify! {
560
+ /// ...
561
+ /// # };
562
+ /// # unreachable!()
563
+ /// }
564
+ ///
565
+ /// fn main() {
566
+ /// let err = do_it().unwrap_err();
567
+ /// if let Some(e) = err.downcast_ref::<SuspiciousError>() {
568
+ /// // If helper() returned SuspiciousError, this downcast will
569
+ /// // correctly succeed even with the context in between.
570
+ /// # return;
571
+ /// }
572
+ /// # panic!("expected downcast to succeed");
573
+ /// }
574
+ /// ```
575
+ ///
576
+ /// - **Attaching context whose type is used in downcasts onto errors whose
577
+ /// type is insignificant.**
578
+ ///
579
+ /// Some codebases prefer to use machine-readable context to categorize
580
+ /// lower level errors in a way that will be actionable to higher levels of
581
+ /// the application.
582
+ ///
583
+ /// ```
584
+ /// # use anyhow::bail;
585
+ /// # use thiserror::Error;
586
+ /// #
587
+ /// # #[derive(Error, Debug)]
588
+ /// # #[error("???")]
589
+ /// # struct HelperFailed;
590
+ /// #
591
+ /// # fn helper() -> Result<()> {
592
+ /// # bail!("no such file or directory");
593
+ /// # }
594
+ /// #
595
+ /// use anyhow::{Context, Result};
596
+ ///
597
+ /// fn do_it() -> Result<()> {
598
+ /// helper().context(HelperFailed)?;
599
+ /// # const IGNORE: &str = stringify! {
600
+ /// ...
601
+ /// # };
602
+ /// # unreachable!()
603
+ /// }
604
+ ///
605
+ /// fn main() {
606
+ /// let err = do_it().unwrap_err();
607
+ /// if let Some(e) = err.downcast_ref::<HelperFailed>() {
608
+ /// // If helper failed, this downcast will succeed because
609
+ /// // HelperFailed is the context that has been attached to
610
+ /// // that error.
611
+ /// # return;
612
+ /// }
613
+ /// # panic!("expected downcast to succeed");
614
+ /// }
615
+ /// ```
616
+ pub trait Context<T, E>: context::private::Sealed {
617
+ /// Wrap the error value with additional context.
618
+ fn context<C>(self, context: C) -> Result<T, Error>
619
+ where
620
+ C: Display + Send + Sync + 'static;
621
+
622
+ /// Wrap the error value with additional context that is evaluated lazily
623
+ /// only once an error does occur.
624
+ fn with_context<C, F>(self, f: F) -> Result<T, Error>
625
+ where
626
+ C: Display + Send + Sync + 'static,
627
+ F: FnOnce() -> C;
628
+ }
629
+
630
+ /// Equivalent to `Ok::<_, anyhow::Error>(value)`.
631
+ ///
632
+ /// This simplifies creation of an `anyhow::Result` in places where type
633
+ /// inference cannot deduce the `E` type of the result &mdash; without needing
634
+ /// to write `Ok::<_, anyhow::Error>(value)`.
635
+ ///
636
+ /// One might think that `anyhow::Result::Ok(value)` would work in such cases
637
+ /// but it does not.
638
+ ///
639
+ /// ```console
640
+ /// error[E0282]: type annotations needed for `std::result::Result<i32, E>`
641
+ /// --> src/main.rs:11:13
642
+ /// |
643
+ /// 11 | let _ = anyhow::Result::Ok(1);
644
+ /// | - ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result`
645
+ /// | |
646
+ /// | consider giving this pattern the explicit type `std::result::Result<i32, E>`, where the type parameter `E` is specified
647
+ /// ```
648
+ #[allow(non_snake_case)]
649
+ #[inline]
650
+ pub fn Ok<T>(value: T) -> Result<T> {
651
+ Result::Ok(value)
652
+ }
653
+
654
+ // Not public API. Referenced by macro-generated code.
655
+ #[doc(hidden)]
656
+ pub mod __private {
657
+ use self::not::Bool;
658
+ use crate::Error;
659
+ use alloc::fmt;
660
+ use core::fmt::Arguments;
661
+
662
+ #[doc(hidden)]
663
+ pub use crate::ensure::{BothDebug, NotBothDebug};
664
+ #[doc(hidden)]
665
+ pub use alloc::format;
666
+ #[doc(hidden)]
667
+ pub use core::result::Result::Err;
668
+ #[doc(hidden)]
669
+ pub use core::{concat, format_args, stringify};
670
+
671
+ #[doc(hidden)]
672
+ pub mod kind {
673
+ #[doc(hidden)]
674
+ pub use crate::kind::{AdhocKind, TraitKind};
675
+
676
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
677
+ #[doc(hidden)]
678
+ pub use crate::kind::BoxedKind;
679
+ }
680
+
681
+ #[doc(hidden)]
682
+ #[inline]
683
+ #[cold]
684
+ pub fn format_err(args: Arguments) -> Error {
685
+ if let Some(message) = args.as_str() {
686
+ // anyhow!("literal"), can downcast to &'static str
687
+ Error::msg(message)
688
+ } else {
689
+ // anyhow!("interpolate {var}"), can downcast to String
690
+ Error::msg(fmt::format(args))
691
+ }
692
+ }
693
+
694
+ #[doc(hidden)]
695
+ #[inline]
696
+ #[cold]
697
+ #[must_use]
698
+ pub fn must_use(error: Error) -> Error {
699
+ error
700
+ }
701
+
702
+ #[doc(hidden)]
703
+ #[inline]
704
+ pub fn not(cond: impl Bool) -> bool {
705
+ cond.not()
706
+ }
707
+
708
+ mod not {
709
+ #[doc(hidden)]
710
+ pub trait Bool {
711
+ fn not(self) -> bool;
712
+ }
713
+
714
+ impl Bool for bool {
715
+ #[inline]
716
+ fn not(self) -> bool {
717
+ !self
718
+ }
719
+ }
720
+
721
+ impl Bool for &bool {
722
+ #[inline]
723
+ fn not(self) -> bool {
724
+ !*self
725
+ }
726
+ }
727
+ }
728
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/macros.rs ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// Return early with an error.
2
+ ///
3
+ /// This macro is equivalent to
4
+ /// <code>return Err([anyhow!($args\...)][anyhow!])</code>.
5
+ ///
6
+ /// The surrounding function's or closure's return value is required to be
7
+ /// <code>Result&lt;_, [anyhow::Error][crate::Error]&gt;</code>.
8
+ ///
9
+ /// [anyhow!]: crate::anyhow
10
+ ///
11
+ /// # Example
12
+ ///
13
+ /// ```
14
+ /// # use anyhow::{bail, Result};
15
+ /// #
16
+ /// # fn has_permission(user: usize, resource: usize) -> bool {
17
+ /// # true
18
+ /// # }
19
+ /// #
20
+ /// # fn main() -> Result<()> {
21
+ /// # let user = 0;
22
+ /// # let resource = 0;
23
+ /// #
24
+ /// if !has_permission(user, resource) {
25
+ /// bail!("permission denied for accessing {}", resource);
26
+ /// }
27
+ /// # Ok(())
28
+ /// # }
29
+ /// ```
30
+ ///
31
+ /// ```
32
+ /// # use anyhow::{bail, Result};
33
+ /// # use thiserror::Error;
34
+ /// #
35
+ /// # const MAX_DEPTH: usize = 1;
36
+ /// #
37
+ /// #[derive(Error, Debug)]
38
+ /// enum ScienceError {
39
+ /// #[error("recursion limit exceeded")]
40
+ /// RecursionLimitExceeded,
41
+ /// # #[error("...")]
42
+ /// # More = (stringify! {
43
+ /// ...
44
+ /// # }, 1).1,
45
+ /// }
46
+ ///
47
+ /// # fn main() -> Result<()> {
48
+ /// # let depth = 0;
49
+ /// #
50
+ /// if depth > MAX_DEPTH {
51
+ /// bail!(ScienceError::RecursionLimitExceeded);
52
+ /// }
53
+ /// # Ok(())
54
+ /// # }
55
+ /// ```
56
+ #[macro_export]
57
+ #[cfg_attr(not(anyhow_no_clippy_format_args), clippy::format_args)]
58
+ macro_rules! bail {
59
+ ($msg:literal $(,)?) => {
60
+ return $crate::__private::Err($crate::__anyhow!($msg))
61
+ };
62
+ ($err:expr $(,)?) => {
63
+ return $crate::__private::Err($crate::__anyhow!($err))
64
+ };
65
+ ($fmt:expr, $($arg:tt)*) => {
66
+ return $crate::__private::Err($crate::__anyhow!($fmt, $($arg)*))
67
+ };
68
+ }
69
+
70
+ macro_rules! __ensure {
71
+ ($ensure:item) => {
72
+ /// Return early with an error if a condition is not satisfied.
73
+ ///
74
+ /// This macro is equivalent to
75
+ /// <code>if !$cond { return Err([anyhow!($args\...)][anyhow!]); }</code>.
76
+ ///
77
+ /// The surrounding function's or closure's return value is required to be
78
+ /// <code>Result&lt;_, [anyhow::Error][crate::Error]&gt;</code>.
79
+ ///
80
+ /// Analogously to `assert!`, `ensure!` takes a condition and exits the function
81
+ /// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`
82
+ /// rather than panicking.
83
+ ///
84
+ /// [anyhow!]: crate::anyhow
85
+ ///
86
+ /// # Example
87
+ ///
88
+ /// ```
89
+ /// # use anyhow::{ensure, Result};
90
+ /// #
91
+ /// # fn main() -> Result<()> {
92
+ /// # let user = 0;
93
+ /// #
94
+ /// ensure!(user == 0, "only user 0 is allowed");
95
+ /// # Ok(())
96
+ /// # }
97
+ /// ```
98
+ ///
99
+ /// ```
100
+ /// # use anyhow::{ensure, Result};
101
+ /// # use thiserror::Error;
102
+ /// #
103
+ /// # const MAX_DEPTH: usize = 1;
104
+ /// #
105
+ /// #[derive(Error, Debug)]
106
+ /// enum ScienceError {
107
+ /// #[error("recursion limit exceeded")]
108
+ /// RecursionLimitExceeded,
109
+ /// # #[error("...")]
110
+ /// # More = (stringify! {
111
+ /// ...
112
+ /// # }, 1).1,
113
+ /// }
114
+ ///
115
+ /// # fn main() -> Result<()> {
116
+ /// # let depth = 0;
117
+ /// #
118
+ /// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);
119
+ /// # Ok(())
120
+ /// # }
121
+ /// ```
122
+ $ensure
123
+ };
124
+ }
125
+
126
+ #[cfg(doc)]
127
+ __ensure![
128
+ #[macro_export]
129
+ macro_rules! ensure {
130
+ ($cond:expr $(,)?) => {
131
+ if !$cond {
132
+ return $crate::__private::Err($crate::Error::msg(
133
+ $crate::__private::concat!("Condition failed: `", $crate::__private::stringify!($cond), "`")
134
+ ));
135
+ }
136
+ };
137
+ ($cond:expr, $msg:literal $(,)?) => {
138
+ if !$cond {
139
+ return $crate::__private::Err($crate::__anyhow!($msg));
140
+ }
141
+ };
142
+ ($cond:expr, $err:expr $(,)?) => {
143
+ if !$cond {
144
+ return $crate::__private::Err($crate::__anyhow!($err));
145
+ }
146
+ };
147
+ ($cond:expr, $fmt:expr, $($arg:tt)*) => {
148
+ if !$cond {
149
+ return $crate::__private::Err($crate::__anyhow!($fmt, $($arg)*));
150
+ }
151
+ };
152
+ }
153
+ ];
154
+
155
+ #[cfg(not(doc))]
156
+ __ensure![
157
+ #[macro_export]
158
+ #[cfg_attr(not(anyhow_no_clippy_format_args), clippy::format_args)]
159
+ macro_rules! ensure {
160
+ ($($tt:tt)*) => {
161
+ $crate::__parse_ensure!(
162
+ /* state */ 0
163
+ /* stack */ ()
164
+ /* bail */ ($($tt)*)
165
+ /* fuel */ (~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~)
166
+ /* parse */ {()}
167
+ /* dup */ ($($tt)*)
168
+ /* rest */ $($tt)*
169
+ )
170
+ };
171
+ }
172
+ ];
173
+
174
+ /// Construct an ad-hoc error from a string or existing non-`anyhow` error
175
+ /// value.
176
+ ///
177
+ /// This evaluates to an [`Error`][crate::Error]. It can take either just a
178
+ /// string, or a format string with arguments. It also can take any custom type
179
+ /// which implements `Debug` and `Display`.
180
+ ///
181
+ /// If called with a single argument whose type implements `std::error::Error`
182
+ /// (in addition to `Debug` and `Display`, which are always required), then that
183
+ /// Error impl's `source` is preserved as the `source` of the resulting
184
+ /// `anyhow::Error`.
185
+ ///
186
+ /// # Example
187
+ ///
188
+ /// ```
189
+ /// # type V = ();
190
+ /// #
191
+ /// use anyhow::{anyhow, Result};
192
+ ///
193
+ /// fn lookup(key: &str) -> Result<V> {
194
+ /// if key.len() != 16 {
195
+ /// return Err(anyhow!("key length must be 16 characters, got {:?}", key));
196
+ /// }
197
+ ///
198
+ /// // ...
199
+ /// # Ok(())
200
+ /// }
201
+ /// ```
202
+ #[macro_export]
203
+ #[cfg_attr(not(anyhow_no_clippy_format_args), clippy::format_args)]
204
+ macro_rules! anyhow {
205
+ ($msg:literal $(,)?) => {
206
+ $crate::__private::must_use({
207
+ let error = $crate::__private::format_err($crate::__private::format_args!($msg));
208
+ error
209
+ })
210
+ };
211
+ ($err:expr $(,)?) => {
212
+ $crate::__private::must_use({
213
+ use $crate::__private::kind::*;
214
+ let error = match $err {
215
+ error => (&error).anyhow_kind().new(error),
216
+ };
217
+ error
218
+ })
219
+ };
220
+ ($fmt:expr, $($arg:tt)*) => {
221
+ $crate::Error::msg($crate::__private::format!($fmt, $($arg)*))
222
+ };
223
+ }
224
+
225
+ // Not public API. This is used in the implementation of some of the other
226
+ // macros, in which the must_use call is not needed because the value is known
227
+ // to be used.
228
+ #[doc(hidden)]
229
+ #[macro_export]
230
+ macro_rules! __anyhow {
231
+ ($msg:literal $(,)?) => ({
232
+ let error = $crate::__private::format_err($crate::__private::format_args!($msg));
233
+ error
234
+ });
235
+ ($err:expr $(,)?) => ({
236
+ use $crate::__private::kind::*;
237
+ let error = match $err {
238
+ error => (&error).anyhow_kind().new(error),
239
+ };
240
+ error
241
+ });
242
+ ($fmt:expr, $($arg:tt)*) => {
243
+ $crate::Error::msg($crate::__private::format!($fmt, $($arg)*))
244
+ };
245
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/nightly.rs ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This code exercises the surface area that we expect of the Error generic
2
+ // member access API. If the current toolchain is able to compile it, then
3
+ // anyhow is able to provide backtrace support.
4
+
5
+ #![cfg_attr(anyhow_build_probe, feature(error_generic_member_access))]
6
+
7
+ use core::error::{self, Error};
8
+ use std::backtrace::Backtrace;
9
+
10
+ pub use core::error::Request;
11
+
12
+ #[cfg(anyhow_build_probe)]
13
+ const _: () = {
14
+ use core::fmt::{self, Debug, Display};
15
+
16
+ struct MyError(Backtrace);
17
+
18
+ impl Debug for MyError {
19
+ fn fmt(&self, _formatter: &mut fmt::Formatter) -> fmt::Result {
20
+ unimplemented!()
21
+ }
22
+ }
23
+
24
+ impl Display for MyError {
25
+ fn fmt(&self, _formatter: &mut fmt::Formatter) -> fmt::Result {
26
+ unimplemented!()
27
+ }
28
+ }
29
+
30
+ impl Error for MyError {
31
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
32
+ provide_ref_backtrace(request, &self.0);
33
+ }
34
+ }
35
+ };
36
+
37
+ // Include in sccache cache key.
38
+ #[cfg(anyhow_build_probe)]
39
+ const _: Option<&str> = option_env!("RUSTC_BOOTSTRAP");
40
+
41
+ pub fn request_ref_backtrace(err: &dyn Error) -> Option<&Backtrace> {
42
+ request_ref::<Backtrace>(err)
43
+ }
44
+
45
+ fn request_ref<'a, T>(err: &'a (impl Error + ?Sized)) -> Option<&'a T>
46
+ where
47
+ T: 'static + ?Sized,
48
+ {
49
+ error::request_ref::<T>(err)
50
+ }
51
+
52
+ pub fn provide_ref_backtrace<'a>(request: &mut Request<'a>, backtrace: &'a Backtrace) {
53
+ Request::provide_ref(request, backtrace);
54
+ }
55
+
56
+ pub fn provide<'a>(err: &'a (impl Error + ?Sized), request: &mut Request<'a>) {
57
+ Error::provide(err, request);
58
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/ptr.rs ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use alloc::boxed::Box;
2
+ use core::marker::PhantomData;
3
+ use core::ptr::NonNull;
4
+
5
+ #[repr(transparent)]
6
+ pub struct Own<T>
7
+ where
8
+ T: ?Sized,
9
+ {
10
+ pub ptr: NonNull<T>,
11
+ }
12
+
13
+ unsafe impl<T> Send for Own<T> where T: ?Sized {}
14
+
15
+ unsafe impl<T> Sync for Own<T> where T: ?Sized {}
16
+
17
+ impl<T> Copy for Own<T> where T: ?Sized {}
18
+
19
+ impl<T> Clone for Own<T>
20
+ where
21
+ T: ?Sized,
22
+ {
23
+ fn clone(&self) -> Self {
24
+ *self
25
+ }
26
+ }
27
+
28
+ impl<T> Own<T>
29
+ where
30
+ T: ?Sized,
31
+ {
32
+ pub fn new(ptr: Box<T>) -> Self {
33
+ Own {
34
+ ptr: unsafe { NonNull::new_unchecked(Box::into_raw(ptr)) },
35
+ }
36
+ }
37
+
38
+ pub fn cast<U: CastTo>(self) -> Own<U::Target> {
39
+ Own {
40
+ ptr: self.ptr.cast(),
41
+ }
42
+ }
43
+
44
+ pub unsafe fn boxed(self) -> Box<T> {
45
+ unsafe { Box::from_raw(self.ptr.as_ptr()) }
46
+ }
47
+
48
+ pub fn by_ref(&self) -> Ref<T> {
49
+ Ref {
50
+ ptr: self.ptr,
51
+ lifetime: PhantomData,
52
+ }
53
+ }
54
+
55
+ pub fn by_mut(&mut self) -> Mut<T> {
56
+ Mut {
57
+ ptr: self.ptr,
58
+ lifetime: PhantomData,
59
+ }
60
+ }
61
+ }
62
+
63
+ #[repr(transparent)]
64
+ pub struct Ref<'a, T>
65
+ where
66
+ T: ?Sized,
67
+ {
68
+ pub ptr: NonNull<T>,
69
+ lifetime: PhantomData<&'a T>,
70
+ }
71
+
72
+ impl<'a, T> Copy for Ref<'a, T> where T: ?Sized {}
73
+
74
+ impl<'a, T> Clone for Ref<'a, T>
75
+ where
76
+ T: ?Sized,
77
+ {
78
+ fn clone(&self) -> Self {
79
+ *self
80
+ }
81
+ }
82
+
83
+ impl<'a, T> Ref<'a, T>
84
+ where
85
+ T: ?Sized,
86
+ {
87
+ pub fn new(ptr: &'a T) -> Self {
88
+ Ref {
89
+ ptr: NonNull::from(ptr),
90
+ lifetime: PhantomData,
91
+ }
92
+ }
93
+
94
+ pub fn from_raw(ptr: NonNull<T>) -> Self {
95
+ Ref {
96
+ ptr,
97
+ lifetime: PhantomData,
98
+ }
99
+ }
100
+
101
+ pub fn cast<U: CastTo>(self) -> Ref<'a, U::Target> {
102
+ Ref {
103
+ ptr: self.ptr.cast(),
104
+ lifetime: PhantomData,
105
+ }
106
+ }
107
+
108
+ pub fn by_mut(self) -> Mut<'a, T> {
109
+ Mut {
110
+ ptr: self.ptr,
111
+ lifetime: PhantomData,
112
+ }
113
+ }
114
+
115
+ pub fn as_ptr(self) -> *const T {
116
+ self.ptr.as_ptr().cast_const()
117
+ }
118
+
119
+ pub unsafe fn deref(self) -> &'a T {
120
+ unsafe { &*self.ptr.as_ptr() }
121
+ }
122
+ }
123
+
124
+ #[repr(transparent)]
125
+ pub struct Mut<'a, T>
126
+ where
127
+ T: ?Sized,
128
+ {
129
+ pub ptr: NonNull<T>,
130
+ lifetime: PhantomData<&'a mut T>,
131
+ }
132
+
133
+ impl<'a, T> Copy for Mut<'a, T> where T: ?Sized {}
134
+
135
+ impl<'a, T> Clone for Mut<'a, T>
136
+ where
137
+ T: ?Sized,
138
+ {
139
+ fn clone(&self) -> Self {
140
+ *self
141
+ }
142
+ }
143
+
144
+ impl<'a, T> Mut<'a, T>
145
+ where
146
+ T: ?Sized,
147
+ {
148
+ pub fn cast<U: CastTo>(self) -> Mut<'a, U::Target> {
149
+ Mut {
150
+ ptr: self.ptr.cast(),
151
+ lifetime: PhantomData,
152
+ }
153
+ }
154
+
155
+ pub fn by_ref(self) -> Ref<'a, T> {
156
+ Ref {
157
+ ptr: self.ptr,
158
+ lifetime: PhantomData,
159
+ }
160
+ }
161
+
162
+ pub fn extend<'b>(self) -> Mut<'b, T> {
163
+ Mut {
164
+ ptr: self.ptr,
165
+ lifetime: PhantomData,
166
+ }
167
+ }
168
+
169
+ pub unsafe fn deref_mut(self) -> &'a mut T {
170
+ unsafe { &mut *self.ptr.as_ptr() }
171
+ }
172
+ }
173
+
174
+ impl<'a, T> Mut<'a, T> {
175
+ pub unsafe fn read(self) -> T {
176
+ unsafe { self.ptr.as_ptr().read() }
177
+ }
178
+ }
179
+
180
+ // Force turbofish on all calls of `.cast::<U>()`.
181
+ pub trait CastTo {
182
+ type Target;
183
+ }
184
+
185
+ impl<T> CastTo for T {
186
+ type Target = T;
187
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/src/wrapper.rs ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::StdError;
2
+ use core::fmt::{self, Debug, Display};
3
+
4
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
5
+ use alloc::boxed::Box;
6
+
7
+ #[cfg(error_generic_member_access)]
8
+ use crate::nightly::{self, Request};
9
+
10
+ #[repr(transparent)]
11
+ pub struct MessageError<M>(pub M);
12
+
13
+ impl<M> Debug for MessageError<M>
14
+ where
15
+ M: Display + Debug,
16
+ {
17
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18
+ Debug::fmt(&self.0, f)
19
+ }
20
+ }
21
+
22
+ impl<M> Display for MessageError<M>
23
+ where
24
+ M: Display + Debug,
25
+ {
26
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27
+ Display::fmt(&self.0, f)
28
+ }
29
+ }
30
+
31
+ impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}
32
+
33
+ #[repr(transparent)]
34
+ pub struct DisplayError<M>(pub M);
35
+
36
+ impl<M> Debug for DisplayError<M>
37
+ where
38
+ M: Display,
39
+ {
40
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
41
+ Display::fmt(&self.0, f)
42
+ }
43
+ }
44
+
45
+ impl<M> Display for DisplayError<M>
46
+ where
47
+ M: Display,
48
+ {
49
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50
+ Display::fmt(&self.0, f)
51
+ }
52
+ }
53
+
54
+ impl<M> StdError for DisplayError<M> where M: Display + 'static {}
55
+
56
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
57
+ #[repr(transparent)]
58
+ pub struct BoxedError(pub Box<dyn StdError + Send + Sync>);
59
+
60
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
61
+ impl Debug for BoxedError {
62
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63
+ Debug::fmt(&self.0, f)
64
+ }
65
+ }
66
+
67
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
68
+ impl Display for BoxedError {
69
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70
+ Display::fmt(&self.0, f)
71
+ }
72
+ }
73
+
74
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
75
+ impl StdError for BoxedError {
76
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
77
+ self.0.source()
78
+ }
79
+
80
+ #[cfg(error_generic_member_access)]
81
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
82
+ nightly::provide(&*self.0, request);
83
+ }
84
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/common/mod.rs ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use anyhow::{bail, Result};
2
+ use std::io;
3
+
4
+ pub fn bail_literal() -> Result<()> {
5
+ bail!("oh no!");
6
+ }
7
+
8
+ pub fn bail_fmt() -> Result<()> {
9
+ bail!("{} {}!", "oh", "no");
10
+ }
11
+
12
+ pub fn bail_error() -> Result<()> {
13
+ bail!(io::Error::new(io::ErrorKind::Other, "oh no!"));
14
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/compiletest.rs ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #[rustversion::attr(not(nightly), ignore = "requires nightly")]
2
+ #[cfg_attr(miri, ignore = "incompatible with miri")]
3
+ #[test]
4
+ fn ui() {
5
+ let t = trybuild::TestCases::new();
6
+ t.compile_fail("tests/ui/*.rs");
7
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/drop/mod.rs ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(clippy::module_name_repetitions)]
2
+
3
+ use std::error::Error as StdError;
4
+ use std::fmt::{self, Display};
5
+ use std::sync::atomic::{AtomicBool, Ordering};
6
+ use std::sync::Arc;
7
+
8
+ #[derive(Debug)]
9
+ pub struct Flag {
10
+ atomic: Arc<AtomicBool>,
11
+ }
12
+
13
+ impl Flag {
14
+ pub fn new() -> Self {
15
+ Flag {
16
+ atomic: Arc::new(AtomicBool::new(false)),
17
+ }
18
+ }
19
+
20
+ pub fn get(&self) -> bool {
21
+ self.atomic.load(Ordering::Relaxed)
22
+ }
23
+ }
24
+
25
+ #[derive(Debug)]
26
+ pub struct DetectDrop {
27
+ has_dropped: Flag,
28
+ }
29
+
30
+ impl DetectDrop {
31
+ pub fn new(has_dropped: &Flag) -> Self {
32
+ DetectDrop {
33
+ has_dropped: Flag {
34
+ atomic: Arc::clone(&has_dropped.atomic),
35
+ },
36
+ }
37
+ }
38
+ }
39
+
40
+ impl StdError for DetectDrop {}
41
+
42
+ impl Display for DetectDrop {
43
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44
+ write!(f, "oh no!")
45
+ }
46
+ }
47
+
48
+ impl Drop for DetectDrop {
49
+ fn drop(&mut self) {
50
+ let already_dropped = self.has_dropped.atomic.swap(true, Ordering::Relaxed);
51
+ assert!(!already_dropped);
52
+ }
53
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_autotrait.rs ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(clippy::extra_unused_type_parameters)]
2
+
3
+ use anyhow::Error;
4
+ use std::panic::{RefUnwindSafe, UnwindSafe};
5
+
6
+ #[test]
7
+ fn test_send() {
8
+ fn assert_send<T: Send>() {}
9
+ assert_send::<Error>();
10
+ }
11
+
12
+ #[test]
13
+ fn test_sync() {
14
+ fn assert_sync<T: Sync>() {}
15
+ assert_sync::<Error>();
16
+ }
17
+
18
+ #[test]
19
+ fn test_unwind_safe() {
20
+ fn assert_unwind_safe<T: UnwindSafe>() {}
21
+ assert_unwind_safe::<Error>();
22
+ }
23
+
24
+ #[test]
25
+ fn test_ref_unwind_safe() {
26
+ fn assert_ref_unwind_safe<T: RefUnwindSafe>() {}
27
+ assert_ref_unwind_safe::<Error>();
28
+ }
29
+
30
+ #[test]
31
+ fn test_unpin() {
32
+ fn assert_unpin<T: Unpin>() {}
33
+ assert_unpin::<Error>();
34
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_backtrace.rs ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(clippy::let_underscore_untyped)]
2
+
3
+ #[rustversion::not(nightly)]
4
+ #[ignore = "requires nightly"]
5
+ #[test]
6
+ fn test_backtrace() {}
7
+
8
+ #[rustversion::nightly]
9
+ #[test]
10
+ fn test_backtrace() {
11
+ use anyhow::anyhow;
12
+
13
+ let error = anyhow!("oh no!");
14
+ let _ = error.backtrace();
15
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_boxed.rs ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(
2
+ // Clippy bug: https://github.com/rust-lang/rust-clippy/issues/7422
3
+ clippy::nonstandard_macro_braces,
4
+ )]
5
+
6
+ use anyhow::anyhow;
7
+ use std::error::Error as StdError;
8
+ use std::io;
9
+ use thiserror::Error;
10
+
11
+ #[derive(Error, Debug)]
12
+ #[error("outer")]
13
+ struct MyError {
14
+ source: io::Error,
15
+ }
16
+
17
+ #[test]
18
+ fn test_boxed_str() {
19
+ let error = Box::<dyn StdError + Send + Sync>::from("oh no!");
20
+ let error = anyhow!(error);
21
+ assert_eq!("oh no!", error.to_string());
22
+ assert_eq!(
23
+ "oh no!",
24
+ error
25
+ .downcast_ref::<Box<dyn StdError + Send + Sync>>()
26
+ .unwrap()
27
+ .to_string()
28
+ );
29
+ }
30
+
31
+ #[test]
32
+ fn test_boxed_thiserror() {
33
+ let error = MyError {
34
+ source: io::Error::new(io::ErrorKind::Other, "oh no!"),
35
+ };
36
+ let error = anyhow!(error);
37
+ assert_eq!("oh no!", error.source().unwrap().to_string());
38
+ }
39
+
40
+ #[test]
41
+ fn test_boxed_anyhow() {
42
+ let error = anyhow!("oh no!").context("it failed");
43
+ let error = anyhow!(error);
44
+ assert_eq!("oh no!", error.source().unwrap().to_string());
45
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_chain.rs ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use anyhow::{anyhow, Chain, Error};
2
+
3
+ fn error() -> Error {
4
+ anyhow!({ 0 }).context(1).context(2).context(3)
5
+ }
6
+
7
+ #[test]
8
+ fn test_iter() {
9
+ let e = error();
10
+ let mut chain = e.chain();
11
+ assert_eq!("3", chain.next().unwrap().to_string());
12
+ assert_eq!("2", chain.next().unwrap().to_string());
13
+ assert_eq!("1", chain.next().unwrap().to_string());
14
+ assert_eq!("0", chain.next().unwrap().to_string());
15
+ assert!(chain.next().is_none());
16
+ assert!(chain.next_back().is_none());
17
+ }
18
+
19
+ #[test]
20
+ fn test_rev() {
21
+ let e = error();
22
+ let mut chain = e.chain().rev();
23
+ assert_eq!("0", chain.next().unwrap().to_string());
24
+ assert_eq!("1", chain.next().unwrap().to_string());
25
+ assert_eq!("2", chain.next().unwrap().to_string());
26
+ assert_eq!("3", chain.next().unwrap().to_string());
27
+ assert!(chain.next().is_none());
28
+ assert!(chain.next_back().is_none());
29
+ }
30
+
31
+ #[test]
32
+ fn test_len() {
33
+ let e = error();
34
+ let mut chain = e.chain();
35
+ assert_eq!(4, chain.len());
36
+ assert_eq!((4, Some(4)), chain.size_hint());
37
+ assert_eq!("3", chain.next().unwrap().to_string());
38
+ assert_eq!(3, chain.len());
39
+ assert_eq!((3, Some(3)), chain.size_hint());
40
+ assert_eq!("0", chain.next_back().unwrap().to_string());
41
+ assert_eq!(2, chain.len());
42
+ assert_eq!((2, Some(2)), chain.size_hint());
43
+ assert_eq!("2", chain.next().unwrap().to_string());
44
+ assert_eq!(1, chain.len());
45
+ assert_eq!((1, Some(1)), chain.size_hint());
46
+ assert_eq!("1", chain.next_back().unwrap().to_string());
47
+ assert_eq!(0, chain.len());
48
+ assert_eq!((0, Some(0)), chain.size_hint());
49
+ assert!(chain.next().is_none());
50
+ }
51
+
52
+ #[test]
53
+ fn test_default() {
54
+ let mut c = Chain::default();
55
+ assert!(c.next().is_none());
56
+ }
57
+
58
+ #[test]
59
+ #[allow(clippy::redundant_clone)]
60
+ fn test_clone() {
61
+ let e = error();
62
+ let mut chain = e.chain().clone();
63
+ assert_eq!("3", chain.next().unwrap().to_string());
64
+ assert_eq!("2", chain.next().unwrap().to_string());
65
+ assert_eq!("1", chain.next().unwrap().to_string());
66
+ assert_eq!("0", chain.next().unwrap().to_string());
67
+ assert!(chain.next().is_none());
68
+ assert!(chain.next_back().is_none());
69
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_context.rs ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(
2
+ // Clippy bug: https://github.com/rust-lang/rust-clippy/issues/7422
3
+ clippy::nonstandard_macro_braces,
4
+ )]
5
+
6
+ mod drop;
7
+
8
+ use crate::drop::{DetectDrop, Flag};
9
+ use anyhow::{Context, Error, Result};
10
+ use std::fmt::{self, Display};
11
+ use thiserror::Error;
12
+
13
+ // https://github.com/dtolnay/anyhow/issues/18
14
+ #[test]
15
+ fn test_inference() -> Result<()> {
16
+ let x = "1";
17
+ let y: u32 = x.parse().context("...")?;
18
+ assert_eq!(y, 1);
19
+ Ok(())
20
+ }
21
+
22
+ macro_rules! context_type {
23
+ ($name:ident) => {
24
+ #[derive(Debug)]
25
+ struct $name {
26
+ message: &'static str,
27
+ #[allow(dead_code)]
28
+ drop: DetectDrop,
29
+ }
30
+
31
+ impl Display for $name {
32
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33
+ f.write_str(self.message)
34
+ }
35
+ }
36
+ };
37
+ }
38
+
39
+ context_type!(HighLevel);
40
+ context_type!(MidLevel);
41
+
42
+ #[derive(Error, Debug)]
43
+ #[error("{message}")]
44
+ struct LowLevel {
45
+ message: &'static str,
46
+ drop: DetectDrop,
47
+ }
48
+
49
+ struct Dropped {
50
+ low: Flag,
51
+ mid: Flag,
52
+ high: Flag,
53
+ }
54
+
55
+ impl Dropped {
56
+ fn none(&self) -> bool {
57
+ !self.low.get() && !self.mid.get() && !self.high.get()
58
+ }
59
+
60
+ fn all(&self) -> bool {
61
+ self.low.get() && self.mid.get() && self.high.get()
62
+ }
63
+ }
64
+
65
+ fn make_chain() -> (Error, Dropped) {
66
+ let dropped = Dropped {
67
+ low: Flag::new(),
68
+ mid: Flag::new(),
69
+ high: Flag::new(),
70
+ };
71
+
72
+ let low = LowLevel {
73
+ message: "no such file or directory",
74
+ drop: DetectDrop::new(&dropped.low),
75
+ };
76
+
77
+ // impl Context for Result<T, E>
78
+ let mid = Err::<(), LowLevel>(low)
79
+ .context(MidLevel {
80
+ message: "failed to load config",
81
+ drop: DetectDrop::new(&dropped.mid),
82
+ })
83
+ .unwrap_err();
84
+
85
+ // impl Context for Result<T, Error>
86
+ let high = Err::<(), Error>(mid)
87
+ .context(HighLevel {
88
+ message: "failed to start server",
89
+ drop: DetectDrop::new(&dropped.high),
90
+ })
91
+ .unwrap_err();
92
+
93
+ (high, dropped)
94
+ }
95
+
96
+ #[test]
97
+ fn test_downcast_ref() {
98
+ let (err, dropped) = make_chain();
99
+
100
+ assert!(!err.is::<String>());
101
+ assert!(err.downcast_ref::<String>().is_none());
102
+
103
+ assert!(err.is::<HighLevel>());
104
+ let high = err.downcast_ref::<HighLevel>().unwrap();
105
+ assert_eq!(high.to_string(), "failed to start server");
106
+
107
+ assert!(err.is::<MidLevel>());
108
+ let mid = err.downcast_ref::<MidLevel>().unwrap();
109
+ assert_eq!(mid.to_string(), "failed to load config");
110
+
111
+ assert!(err.is::<LowLevel>());
112
+ let low = err.downcast_ref::<LowLevel>().unwrap();
113
+ assert_eq!(low.to_string(), "no such file or directory");
114
+
115
+ assert!(dropped.none());
116
+ drop(err);
117
+ assert!(dropped.all());
118
+ }
119
+
120
+ #[test]
121
+ fn test_downcast_high() {
122
+ let (err, dropped) = make_chain();
123
+
124
+ let err = err.downcast::<HighLevel>().unwrap();
125
+ assert!(!dropped.high.get());
126
+ assert!(dropped.low.get() && dropped.mid.get());
127
+
128
+ drop(err);
129
+ assert!(dropped.all());
130
+ }
131
+
132
+ #[test]
133
+ fn test_downcast_mid() {
134
+ let (err, dropped) = make_chain();
135
+
136
+ let err = err.downcast::<MidLevel>().unwrap();
137
+ assert!(!dropped.mid.get());
138
+ assert!(dropped.low.get() && dropped.high.get());
139
+
140
+ drop(err);
141
+ assert!(dropped.all());
142
+ }
143
+
144
+ #[test]
145
+ fn test_downcast_low() {
146
+ let (err, dropped) = make_chain();
147
+
148
+ let err = err.downcast::<LowLevel>().unwrap();
149
+ assert!(!dropped.low.get());
150
+ assert!(dropped.mid.get() && dropped.high.get());
151
+
152
+ drop(err);
153
+ assert!(dropped.all());
154
+ }
155
+
156
+ #[test]
157
+ fn test_unsuccessful_downcast() {
158
+ let (err, dropped) = make_chain();
159
+
160
+ let err = err.downcast::<String>().unwrap_err();
161
+ assert!(dropped.none());
162
+
163
+ drop(err);
164
+ assert!(dropped.all());
165
+ }
166
+
167
+ #[test]
168
+ fn test_root_cause() {
169
+ let (err, _) = make_chain();
170
+
171
+ assert_eq!(err.root_cause().to_string(), "no such file or directory");
172
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_convert.rs ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(clippy::unnecessary_wraps)]
2
+
3
+ mod drop;
4
+
5
+ use self::drop::{DetectDrop, Flag};
6
+ use anyhow::{Error, Result};
7
+ use std::error::Error as StdError;
8
+
9
+ #[test]
10
+ fn test_convert() {
11
+ let has_dropped = Flag::new();
12
+ let error = Error::new(DetectDrop::new(&has_dropped));
13
+ let box_dyn = Box::<dyn StdError>::from(error);
14
+ assert_eq!("oh no!", box_dyn.to_string());
15
+ drop(box_dyn);
16
+ assert!(has_dropped.get());
17
+ }
18
+
19
+ #[test]
20
+ fn test_convert_send() {
21
+ let has_dropped = Flag::new();
22
+ let error = Error::new(DetectDrop::new(&has_dropped));
23
+ let box_dyn = Box::<dyn StdError + Send>::from(error);
24
+ assert_eq!("oh no!", box_dyn.to_string());
25
+ drop(box_dyn);
26
+ assert!(has_dropped.get());
27
+ }
28
+
29
+ #[test]
30
+ fn test_convert_send_sync() {
31
+ let has_dropped = Flag::new();
32
+ let error = Error::new(DetectDrop::new(&has_dropped));
33
+ let box_dyn = Box::<dyn StdError + Send + Sync>::from(error);
34
+ assert_eq!("oh no!", box_dyn.to_string());
35
+ drop(box_dyn);
36
+ assert!(has_dropped.get());
37
+ }
38
+
39
+ #[test]
40
+ fn test_question_mark() -> Result<(), Box<dyn StdError>> {
41
+ fn f() -> Result<()> {
42
+ Ok(())
43
+ }
44
+ f()?;
45
+ Ok(())
46
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_downcast.rs ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(clippy::assertions_on_result_states, clippy::wildcard_imports)]
2
+
3
+ mod common;
4
+ mod drop;
5
+
6
+ use self::common::*;
7
+ use self::drop::{DetectDrop, Flag};
8
+ use anyhow::Error;
9
+ use std::error::Error as StdError;
10
+ use std::fmt::{self, Display};
11
+ use std::io;
12
+
13
+ #[test]
14
+ fn test_downcast() {
15
+ assert_eq!(
16
+ "oh no!",
17
+ bail_literal().unwrap_err().downcast::<&str>().unwrap(),
18
+ );
19
+ assert_eq!(
20
+ "oh no!",
21
+ bail_fmt().unwrap_err().downcast::<String>().unwrap(),
22
+ );
23
+ assert_eq!(
24
+ "oh no!",
25
+ bail_error()
26
+ .unwrap_err()
27
+ .downcast::<io::Error>()
28
+ .unwrap()
29
+ .to_string(),
30
+ );
31
+ }
32
+
33
+ #[test]
34
+ fn test_downcast_ref() {
35
+ assert_eq!(
36
+ "oh no!",
37
+ *bail_literal().unwrap_err().downcast_ref::<&str>().unwrap(),
38
+ );
39
+ assert_eq!(
40
+ "oh no!",
41
+ bail_fmt().unwrap_err().downcast_ref::<String>().unwrap(),
42
+ );
43
+ assert_eq!(
44
+ "oh no!",
45
+ bail_error()
46
+ .unwrap_err()
47
+ .downcast_ref::<io::Error>()
48
+ .unwrap()
49
+ .to_string(),
50
+ );
51
+ }
52
+
53
+ #[test]
54
+ fn test_downcast_mut() {
55
+ assert_eq!(
56
+ "oh no!",
57
+ *bail_literal().unwrap_err().downcast_mut::<&str>().unwrap(),
58
+ );
59
+ assert_eq!(
60
+ "oh no!",
61
+ bail_fmt().unwrap_err().downcast_mut::<String>().unwrap(),
62
+ );
63
+ assert_eq!(
64
+ "oh no!",
65
+ bail_error()
66
+ .unwrap_err()
67
+ .downcast_mut::<io::Error>()
68
+ .unwrap()
69
+ .to_string(),
70
+ );
71
+
72
+ let mut bailed = bail_fmt().unwrap_err();
73
+ *bailed.downcast_mut::<String>().unwrap() = "clobber".to_string();
74
+ assert_eq!(bailed.downcast_ref::<String>().unwrap(), "clobber");
75
+ assert_eq!(bailed.downcast_mut::<String>().unwrap(), "clobber");
76
+ assert_eq!(bailed.downcast::<String>().unwrap(), "clobber");
77
+ }
78
+
79
+ #[test]
80
+ fn test_drop() {
81
+ let has_dropped = Flag::new();
82
+ let error = Error::new(DetectDrop::new(&has_dropped));
83
+ drop(error.downcast::<DetectDrop>().unwrap());
84
+ assert!(has_dropped.get());
85
+ }
86
+
87
+ #[test]
88
+ fn test_as_ref() {
89
+ let error = bail_error().unwrap_err();
90
+ let ref_dyn: &dyn StdError = error.as_ref();
91
+ assert_eq!("oh no!", ref_dyn.to_string());
92
+ let ref_dyn_send_sync: &(dyn StdError + Send + Sync) = error.as_ref();
93
+ assert_eq!("oh no!", ref_dyn_send_sync.to_string());
94
+ }
95
+
96
+ #[test]
97
+ fn test_large_alignment() {
98
+ #[repr(align(64))]
99
+ #[derive(Debug)]
100
+ struct LargeAlignedError(&'static str);
101
+
102
+ impl Display for LargeAlignedError {
103
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104
+ f.write_str(self.0)
105
+ }
106
+ }
107
+
108
+ impl StdError for LargeAlignedError {}
109
+
110
+ let error = Error::new(LargeAlignedError("oh no!"));
111
+ assert_eq!(
112
+ "oh no!",
113
+ error.downcast_ref::<LargeAlignedError>().unwrap().0
114
+ );
115
+ }
116
+
117
+ #[test]
118
+ fn test_unsuccessful_downcast() {
119
+ let mut error = bail_error().unwrap_err();
120
+ assert!(error.downcast_ref::<&str>().is_none());
121
+ assert!(error.downcast_mut::<&str>().is_none());
122
+ assert!(error.downcast::<&str>().is_err());
123
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_ensure.rs ADDED
@@ -0,0 +1,756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(
2
+ clippy::bool_to_int_with_if,
3
+ clippy::char_lit_as_u8,
4
+ clippy::deref_addrof,
5
+ clippy::diverging_sub_expression,
6
+ clippy::erasing_op,
7
+ clippy::extra_unused_type_parameters,
8
+ clippy::if_same_then_else,
9
+ clippy::ifs_same_cond,
10
+ clippy::ignored_unit_patterns,
11
+ clippy::items_after_statements,
12
+ clippy::let_and_return,
13
+ clippy::let_underscore_untyped,
14
+ clippy::literal_string_with_formatting_args,
15
+ clippy::match_bool,
16
+ clippy::needless_else,
17
+ clippy::never_loop,
18
+ clippy::overly_complex_bool_expr,
19
+ clippy::ptr_cast_constness,
20
+ clippy::redundant_closure_call,
21
+ clippy::redundant_pattern_matching,
22
+ clippy::too_many_lines,
23
+ clippy::uninlined_format_args,
24
+ clippy::unit_arg,
25
+ clippy::unnecessary_cast,
26
+ clippy::while_immutable_condition,
27
+ clippy::zero_ptr,
28
+ irrefutable_let_patterns
29
+ )]
30
+
31
+ use self::Enum::Generic;
32
+ use anyhow::{anyhow, ensure, Chain, Error, Result};
33
+ use std::fmt::{self, Debug};
34
+ use std::iter;
35
+ use std::marker::{PhantomData, PhantomData as P};
36
+ use std::mem;
37
+ use std::ops::Add;
38
+ use std::ptr;
39
+
40
+ struct S;
41
+
42
+ impl<T> Add<T> for S {
43
+ type Output = bool;
44
+ fn add(self, rhs: T) -> Self::Output {
45
+ let _ = rhs;
46
+ false
47
+ }
48
+ }
49
+
50
+ trait Trait: Sized {
51
+ const V: usize = 0;
52
+ fn t(self, i: i32) -> i32 {
53
+ i
54
+ }
55
+ }
56
+
57
+ impl<T> Trait for T {}
58
+
59
+ enum Enum<T: ?Sized> {
60
+ #[allow(dead_code)]
61
+ Thing(PhantomData<T>),
62
+ Generic,
63
+ }
64
+
65
+ impl<T: ?Sized> PartialEq for Enum<T> {
66
+ fn eq(&self, rhs: &Self) -> bool {
67
+ mem::discriminant(self) == mem::discriminant(rhs)
68
+ }
69
+ }
70
+
71
+ impl<T: ?Sized> Debug for Enum<T> {
72
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
73
+ formatter.write_str("Generic")
74
+ }
75
+ }
76
+
77
+ #[track_caller]
78
+ fn assert_err<T: Debug>(result: impl FnOnce() -> Result<T>, expected: &'static str) {
79
+ let actual = result().unwrap_err().to_string();
80
+
81
+ // In general different rustc versions will format the interpolated lhs and
82
+ // rhs $:expr fragment with insignificant differences in whitespace or
83
+ // punctuation, so we check the message in full against nightly and do just
84
+ // a cursory test on older toolchains.
85
+ if rustversion::cfg!(nightly) && !cfg!(miri) {
86
+ assert_eq!(actual, expected);
87
+ } else {
88
+ assert_eq!(actual.contains(" vs "), expected.contains(" vs "));
89
+ }
90
+ }
91
+
92
+ #[test]
93
+ fn test_recursion() {
94
+ // Must not blow the default #[recursion_limit], which is 128.
95
+ #[rustfmt::skip]
96
+ let test = || Ok(ensure!(
97
+ false | false | false | false | false | false | false | false | false |
98
+ false | false | false | false | false | false | false | false | false |
99
+ false | false | false | false | false | false | false | false | false |
100
+ false | false | false | false | false | false | false | false | false |
101
+ false | false | false | false | false | false | false | false | false |
102
+ false | false | false | false | false | false | false | false | false |
103
+ false | false | false | false | false | false | false | false | false
104
+ ));
105
+
106
+ test().unwrap_err();
107
+ }
108
+
109
+ #[test]
110
+ fn test_low_precedence_control_flow() {
111
+ #[allow(unreachable_code)]
112
+ let test = || {
113
+ let val = loop {
114
+ // Break has lower precedence than the comparison operators so the
115
+ // expression here is `S + (break (1 == 1))`. It would be bad if the
116
+ // ensure macro partitioned this input into `(S + break 1) == (1)`
117
+ // because that means a different thing than what was written.
118
+ ensure!(S + break 1 == 1);
119
+ };
120
+ Ok(val)
121
+ };
122
+
123
+ assert!(test().unwrap());
124
+ }
125
+
126
+ #[test]
127
+ fn test_low_precedence_binary_operator() {
128
+ // Must not partition as `false == (true && false)`.
129
+ let test = || Ok(ensure!(false == true && false));
130
+ assert_err(test, "Condition failed: `false == true && false`");
131
+
132
+ // But outside the root level, it is fine.
133
+ let test = || Ok(ensure!(while false == true && false {} < ()));
134
+ assert_err(
135
+ test,
136
+ "Condition failed: `while false == true && false {} < ()` (() vs ())",
137
+ );
138
+
139
+ let a = 15;
140
+ let b = 3;
141
+ let test = || Ok(ensure!(a <= b || a - b <= 10));
142
+ assert_err(test, "Condition failed: `a <= b || a - b <= 10`");
143
+ }
144
+
145
+ #[test]
146
+ fn test_high_precedence_binary_operator() {
147
+ let a = 15;
148
+ let b = 3;
149
+ let test = || Ok(ensure!(a - b <= 10));
150
+ assert_err(test, "Condition failed: `a - b <= 10` (12 vs 10)");
151
+ }
152
+
153
+ #[test]
154
+ fn test_closure() {
155
+ // Must not partition as `(S + move) || (1 == 1)` by treating move as an
156
+ // identifier, nor as `(S + move || 1) == (1)` by misinterpreting the
157
+ // closure precedence.
158
+ let test = || Ok(ensure!(S + move || 1 == 1));
159
+ assert_err(test, "Condition failed: `S + move || 1 == 1`");
160
+
161
+ let test = || Ok(ensure!(S + || 1 == 1));
162
+ assert_err(test, "Condition failed: `S + || 1 == 1`");
163
+
164
+ // Must not partition as `S + ((move | ()) | 1) == 1` by treating those
165
+ // pipes as bitwise-or.
166
+ let test = || Ok(ensure!(S + move |()| 1 == 1));
167
+ assert_err(test, "Condition failed: `S + move |()| 1 == 1`");
168
+
169
+ let test = || Ok(ensure!(S + |()| 1 == 1));
170
+ assert_err(test, "Condition failed: `S + |()| 1 == 1`");
171
+ }
172
+
173
+ #[test]
174
+ fn test_unary() {
175
+ let mut x = &1;
176
+ let test = || Ok(ensure!(*x == 2));
177
+ assert_err(test, "Condition failed: `*x == 2` (1 vs 2)");
178
+
179
+ let test = || Ok(ensure!(!x == 1));
180
+ assert_err(test, "Condition failed: `!x == 1` (-2 vs 1)");
181
+
182
+ let test = || Ok(ensure!(-x == 1));
183
+ assert_err(test, "Condition failed: `-x == 1` (-1 vs 1)");
184
+
185
+ let test = || Ok(ensure!(&x == &&2));
186
+ assert_err(test, "Condition failed: `&x == &&2` (1 vs 2)");
187
+
188
+ let test = || Ok(ensure!(&mut x == *&&mut &2));
189
+ assert_err(test, "Condition failed: `&mut x == *&&mut &2` (1 vs 2)");
190
+ }
191
+
192
+ #[rustversion::since(1.82)]
193
+ #[test]
194
+ fn test_raw_addr() {
195
+ let mut x = 1;
196
+ let test = || Ok(ensure!(S + &raw const x != S + &raw mut x));
197
+ assert_err(
198
+ test,
199
+ "Condition failed: `S + &raw const x != S + &raw mut x` (false vs false)",
200
+ );
201
+ }
202
+
203
+ #[test]
204
+ fn test_if() {
205
+ #[rustfmt::skip]
206
+ let test = || Ok(ensure!(if false {}.t(1) == 2));
207
+ assert_err(test, "Condition failed: `if false {}.t(1) == 2` (1 vs 2)");
208
+
209
+ #[rustfmt::skip]
210
+ let test = || Ok(ensure!(if false {} else {}.t(1) == 2));
211
+ assert_err(
212
+ test,
213
+ "Condition failed: `if false {} else {}.t(1) == 2` (1 vs 2)",
214
+ );
215
+
216
+ #[rustfmt::skip]
217
+ let test = || Ok(ensure!(if false {} else if false {}.t(1) == 2));
218
+ assert_err(
219
+ test,
220
+ "Condition failed: `if false {} else if false {}.t(1) == 2` (1 vs 2)",
221
+ );
222
+
223
+ #[rustfmt::skip]
224
+ let test = || Ok(ensure!(if let 1 = 2 {}.t(1) == 2));
225
+ assert_err(
226
+ test,
227
+ "Condition failed: `if let 1 = 2 {}.t(1) == 2` (1 vs 2)",
228
+ );
229
+
230
+ #[rustfmt::skip]
231
+ let test = || Ok(ensure!(if let 1 | 2 = 2 {}.t(1) == 2));
232
+ assert_err(
233
+ test,
234
+ "Condition failed: `if let 1 | 2 = 2 {}.t(1) == 2` (1 vs 2)",
235
+ );
236
+
237
+ #[rustfmt::skip]
238
+ let test = || Ok(ensure!(if let | 1 | 2 = 2 {}.t(1) == 2));
239
+ assert_err(
240
+ test,
241
+ "Condition failed: `if let | 1 | 2 = 2 {}.t(1) == 2` (1 vs 2)",
242
+ );
243
+ }
244
+
245
+ #[test]
246
+ fn test_loop() {
247
+ #[rustfmt::skip]
248
+ let test = || Ok(ensure!(1 + loop { break 1 } == 1));
249
+ assert_err(
250
+ test,
251
+ "Condition failed: `1 + loop { break 1 } == 1` (2 vs 1)",
252
+ );
253
+
254
+ #[rustfmt::skip]
255
+ let test = || Ok(ensure!(1 + 'a: loop { break 'a 1 } == 1));
256
+ assert_err(
257
+ test,
258
+ "Condition failed: `1 + 'a: loop { break 'a 1 } == 1` (2 vs 1)",
259
+ );
260
+
261
+ #[rustfmt::skip]
262
+ let test = || Ok(ensure!(while false {}.t(1) == 2));
263
+ assert_err(
264
+ test,
265
+ "Condition failed: `while false {}.t(1) == 2` (1 vs 2)",
266
+ );
267
+
268
+ #[rustfmt::skip]
269
+ let test = || Ok(ensure!(while let None = Some(1) {}.t(1) == 2));
270
+ assert_err(
271
+ test,
272
+ "Condition failed: `while let None = Some(1) {}.t(1) == 2` (1 vs 2)",
273
+ );
274
+
275
+ #[rustfmt::skip]
276
+ let test = || Ok(ensure!(for _x in iter::once(0) {}.t(1) == 2));
277
+ assert_err(
278
+ test,
279
+ "Condition failed: `for _x in iter::once(0) {}.t(1) == 2` (1 vs 2)",
280
+ );
281
+
282
+ #[rustfmt::skip]
283
+ let test = || Ok(ensure!(for | _x in iter::once(0) {}.t(1) == 2));
284
+ assert_err(
285
+ test,
286
+ "Condition failed: `for | _x in iter::once(0) {}.t(1) == 2` (1 vs 2)",
287
+ );
288
+
289
+ #[rustfmt::skip]
290
+ let test = || Ok(ensure!(for true | false in iter::empty() {}.t(1) == 2));
291
+ assert_err(
292
+ test,
293
+ "Condition failed: `for true | false in iter::empty() {}.t(1) == 2` (1 vs 2)",
294
+ );
295
+ }
296
+
297
+ #[test]
298
+ fn test_match() {
299
+ #[rustfmt::skip]
300
+ let test = || Ok(ensure!(match 1 == 1 { true => 1, false => 0 } == 2));
301
+ assert_err(
302
+ test,
303
+ "Condition failed: `match 1 == 1 { true => 1, false => 0 } == 2` (1 vs 2)",
304
+ );
305
+ }
306
+
307
+ #[test]
308
+ fn test_atom() {
309
+ let test = || Ok(ensure!([false, false].len() > 3));
310
+ assert_err(
311
+ test,
312
+ "Condition failed: `[false, false].len() > 3` (2 vs 3)",
313
+ );
314
+
315
+ #[rustfmt::skip]
316
+ let test = || Ok(ensure!({ let x = 1; x } >= 3));
317
+ assert_err(test, "Condition failed: `{ let x = 1; x } >= 3` (1 vs 3)");
318
+
319
+ let test = || Ok(ensure!(S + async { 1 } == true));
320
+ assert_err(
321
+ test,
322
+ "Condition failed: `S + async { 1 } == true` (false vs true)",
323
+ );
324
+
325
+ let test = || Ok(ensure!(S + async move { 1 } == true));
326
+ assert_err(
327
+ test,
328
+ "Condition failed: `S + async move { 1 } == true` (false vs true)",
329
+ );
330
+
331
+ let x = &1;
332
+ let test = || Ok(ensure!(S + unsafe { ptr::read(x) } == true));
333
+ assert_err(
334
+ test,
335
+ "Condition failed: `S + unsafe { ptr::read(x) } == true` (false vs true)",
336
+ );
337
+ }
338
+
339
+ #[test]
340
+ fn test_path() {
341
+ let test = || Ok(ensure!(crate::S.t(1) == 2));
342
+ assert_err(test, "Condition failed: `crate::S.t(1) == 2` (1 vs 2)");
343
+
344
+ let test = || Ok(ensure!(::anyhow::Error::root_cause.t(1) == 2));
345
+ assert_err(
346
+ test,
347
+ "Condition failed: `::anyhow::Error::root_cause.t(1) == 2` (1 vs 2)",
348
+ );
349
+
350
+ let test = || Ok(ensure!(Error::msg::<&str>.t(1) == 2));
351
+ assert_err(
352
+ test,
353
+ "Condition failed: `Error::msg::<&str>.t(1) == 2` (1 vs 2)",
354
+ );
355
+
356
+ #[rustfmt::skip]
357
+ let test = || Ok(ensure!(Error::msg::<&str,>.t(1) == 2));
358
+ assert_err(
359
+ test,
360
+ "Condition failed: `Error::msg::<&str,>.t(1) == 2` (1 vs 2)",
361
+ );
362
+
363
+ let test = || Ok(ensure!(Error::msg::<<str as ToOwned>::Owned>.t(1) == 2));
364
+ assert_err(
365
+ test,
366
+ "Condition failed: `Error::msg::<<str as ToOwned>::Owned>.t(1) == 2` (1 vs 2)",
367
+ );
368
+
369
+ let test = || Ok(ensure!(Chain::<'static>::new.t(1) == 2));
370
+ assert_err(
371
+ test,
372
+ "Condition failed: `Chain::<'static>::new.t(1) == 2` (1 vs 2)",
373
+ );
374
+
375
+ #[rustfmt::skip]
376
+ let test = || Ok(ensure!(Chain::<'static,>::new.t(1) == 2));
377
+ assert_err(
378
+ test,
379
+ "Condition failed: `Chain::<'static,>::new.t(1) == 2` (1 vs 2)",
380
+ );
381
+
382
+ fn f<const I: isize>() {}
383
+ let test = || Ok(ensure!(f::<1>() != ()));
384
+ assert_err(test, "Condition failed: `f::<1>() != ()` (() vs ())");
385
+ let test = || Ok(ensure!(f::<-1>() != ()));
386
+ assert_err(test, "Condition failed: `f::<-1>() != ()` (() vs ())");
387
+
388
+ fn g<T, const I: isize>() {}
389
+ let test = || Ok(ensure!(g::<u8, 1>() != ()));
390
+ assert_err(test, "Condition failed: `g::<u8, 1>() != ()` (() vs ())");
391
+ let test = || Ok(ensure!(g::<u8, -1>() != ()));
392
+ assert_err(test, "Condition failed: `g::<u8, -1>() != ()` (() vs ())");
393
+
394
+ #[derive(PartialOrd, PartialEq, Debug)]
395
+ enum E<'a, T> {
396
+ #[allow(dead_code)]
397
+ T(&'a T),
398
+ U,
399
+ }
400
+
401
+ #[rustfmt::skip]
402
+ let test = || Ok(ensure!(E::U::<>>E::U::<u8>));
403
+ assert_err(test, "Condition failed: `E::U::<> > E::U::<u8>` (U vs U)");
404
+
405
+ #[rustfmt::skip]
406
+ let test = || Ok(ensure!(E::U::<u8>>E::U));
407
+ assert_err(test, "Condition failed: `E::U::<u8> > E::U` (U vs U)");
408
+
409
+ #[rustfmt::skip]
410
+ let test = || Ok(ensure!(E::U::<u8,>>E::U));
411
+ assert_err(test, "Condition failed: `E::U::<u8,> > E::U` (U vs U)");
412
+
413
+ let test = || Ok(ensure!(Generic::<dyn Debug + Sync> != Generic));
414
+ assert_err(
415
+ test,
416
+ "Condition failed: `Generic::<dyn Debug + Sync> != Generic` (Generic vs Generic)",
417
+ );
418
+
419
+ let test = || Ok(ensure!(Generic::<dyn Fn() + Sync> != Generic));
420
+ assert_err(
421
+ test,
422
+ "Condition failed: `Generic::<dyn Fn() + Sync> != Generic` (Generic vs Generic)",
423
+ );
424
+
425
+ #[rustfmt::skip]
426
+ let test = || {
427
+ Ok(ensure!(
428
+ Generic::<dyn Fn::() + ::std::marker::Sync> != Generic
429
+ ))
430
+ };
431
+ assert_err(
432
+ test,
433
+ "Condition failed: `Generic::<dyn Fn::() + ::std::marker::Sync> != Generic` (Generic vs Generic)",
434
+ );
435
+ }
436
+
437
+ #[test]
438
+ fn test_macro() {
439
+ let test = || Ok(ensure!(anyhow!("...").to_string().len() <= 1));
440
+ assert_err(
441
+ test,
442
+ "Condition failed: `anyhow!(\"...\").to_string().len() <= 1` (3 vs 1)",
443
+ );
444
+
445
+ let test = || Ok(ensure!(vec![1].len() < 1));
446
+ assert_err(test, "Condition failed: `vec![1].len() < 1` (1 vs 1)");
447
+
448
+ let test = || Ok(ensure!(stringify! {} != ""));
449
+ assert_err(
450
+ test,
451
+ "Condition failed: `stringify! {} != \"\"` (\"\" vs \"\")",
452
+ );
453
+ }
454
+
455
+ #[test]
456
+ fn test_trailer() {
457
+ let test = || Ok(ensure!((|| 1)() == 2));
458
+ assert_err(test, "Condition failed: `(|| 1)() == 2` (1 vs 2)");
459
+
460
+ let test = || Ok(ensure!(b"hmm"[1] == b'c'));
461
+ assert_err(test, "Condition failed: `b\"hmm\"[1] == b'c'` (109 vs 99)");
462
+
463
+ let test = || Ok(ensure!(PhantomData::<u8> {} != PhantomData));
464
+ assert_err(
465
+ test,
466
+ "Condition failed: `PhantomData::<u8> {} != PhantomData` (PhantomData<u8> vs PhantomData<u8>)",
467
+ );
468
+
469
+ let result = Ok::<_, Error>(1);
470
+ let test = || Ok(ensure!(result? == 2));
471
+ assert_err(test, "Condition failed: `result? == 2` (1 vs 2)");
472
+
473
+ let test = || Ok(ensure!((2, 3).1 == 2));
474
+ assert_err(test, "Condition failed: `(2, 3).1 == 2` (3 vs 2)");
475
+
476
+ #[rustfmt::skip]
477
+ let test = || Ok(ensure!((2, (3, 4)). 1.1 == 2));
478
+ assert_err(test, "Condition failed: `(2, (3, 4)).1.1 == 2` (4 vs 2)");
479
+
480
+ let err = anyhow!("");
481
+ let test = || Ok(ensure!(err.is::<&str>() == false));
482
+ assert_err(
483
+ test,
484
+ "Condition failed: `err.is::<&str>() == false` (true vs false)",
485
+ );
486
+
487
+ let test = || Ok(ensure!(err.is::<<str as ToOwned>::Owned>() == true));
488
+ assert_err(
489
+ test,
490
+ "Condition failed: `err.is::<<str as ToOwned>::Owned>() == true` (false vs true)",
491
+ );
492
+ }
493
+
494
+ #[test]
495
+ fn test_whitespace() {
496
+ #[derive(Debug)]
497
+ pub struct Point {
498
+ #[allow(dead_code)]
499
+ pub x: i32,
500
+ #[allow(dead_code)]
501
+ pub y: i32,
502
+ }
503
+
504
+ let point = Point { x: 0, y: 0 };
505
+ let test = || Ok(ensure!("" == format!("{:#?}", point)));
506
+ assert_err(
507
+ test,
508
+ "Condition failed: `\"\" == format!(\"{:#?}\", point)`",
509
+ );
510
+ }
511
+
512
+ #[test]
513
+ fn test_too_long() {
514
+ let test = || Ok(ensure!("" == "x".repeat(10)));
515
+ assert_err(
516
+ test,
517
+ "Condition failed: `\"\" == \"x\".repeat(10)` (\"\" vs \"xxxxxxxxxx\")",
518
+ );
519
+
520
+ let test = || Ok(ensure!("" == "x".repeat(80)));
521
+ assert_err(test, "Condition failed: `\"\" == \"x\".repeat(80)`");
522
+ }
523
+
524
+ #[test]
525
+ fn test_as() {
526
+ let test = || Ok(ensure!('\0' as u8 > 1));
527
+ assert_err(test, "Condition failed: `'\\0' as u8 > 1` (0 vs 1)");
528
+
529
+ let test = || Ok(ensure!('\0' as ::std::primitive::u8 > 1));
530
+ assert_err(
531
+ test,
532
+ "Condition failed: `'\\0' as ::std::primitive::u8 > 1` (0 vs 1)",
533
+ );
534
+
535
+ let test = || Ok(ensure!(&[0] as &[i32] == [1]));
536
+ assert_err(
537
+ test,
538
+ "Condition failed: `&[0] as &[i32] == [1]` ([0] vs [1])",
539
+ );
540
+
541
+ let test = || Ok(ensure!(0 as *const () as *mut _ == 1 as *mut ()));
542
+ assert_err(
543
+ test,
544
+ "Condition failed: `0 as *const () as *mut _ == 1 as *mut ()` (0x0 vs 0x1)",
545
+ );
546
+
547
+ let s = "";
548
+ let test = || Ok(ensure!(s as &str != s));
549
+ assert_err(test, "Condition failed: `s as &str != s` (\"\" vs \"\")");
550
+
551
+ let test = || Ok(ensure!(&s as &&str != &s));
552
+ assert_err(test, "Condition failed: `&s as &&str != &s` (\"\" vs \"\")");
553
+
554
+ let test = || Ok(ensure!(s as &'static str != s));
555
+ assert_err(
556
+ test,
557
+ "Condition failed: `s as &'static str != s` (\"\" vs \"\")",
558
+ );
559
+
560
+ let test = || Ok(ensure!(&s as &&'static str != &s));
561
+ assert_err(
562
+ test,
563
+ "Condition failed: `&s as &&'static str != &s` (\"\" vs \"\")",
564
+ );
565
+
566
+ let m: &mut str = Default::default();
567
+ let test = || Ok(ensure!(m as &mut str != s));
568
+ assert_err(
569
+ test,
570
+ "Condition failed: `m as &mut str != s` (\"\" vs \"\")",
571
+ );
572
+
573
+ let test = || Ok(ensure!(&m as &&mut str != &s));
574
+ assert_err(
575
+ test,
576
+ "Condition failed: `&m as &&mut str != &s` (\"\" vs \"\")",
577
+ );
578
+
579
+ let test = || Ok(ensure!(&m as &&'static mut str != &s));
580
+ assert_err(
581
+ test,
582
+ "Condition failed: `&m as &&'static mut str != &s` (\"\" vs \"\")",
583
+ );
584
+
585
+ let f = || {};
586
+ let test = || Ok(ensure!(f as fn() as usize * 0 != 0));
587
+ assert_err(
588
+ test,
589
+ "Condition failed: `f as fn() as usize * 0 != 0` (0 vs 0)",
590
+ );
591
+
592
+ let test = || Ok(ensure!(f as fn() -> () as usize * 0 != 0));
593
+ assert_err(
594
+ test,
595
+ "Condition failed: `f as fn() -> () as usize * 0 != 0` (0 vs 0)",
596
+ );
597
+
598
+ let test = || Ok(ensure!(f as for<'a> fn() as usize * 0 != 0));
599
+ assert_err(
600
+ test,
601
+ "Condition failed: `f as for<'a> fn() as usize * 0 != 0` (0 vs 0)",
602
+ );
603
+
604
+ let test = || Ok(ensure!(f as unsafe fn() as usize * 0 != 0));
605
+ assert_err(
606
+ test,
607
+ "Condition failed: `f as unsafe fn() as usize * 0 != 0` (0 vs 0)",
608
+ );
609
+
610
+ #[rustfmt::skip]
611
+ let test = || Ok(ensure!(f as extern "Rust" fn() as usize * 0 != 0));
612
+ assert_err(
613
+ test,
614
+ "Condition failed: `f as extern \"Rust\" fn() as usize * 0 != 0` (0 vs 0)",
615
+ );
616
+
617
+ extern "C" fn extern_fn() {}
618
+ #[rustfmt::skip]
619
+ #[allow(missing_abi)]
620
+ let test = || Ok(ensure!(extern_fn as extern fn() as usize * 0 != 0));
621
+ assert_err(
622
+ test,
623
+ "Condition failed: `extern_fn as extern fn() as usize * 0 != 0` (0 vs 0)",
624
+ );
625
+
626
+ let f = || -> ! { panic!() };
627
+ let test = || Ok(ensure!(f as fn() -> ! as usize * 0 != 0));
628
+ assert_err(
629
+ test,
630
+ "Condition failed: `f as fn() -> ! as usize * 0 != 0` (0 vs 0)",
631
+ );
632
+
633
+ trait EqDebug<T>: PartialEq<T> + Debug {
634
+ type Assoc;
635
+ }
636
+
637
+ impl<S, T> EqDebug<T> for S
638
+ where
639
+ S: PartialEq<T> + Debug,
640
+ {
641
+ type Assoc = bool;
642
+ }
643
+
644
+ let test = || Ok(ensure!(&0 as &dyn EqDebug<i32, Assoc = bool> != &0));
645
+ assert_err(
646
+ test,
647
+ "Condition failed: `&0 as &dyn EqDebug<i32, Assoc = bool> != &0` (0 vs 0)",
648
+ );
649
+
650
+ let test = || {
651
+ Ok(ensure!(
652
+ PhantomData as PhantomData<<i32 as ToOwned>::Owned> != PhantomData
653
+ ))
654
+ };
655
+ assert_err(
656
+ test,
657
+ "Condition failed: `PhantomData as PhantomData<<i32 as ToOwned>::Owned> != PhantomData` (PhantomData<i32> vs PhantomData<i32>)",
658
+ );
659
+
660
+ macro_rules! int {
661
+ (...) => {
662
+ u8
663
+ };
664
+ }
665
+
666
+ let test = || Ok(ensure!(0 as int!(...) != 0));
667
+ assert_err(test, "Condition failed: `0 as int!(...) != 0` (0 vs 0)");
668
+
669
+ let test = || Ok(ensure!(0 as int![...] != 0));
670
+ assert_err(test, "Condition failed: `0 as int![...] != 0` (0 vs 0)");
671
+
672
+ let test = || Ok(ensure!(0 as int! {...} != 0));
673
+ assert_err(test, "Condition failed: `0 as int! {...} != 0` (0 vs 0)");
674
+ }
675
+
676
+ #[test]
677
+ fn test_pat() {
678
+ let test = || Ok(ensure!(if let ref mut _x @ 0 = 0 { 0 } else { 1 } == 1));
679
+ assert_err(
680
+ test,
681
+ "Condition failed: `if let ref mut _x @ 0 = 0 { 0 } else { 1 } == 1` (0 vs 1)",
682
+ );
683
+
684
+ let test = || Ok(ensure!(if let -1..=1 = 0 { 0 } else { 1 } == 1));
685
+ assert_err(
686
+ test,
687
+ "Condition failed: `if let -1..=1 = 0 { 0 } else { 1 } == 1` (0 vs 1)",
688
+ );
689
+
690
+ let test = || Ok(ensure!(if let &0 = &0 { 0 } else { 1 } == 1));
691
+ assert_err(
692
+ test,
693
+ "Condition failed: `if let &0 = &0 { 0 } else { 1 } == 1` (0 vs 1)",
694
+ );
695
+
696
+ let test = || Ok(ensure!(if let &&0 = &&0 { 0 } else { 1 } == 1));
697
+ assert_err(
698
+ test,
699
+ "Condition failed: `if let &&0 = &&0 { 0 } else { 1 } == 1` (0 vs 1)",
700
+ );
701
+
702
+ let test = || Ok(ensure!(if let &mut 0 = &mut 0 { 0 } else { 1 } == 1));
703
+ assert_err(
704
+ test,
705
+ "Condition failed: `if let &mut 0 = &mut 0 { 0 } else { 1 } == 1` (0 vs 1)",
706
+ );
707
+
708
+ let test = || Ok(ensure!(if let &&mut 0 = &&mut 0 { 0 } else { 1 } == 1));
709
+ assert_err(
710
+ test,
711
+ "Condition failed: `if let &&mut 0 = &&mut 0 { 0 } else { 1 } == 1` (0 vs 1)",
712
+ );
713
+
714
+ let test = || Ok(ensure!(if let (0, 1) = (0, 1) { 0 } else { 1 } == 1));
715
+ assert_err(
716
+ test,
717
+ "Condition failed: `if let (0, 1) = (0, 1) { 0 } else { 1 } == 1` (0 vs 1)",
718
+ );
719
+
720
+ let test = || Ok(ensure!(if let [0] = b"\0" { 0 } else { 1 } == 1));
721
+ assert_err(
722
+ test,
723
+ "Condition failed: `if let [0] = b\"\\0\" { 0 } else { 1 } == 1` (0 vs 1)",
724
+ );
725
+
726
+ let p = PhantomData::<u8>;
727
+ let test = || Ok(ensure!(if let P::<u8> {} = p { 0 } else { 1 } == 1));
728
+ assert_err(
729
+ test,
730
+ "Condition failed: `if let P::<u8> {} = p { 0 } else { 1 } == 1` (0 vs 1)",
731
+ );
732
+
733
+ let test = || Ok(ensure!(if let ::std::marker::PhantomData = p {} != ()));
734
+ assert_err(
735
+ test,
736
+ "Condition failed: `if let ::std::marker::PhantomData = p {} != ()` (() vs ())",
737
+ );
738
+
739
+ let test = || Ok(ensure!(if let <S as Trait>::V = 0 { 0 } else { 1 } == 1));
740
+ assert_err(
741
+ test,
742
+ "Condition failed: `if let <S as Trait>::V = 0 { 0 } else { 1 } == 1` (0 vs 1)",
743
+ );
744
+
745
+ let test = || Ok(ensure!(for _ in iter::once(()) {} != ()));
746
+ assert_err(
747
+ test,
748
+ "Condition failed: `for _ in iter::once(()) {} != ()` (() vs ())",
749
+ );
750
+
751
+ let test = || Ok(ensure!(if let stringify!(x) = "x" { 0 } else { 1 } == 1));
752
+ assert_err(
753
+ test,
754
+ "Condition failed: `if let stringify!(x) = \"x\" { 0 } else { 1 } == 1` (0 vs 1)",
755
+ );
756
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_ffi.rs ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![deny(improper_ctypes, improper_ctypes_definitions)]
2
+ #![allow(clippy::uninlined_format_args)]
3
+
4
+ use anyhow::anyhow;
5
+
6
+ #[no_mangle]
7
+ pub extern "C" fn anyhow1(err: anyhow::Error) {
8
+ println!("{:?}", err);
9
+ }
10
+
11
+ #[no_mangle]
12
+ pub extern "C" fn anyhow2(err: &mut Option<anyhow::Error>) {
13
+ *err = Some(anyhow!("ffi error"));
14
+ }
15
+
16
+ #[no_mangle]
17
+ pub extern "C" fn anyhow3() -> Option<anyhow::Error> {
18
+ Some(anyhow!("ffi error"))
19
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_fmt.rs ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use anyhow::{bail, Context, Result};
2
+ use std::io;
3
+
4
+ fn f() -> Result<()> {
5
+ bail!(io::Error::new(io::ErrorKind::PermissionDenied, "oh no!"));
6
+ }
7
+
8
+ fn g() -> Result<()> {
9
+ f().context("f failed")
10
+ }
11
+
12
+ fn h() -> Result<()> {
13
+ g().context("g failed")
14
+ }
15
+
16
+ const EXPECTED_ALTDISPLAY_F: &str = "oh no!";
17
+
18
+ const EXPECTED_ALTDISPLAY_G: &str = "f failed: oh no!";
19
+
20
+ const EXPECTED_ALTDISPLAY_H: &str = "g failed: f failed: oh no!";
21
+
22
+ const EXPECTED_DEBUG_F: &str = "oh no!";
23
+
24
+ const EXPECTED_DEBUG_G: &str = "\
25
+ f failed
26
+
27
+ Caused by:
28
+ oh no!\
29
+ ";
30
+
31
+ const EXPECTED_DEBUG_H: &str = "\
32
+ g failed
33
+
34
+ Caused by:
35
+ 0: f failed
36
+ 1: oh no!\
37
+ ";
38
+
39
+ const EXPECTED_ALTDEBUG_F: &str = "\
40
+ Custom {
41
+ kind: PermissionDenied,
42
+ error: \"oh no!\",
43
+ }\
44
+ ";
45
+
46
+ const EXPECTED_ALTDEBUG_G: &str = "\
47
+ Error {
48
+ context: \"f failed\",
49
+ source: Custom {
50
+ kind: PermissionDenied,
51
+ error: \"oh no!\",
52
+ },
53
+ }\
54
+ ";
55
+
56
+ const EXPECTED_ALTDEBUG_H: &str = "\
57
+ Error {
58
+ context: \"g failed\",
59
+ source: Error {
60
+ context: \"f failed\",
61
+ source: Custom {
62
+ kind: PermissionDenied,
63
+ error: \"oh no!\",
64
+ },
65
+ },
66
+ }\
67
+ ";
68
+
69
+ #[test]
70
+ fn test_display() {
71
+ assert_eq!("g failed", h().unwrap_err().to_string());
72
+ }
73
+
74
+ #[test]
75
+ fn test_altdisplay() {
76
+ assert_eq!(EXPECTED_ALTDISPLAY_F, format!("{:#}", f().unwrap_err()));
77
+ assert_eq!(EXPECTED_ALTDISPLAY_G, format!("{:#}", g().unwrap_err()));
78
+ assert_eq!(EXPECTED_ALTDISPLAY_H, format!("{:#}", h().unwrap_err()));
79
+ }
80
+
81
+ #[test]
82
+ fn test_debug() {
83
+ assert_eq!(EXPECTED_DEBUG_F, format!("{:?}", f().unwrap_err()));
84
+ assert_eq!(EXPECTED_DEBUG_G, format!("{:?}", g().unwrap_err()));
85
+ assert_eq!(EXPECTED_DEBUG_H, format!("{:?}", h().unwrap_err()));
86
+ }
87
+
88
+ #[test]
89
+ fn test_altdebug() {
90
+ assert_eq!(EXPECTED_ALTDEBUG_F, format!("{:#?}", f().unwrap_err()));
91
+ assert_eq!(EXPECTED_ALTDEBUG_G, format!("{:#?}", g().unwrap_err()));
92
+ assert_eq!(EXPECTED_ALTDEBUG_H, format!("{:#?}", h().unwrap_err()));
93
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_macros.rs ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(
2
+ clippy::assertions_on_result_states,
3
+ clippy::eq_op,
4
+ clippy::incompatible_msrv, // https://github.com/rust-lang/rust-clippy/issues/12257
5
+ clippy::items_after_statements,
6
+ clippy::match_single_binding,
7
+ clippy::needless_pass_by_value,
8
+ clippy::shadow_unrelated,
9
+ clippy::uninlined_format_args,
10
+ clippy::wildcard_imports
11
+ )]
12
+
13
+ mod common;
14
+
15
+ use self::common::*;
16
+ use anyhow::{anyhow, ensure, Result};
17
+ use std::cell::Cell;
18
+ use std::future;
19
+
20
+ #[test]
21
+ fn test_messages() {
22
+ assert_eq!("oh no!", bail_literal().unwrap_err().to_string());
23
+ assert_eq!("oh no!", bail_fmt().unwrap_err().to_string());
24
+ assert_eq!("oh no!", bail_error().unwrap_err().to_string());
25
+ }
26
+
27
+ #[test]
28
+ fn test_ensure() {
29
+ let f = || {
30
+ ensure!(1 + 1 == 2, "This is correct");
31
+ Ok(())
32
+ };
33
+ assert!(f().is_ok());
34
+
35
+ let v = 1;
36
+ let f = || {
37
+ ensure!(v + v == 2, "This is correct, v: {}", v);
38
+ Ok(())
39
+ };
40
+ assert!(f().is_ok());
41
+
42
+ let f = || {
43
+ ensure!(v + v == 1, "This is not correct, v: {}", v);
44
+ Ok(())
45
+ };
46
+ assert!(f().is_err());
47
+
48
+ let f = || {
49
+ ensure!(v + v == 1);
50
+ Ok(())
51
+ };
52
+ assert_eq!(
53
+ f().unwrap_err().to_string(),
54
+ "Condition failed: `v + v == 1` (2 vs 1)",
55
+ );
56
+ }
57
+
58
+ #[test]
59
+ fn test_ensure_nonbool() -> Result<()> {
60
+ struct Struct {
61
+ condition: bool,
62
+ }
63
+
64
+ let s = Struct { condition: true };
65
+ match &s {
66
+ Struct { condition } => ensure!(condition), // &bool
67
+ }
68
+
69
+ Ok(())
70
+ }
71
+
72
+ #[test]
73
+ fn test_temporaries() {
74
+ fn require_send_sync(_: impl Send + Sync) {}
75
+
76
+ require_send_sync(async {
77
+ // If anyhow hasn't dropped any temporary format_args it creates by the
78
+ // time it's done evaluating, those will stick around until the
79
+ // semicolon, which is on the other side of the await point, making the
80
+ // enclosing future non-Send.
81
+ future::ready(anyhow!("...")).await;
82
+ });
83
+
84
+ fn message(cell: Cell<&str>) -> &str {
85
+ cell.get()
86
+ }
87
+
88
+ require_send_sync(async {
89
+ future::ready(anyhow!(message(Cell::new("...")))).await;
90
+ });
91
+ }
92
+
93
+ #[test]
94
+ fn test_brace_escape() {
95
+ let err = anyhow!("unterminated ${{..}} expression");
96
+ assert_eq!("unterminated ${..} expression", err.to_string());
97
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_repr.rs ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(clippy::extra_unused_type_parameters)]
2
+
3
+ mod drop;
4
+
5
+ use self::drop::{DetectDrop, Flag};
6
+ use anyhow::Error;
7
+ use std::mem;
8
+
9
+ #[test]
10
+ fn test_error_size() {
11
+ assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());
12
+ }
13
+
14
+ #[test]
15
+ fn test_null_pointer_optimization() {
16
+ assert_eq!(mem::size_of::<Result<(), Error>>(), mem::size_of::<usize>());
17
+ }
18
+
19
+ #[test]
20
+ fn test_autotraits() {
21
+ fn assert<E: Unpin + Send + Sync + 'static>() {}
22
+ assert::<Error>();
23
+ }
24
+
25
+ #[test]
26
+ fn test_drop() {
27
+ let has_dropped = Flag::new();
28
+ drop(Error::new(DetectDrop::new(&has_dropped)));
29
+ assert!(has_dropped.get());
30
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/test_source.rs ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use anyhow::anyhow;
2
+ use std::error::Error as StdError;
3
+ use std::fmt::{self, Display};
4
+ use std::io;
5
+
6
+ #[derive(Debug)]
7
+ enum TestError {
8
+ Io(io::Error),
9
+ }
10
+
11
+ impl Display for TestError {
12
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
13
+ match self {
14
+ TestError::Io(e) => Display::fmt(e, formatter),
15
+ }
16
+ }
17
+ }
18
+
19
+ impl StdError for TestError {
20
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
21
+ match self {
22
+ TestError::Io(io) => Some(io),
23
+ }
24
+ }
25
+ }
26
+
27
+ #[test]
28
+ fn test_literal_source() {
29
+ let error = anyhow!("oh no!");
30
+ assert!(error.source().is_none());
31
+ }
32
+
33
+ #[test]
34
+ fn test_variable_source() {
35
+ let msg = "oh no!";
36
+ let error = anyhow!(msg);
37
+ assert!(error.source().is_none());
38
+
39
+ let msg = msg.to_owned();
40
+ let error = anyhow!(msg);
41
+ assert!(error.source().is_none());
42
+ }
43
+
44
+ #[test]
45
+ fn test_fmt_source() {
46
+ let error = anyhow!("{} {}!", "oh", "no");
47
+ assert!(error.source().is_none());
48
+ }
49
+
50
+ #[test]
51
+ fn test_io_source() {
52
+ let io = io::Error::new(io::ErrorKind::Other, "oh no!");
53
+ let error = anyhow!(TestError::Io(io));
54
+ assert_eq!("oh no!", error.source().unwrap().to_string());
55
+ }
56
+
57
+ #[test]
58
+ fn test_anyhow_from_anyhow() {
59
+ let error = anyhow!("oh no!").context("context");
60
+ let error = anyhow!(error);
61
+ assert_eq!("oh no!", error.source().unwrap().to_string());
62
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/chained-comparison.rs ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ use anyhow::{ensure, Result};
2
+
3
+ fn main() -> Result<()> {
4
+ // `ensure!` must not partition this into `(false) == (false == true)`
5
+ // because Rust doesn't ordinarily allow this form of expression.
6
+ ensure!(false == false == true);
7
+ Ok(())
8
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/chained-comparison.stderr ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ error: comparison operators cannot be chained
2
+ --> tests/ui/chained-comparison.rs:6:19
3
+ |
4
+ 6 | ensure!(false == false == true);
5
+ | ^^ ^^
6
+ |
7
+ help: split the comparison into two
8
+ |
9
+ 6 | ensure!(false == false && false == true);
10
+ | ++++++++
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/empty-ensure.rs ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ use anyhow::{ensure, Result};
2
+
3
+ fn main() -> Result<()> {
4
+ ensure!();
5
+ Ok(())
6
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/empty-ensure.stderr ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ error: unexpected end of macro invocation
2
+ --> tests/ui/empty-ensure.rs:4:5
3
+ |
4
+ 4 | ensure!();
5
+ | ^^^^^^^^^ missing tokens in macro arguments
6
+ |
7
+ note: while trying to match meta-variable `$cond:expr`
8
+ --> src/ensure.rs
9
+ |
10
+ | ($cond:expr $(,)?) => {
11
+ | ^^^^^^^^^^
12
+ = note: this error originates in the macro `$crate::__parse_ensure` which comes from the expansion of the macro `ensure` (in Nightly builds, run with -Z macro-backtrace for more info)
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/ensure-nonbool.rs ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use anyhow::{ensure, Result};
2
+ use std::ops::{Deref, Not};
3
+
4
+ struct Bool(bool);
5
+
6
+ struct DerefBool(bool);
7
+
8
+ struct NotBool(bool);
9
+
10
+ impl Deref for DerefBool {
11
+ type Target = bool;
12
+ fn deref(&self) -> &Self::Target {
13
+ &self.0
14
+ }
15
+ }
16
+
17
+ impl Not for NotBool {
18
+ type Output = bool;
19
+ fn not(self) -> Self::Output {
20
+ !self.0
21
+ }
22
+ }
23
+
24
+ fn main() -> Result<()> {
25
+ ensure!("...");
26
+
27
+ let mut s = Bool(true);
28
+ match &mut s {
29
+ Bool(cond) => ensure!(cond),
30
+ }
31
+
32
+ let db = DerefBool(true);
33
+ ensure!(db);
34
+ ensure!(&db);
35
+
36
+ let nb = NotBool(true);
37
+ ensure!(nb);
38
+
39
+ Ok(())
40
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/ensure-nonbool.stderr ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ error[E0277]: the trait bound `&str: anyhow::__private::not::Bool` is not satisfied
2
+ --> tests/ui/ensure-nonbool.rs:25:13
3
+ |
4
+ 25 | ensure!("...");
5
+ | --------^^^^^-
6
+ | | |
7
+ | | the trait `anyhow::__private::not::Bool` is not implemented for `&str`
8
+ | required by a bound introduced by this call
9
+ |
10
+ help: the following other types implement trait `anyhow::__private::not::Bool`
11
+ --> src/lib.rs
12
+ |
13
+ | impl Bool for bool {
14
+ | ^^^^^^^^^^^^^^^^^^ `bool`
15
+ ...
16
+ | impl Bool for &bool {
17
+ | ^^^^^^^^^^^^^^^^^^^ `&bool`
18
+ note: required by a bound in `anyhow::__private::not`
19
+ --> src/lib.rs
20
+ |
21
+ | pub fn not(cond: impl Bool) -> bool {
22
+ | ^^^^ required by this bound in `not`
23
+
24
+ error[E0277]: the trait bound `&mut bool: anyhow::__private::not::Bool` is not satisfied
25
+ --> tests/ui/ensure-nonbool.rs:29:31
26
+ |
27
+ 29 | Bool(cond) => ensure!(cond),
28
+ | --------^^^^-
29
+ | | |
30
+ | | the trait `anyhow::__private::not::Bool` is not implemented for `&mut bool`
31
+ | required by a bound introduced by this call
32
+ |
33
+ = note: `anyhow::__private::not::Bool` is implemented for `&bool`, but not for `&mut bool`
34
+ note: required by a bound in `anyhow::__private::not`
35
+ --> src/lib.rs
36
+ |
37
+ | pub fn not(cond: impl Bool) -> bool {
38
+ | ^^^^ required by this bound in `not`
39
+ help: consider dereferencing here
40
+ |
41
+ 29 | Bool(cond) => ensure!(*cond),
42
+ | +
43
+
44
+ error[E0277]: the trait bound `DerefBool: anyhow::__private::not::Bool` is not satisfied
45
+ --> tests/ui/ensure-nonbool.rs:33:13
46
+ |
47
+ 33 | ensure!(db);
48
+ | --------^^-
49
+ | | |
50
+ | | unsatisfied trait bound
51
+ | required by a bound introduced by this call
52
+ |
53
+ help: the trait `anyhow::__private::not::Bool` is not implemented for `DerefBool`
54
+ --> tests/ui/ensure-nonbool.rs:6:1
55
+ |
56
+ 6 | struct DerefBool(bool);
57
+ | ^^^^^^^^^^^^^^^^
58
+ note: required by a bound in `anyhow::__private::not`
59
+ --> src/lib.rs
60
+ |
61
+ | pub fn not(cond: impl Bool) -> bool {
62
+ | ^^^^ required by this bound in `not`
63
+ help: consider dereferencing here
64
+ |
65
+ 33 | ensure!(*db);
66
+ | +
67
+
68
+ error[E0277]: the trait bound `&DerefBool: anyhow::__private::not::Bool` is not satisfied
69
+ --> tests/ui/ensure-nonbool.rs:34:13
70
+ |
71
+ 34 | ensure!(&db);
72
+ | --------^^^-
73
+ | | |
74
+ | | the trait `anyhow::__private::not::Bool` is not implemented for `&DerefBool`
75
+ | required by a bound introduced by this call
76
+ |
77
+ note: required by a bound in `anyhow::__private::not`
78
+ --> src/lib.rs
79
+ |
80
+ | pub fn not(cond: impl Bool) -> bool {
81
+ | ^^^^ required by this bound in `not`
82
+ help: consider dereferencing here
83
+ |
84
+ 34 | ensure!(&*db);
85
+ | +
86
+
87
+ error[E0277]: the trait bound `NotBool: anyhow::__private::not::Bool` is not satisfied
88
+ --> tests/ui/ensure-nonbool.rs:37:13
89
+ |
90
+ 37 | ensure!(nb);
91
+ | --------^^-
92
+ | | |
93
+ | | unsatisfied trait bound
94
+ | required by a bound introduced by this call
95
+ |
96
+ help: the trait `anyhow::__private::not::Bool` is not implemented for `NotBool`
97
+ --> tests/ui/ensure-nonbool.rs:8:1
98
+ |
99
+ 8 | struct NotBool(bool);
100
+ | ^^^^^^^^^^^^^^
101
+ help: the following other types implement trait `anyhow::__private::not::Bool`
102
+ --> src/lib.rs
103
+ |
104
+ | impl Bool for bool {
105
+ | ^^^^^^^^^^^^^^^^^^ `bool`
106
+ ...
107
+ | impl Bool for &bool {
108
+ | ^^^^^^^^^^^^^^^^^^^ `&bool`
109
+ note: required by a bound in `anyhow::__private::not`
110
+ --> src/lib.rs
111
+ |
112
+ | pub fn not(cond: impl Bool) -> bool {
113
+ | ^^^^ required by this bound in `not`
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/must-use.rs ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![deny(unused_must_use)]
2
+
3
+ use anyhow::anyhow;
4
+
5
+ fn main() -> anyhow::Result<()> {
6
+ if true {
7
+ // meant to write bail!
8
+ anyhow!("it failed");
9
+ }
10
+ Ok(())
11
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/must-use.stderr ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ error: unused return value of `anyhow::__private::must_use` that must be used
2
+ --> tests/ui/must-use.rs:8:9
3
+ |
4
+ 8 | anyhow!("it failed");
5
+ | ^^^^^^^^^^^^^^^^^^^^
6
+ |
7
+ note: the lint level is defined here
8
+ --> tests/ui/must-use.rs:1:9
9
+ |
10
+ 1 | #![deny(unused_must_use)]
11
+ | ^^^^^^^^^^^^^^^
12
+ help: use `let _ = ...` to ignore the resulting value
13
+ |
14
+ 8 | let _ = anyhow!("it failed");
15
+ | +++++++
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/no-impl.rs ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ use anyhow::anyhow;
2
+
3
+ #[derive(Debug)]
4
+ struct Error;
5
+
6
+ fn main() {
7
+ let _ = anyhow!(Error);
8
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/no-impl.stderr ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ error[E0599]: the method `anyhow_kind` exists for reference `&Error`, but its trait bounds were not satisfied
2
+ --> tests/ui/no-impl.rs:7:13
3
+ |
4
+ 4 | struct Error;
5
+ | ------------ doesn't satisfy `Error: Into<anyhow::Error>`, `Error: anyhow::kind::TraitKind` or `Error: std::fmt::Display`
6
+ ...
7
+ 7 | let _ = anyhow!(Error);
8
+ | ^^^^^^^^^^^^^^ method cannot be called on `&Error` due to unsatisfied trait bounds
9
+ |
10
+ = note: the following trait bounds were not satisfied:
11
+ `Error: Into<anyhow::Error>`
12
+ which is required by `Error: anyhow::kind::TraitKind`
13
+ `Error: std::fmt::Display`
14
+ which is required by `&Error: anyhow::kind::AdhocKind`
15
+ `&Error: Into<anyhow::Error>`
16
+ which is required by `&Error: anyhow::kind::TraitKind`
17
+ note: the traits `Into` and `std::fmt::Display` must be implemented
18
+ --> $RUST/core/src/fmt/mod.rs
19
+ |
20
+ | pub trait Display: PointeeSized {
21
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
22
+ |
23
+ ::: $RUST/core/src/convert/mod.rs
24
+ |
25
+ | pub const trait Into<T>: Sized {
26
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
27
+ = help: items from traits can only be used if the trait is implemented and in scope
28
+ = note: the following traits define an item `anyhow_kind`, perhaps you need to implement one of them:
29
+ candidate #1: `anyhow::kind::AdhocKind`
30
+ candidate #2: `anyhow::kind::BoxedKind`
31
+ candidate #3: `anyhow::kind::TraitKind`
32
+ = note: this error originates in the macro `anyhow` (in Nightly builds, run with -Z macro-backtrace for more info)
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/temporary-value.rs ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ use anyhow::anyhow;
2
+
3
+ fn main() {
4
+ let _ = anyhow!(&String::new());
5
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/temporary-value.stderr ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ error[E0716]: temporary value dropped while borrowed
2
+ --> tests/ui/temporary-value.rs:4:22
3
+ |
4
+ 4 | let _ = anyhow!(&String::new());
5
+ | ---------^^^^^^^^^^^^^-
6
+ | | |
7
+ | | creates a temporary value which is freed while still in use
8
+ | temporary value is freed at the end of this statement
9
+ | argument requires that borrow lasts for `'static`
10
+ |
11
+ note: requirement that the value outlives `'static` introduced here
12
+ --> src/kind.rs
13
+ |
14
+ | M: Display + Debug + Send + Sync + 'static,
15
+ | ^^^^^^^
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/wrong-interpolation.rs ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ use anyhow::{bail, Result};
2
+
3
+ fn main() -> Result<()> {
4
+ bail!("{} not found");
5
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/anyhow-1.0.101/tests/ui/wrong-interpolation.stderr ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ error: 1 positional argument in format string, but no arguments were given
2
+ --> tests/ui/wrong-interpolation.rs:4:12
3
+ |
4
+ 4 | bail!("{} not found");
5
+ | ^^
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_02_parse.rs ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use clap::{arg, command, value_parser};
2
+
3
+ fn main() {
4
+ let matches = command!() // requires `cargo` feature
5
+ .arg(
6
+ arg!(<PORT>)
7
+ .help("Network port to use")
8
+ .value_parser(value_parser!(u16).range(1..)),
9
+ )
10
+ .get_matches();
11
+
12
+ // Note, it's safe to call unwrap() because the arg is required
13
+ let port: u16 = *matches
14
+ .get_one::<u16>("PORT")
15
+ .expect("'PORT' is required and parsing will fail if its missing");
16
+ println!("PORT = {port}");
17
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_02_validate.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ```console
2
+ $ 04_02_validate --help
3
+ A simple to use, efficient, and full-featured Command Line Argument Parser
4
+
5
+ Usage: 04_02_validate[EXE] <PORT>
6
+
7
+ Arguments:
8
+ <PORT> Network port to use
9
+
10
+ Options:
11
+ -h, --help Print help
12
+ -V, --version Print version
13
+
14
+ $ 04_02_validate 22
15
+ PORT = 22
16
+
17
+ $ 04_02_validate foobar
18
+ ? failed
19
+ error: invalid value 'foobar' for '<PORT>': `foobar` isn't a port number
20
+
21
+ For more information, try '--help'.
22
+
23
+ $ 04_02_validate 0
24
+ ? failed
25
+ error: invalid value '0' for '<PORT>': port not in range 1-65535
26
+
27
+ For more information, try '--help'.
28
+
29
+ ```
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_02_validate.rs ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::ops::RangeInclusive;
2
+
3
+ use clap::{arg, command};
4
+
5
+ fn main() {
6
+ let matches = command!() // requires `cargo` feature
7
+ .arg(
8
+ arg!(<PORT>)
9
+ .help("Network port to use")
10
+ .value_parser(port_in_range),
11
+ )
12
+ .get_matches();
13
+
14
+ // Note, it's safe to call unwrap() because the arg is required
15
+ let port: u16 = *matches
16
+ .get_one::<u16>("PORT")
17
+ .expect("'PORT' is required and parsing will fail if its missing");
18
+ println!("PORT = {port}");
19
+ }
20
+
21
+ const PORT_RANGE: RangeInclusive<usize> = 1..=65535;
22
+
23
+ fn port_in_range(s: &str) -> Result<u16, String> {
24
+ let port: usize = s
25
+ .parse()
26
+ .map_err(|_| format!("`{s}` isn't a port number"))?;
27
+ if PORT_RANGE.contains(&port) {
28
+ Ok(port as u16)
29
+ } else {
30
+ Err(format!(
31
+ "port not in range {}-{}",
32
+ PORT_RANGE.start(),
33
+ PORT_RANGE.end()
34
+ ))
35
+ }
36
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_03_relations.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ```console
2
+ $ 04_03_relations --help
3
+ A simple to use, efficient, and full-featured Command Line Argument Parser
4
+
5
+ Usage: 04_03_relations[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
6
+
7
+ Arguments:
8
+ [INPUT_FILE] some regular input
9
+
10
+ Options:
11
+ --set-ver <VER> set version manually
12
+ --major auto inc major
13
+ --minor auto inc minor
14
+ --patch auto inc patch
15
+ --spec-in <SPEC_IN> some special input argument
16
+ -c <CONFIG>
17
+ -h, --help Print help
18
+ -V, --version Print version
19
+
20
+ $ 04_03_relations
21
+ ? failed
22
+ error: the following required arguments were not provided:
23
+ <--set-ver <VER>|--major|--minor|--patch>
24
+
25
+ Usage: 04_03_relations[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
26
+
27
+ For more information, try '--help'.
28
+
29
+ $ 04_03_relations --major
30
+ Version: 2.2.3
31
+
32
+ $ 04_03_relations --major --minor
33
+ ? failed
34
+ error: the argument '--major' cannot be used with '--minor'
35
+
36
+ Usage: 04_03_relations[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
37
+
38
+ For more information, try '--help'.
39
+
40
+ $ 04_03_relations --major -c config.toml
41
+ ? failed
42
+ error: the following required arguments were not provided:
43
+ <INPUT_FILE|--spec-in <SPEC_IN>>
44
+
45
+ Usage: 04_03_relations[EXE] -c <CONFIG> <--set-ver <VER>|--major|--minor|--patch> <INPUT_FILE|--spec-in <SPEC_IN>>
46
+
47
+ For more information, try '--help'.
48
+
49
+ $ 04_03_relations --major -c config.toml --spec-in input.txt
50
+ Version: 2.2.3
51
+ Doing work using input input.txt and config config.toml
52
+
53
+ ```
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_03_relations.rs ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::path::PathBuf;
2
+
3
+ use clap::{arg, command, value_parser, ArgAction, ArgGroup};
4
+
5
+ fn main() {
6
+ // Create application like normal
7
+ let matches = command!() // requires `cargo` feature
8
+ // Add the version arguments
9
+ .arg(arg!(--"set-ver" <VER> "set version manually"))
10
+ .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue))
11
+ .arg(arg!(--minor "auto inc minor").action(ArgAction::SetTrue))
12
+ .arg(arg!(--patch "auto inc patch").action(ArgAction::SetTrue))
13
+ // Create a group, make it required, and add the above arguments
14
+ .group(
15
+ ArgGroup::new("vers")
16
+ .required(true)
17
+ .args(["set-ver", "major", "minor", "patch"]),
18
+ )
19
+ // Arguments can also be added to a group individually, these two arguments
20
+ // are part of the "input" group which is not required
21
+ .arg(
22
+ arg!([INPUT_FILE] "some regular input")
23
+ .value_parser(value_parser!(PathBuf))
24
+ .group("input"),
25
+ )
26
+ .arg(
27
+ arg!(--"spec-in" <SPEC_IN> "some special input argument")
28
+ .value_parser(value_parser!(PathBuf))
29
+ .group("input"),
30
+ )
31
+ // Now let's assume we have a -c [config] argument which requires one of
32
+ // (but **not** both) the "input" arguments
33
+ .arg(
34
+ arg!(config: -c <CONFIG>)
35
+ .value_parser(value_parser!(PathBuf))
36
+ .requires("input"),
37
+ )
38
+ .get_matches();
39
+
40
+ // Let's assume the old version 1.2.3
41
+ let mut major = 1;
42
+ let mut minor = 2;
43
+ let mut patch = 3;
44
+
45
+ // See if --set-ver was used to set the version manually
46
+ let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
47
+ ver.to_owned()
48
+ } else {
49
+ // Increment the one requested (in a real program, we'd reset the lower numbers)
50
+ let (maj, min, pat) = (
51
+ matches.get_flag("major"),
52
+ matches.get_flag("minor"),
53
+ matches.get_flag("patch"),
54
+ );
55
+ match (maj, min, pat) {
56
+ (true, _, _) => major += 1,
57
+ (_, true, _) => minor += 1,
58
+ (_, _, true) => patch += 1,
59
+ _ => unreachable!(),
60
+ };
61
+ format!("{major}.{minor}.{patch}")
62
+ };
63
+
64
+ println!("Version: {version}");
65
+
66
+ // Check for usage of -c
67
+ if matches.contains_id("config") {
68
+ let input = matches
69
+ .get_one::<PathBuf>("INPUT_FILE")
70
+ .unwrap_or_else(|| matches.get_one::<PathBuf>("spec-in").unwrap())
71
+ .display();
72
+ println!(
73
+ "Doing work using input {} and config {}",
74
+ input,
75
+ matches.get_one::<PathBuf>("config").unwrap().display()
76
+ );
77
+ }
78
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/clap-4.5.60/examples/tutorial_builder/04_04_custom.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ```console
2
+ $ 04_04_custom --help
3
+ A simple to use, efficient, and full-featured Command Line Argument Parser
4
+
5
+ Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
6
+
7
+ Arguments:
8
+ [INPUT_FILE] some regular input
9
+
10
+ Options:
11
+ --set-ver <VER> set version manually
12
+ --major auto inc major
13
+ --minor auto inc minor
14
+ --patch auto inc patch
15
+ --spec-in <SPEC_IN> some special input argument
16
+ -c <CONFIG>
17
+ -h, --help Print help
18
+ -V, --version Print version
19
+
20
+ $ 04_04_custom
21
+ ? failed
22
+ error: Can only modify one version field
23
+
24
+ Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
25
+
26
+ For more information, try '--help'.
27
+
28
+ $ 04_04_custom --major
29
+ Version: 2.2.3
30
+
31
+ $ 04_04_custom --major --minor
32
+ ? failed
33
+ error: Can only modify one version field
34
+
35
+ Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
36
+
37
+ For more information, try '--help'.
38
+
39
+ $ 04_04_custom --major -c config.toml
40
+ ? failed
41
+ Version: 2.2.3
42
+ error: INPUT_FILE or --spec-in is required when using --config
43
+
44
+ Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
45
+
46
+ For more information, try '--help'.
47
+
48
+ $ 04_04_custom --major -c config.toml --spec-in input.txt
49
+ Version: 2.2.3
50
+ Doing work using input input.txt and config config.toml
51
+
52
+ ```