• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! [![github]](https://github.com/dtolnay/no-panic) [![crates-io]](https://crates.io/crates/no-panic) [![docs-rs]](https://docs.rs/no-panic)
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 //! A Rust attribute macro to require that the compiler prove a function can't
10 //! ever panic.
11 //!
12 //! ```toml
13 //! [dependencies]
14 //! no-panic = "0.1"
15 //! ```
16 //!
17 //! ```
18 //! use no_panic::no_panic;
19 //!
20 //! #[no_panic]
21 //! fn demo(s: &str) -> &str {
22 //!     &s[1..]
23 //! }
24 //!
25 //! fn main() {
26 //!     # fn demo(s: &str) -> &str {
27 //!     #     &s[1..]
28 //!     # }
29 //!     #
30 //!     println!("{}", demo("input string"));
31 //! }
32 //! ```
33 //!
34 //! If the function does panic (or the compiler fails to prove that the function
35 //! cannot panic), the program fails to compile with a linker error that
36 //! identifies the function name. Let's trigger that by passing a string that
37 //! cannot be sliced at the first byte:
38 //!
39 //! ```should_panic
40 //! # fn demo(s: &str) -> &str {
41 //! #     &s[1..]
42 //! # }
43 //! #
44 //! fn main() {
45 //!     println!("{}", demo("\u{1f980}input string"));
46 //! }
47 //! ```
48 //!
49 //! ```console
50 //!    Compiling no-panic-demo v0.0.1
51 //! error: linking with `cc` failed: exit code: 1
52 //!   |
53 //!   = note: /no-panic-demo/target/release/deps/no_panic_demo-7170785b672ae322.no_p
54 //! anic_demo1-cba7f4b666ccdbcbbf02b7348e5df1b2.rs.rcgu.o: In function `_$LT$no_pani
55 //! c_demo..demo..__NoPanic$u20$as$u20$core..ops..drop..Drop$GT$::drop::h72f8f423002
56 //! b8d9f':
57 //!           no_panic_demo1-cba7f4b666ccdbcbbf02b7348e5df1b2.rs:(.text._ZN72_$LT$no
58 //! _panic_demo..demo..__NoPanic$u20$as$u20$core..ops..drop..Drop$GT$4drop17h72f8f42
59 //! 3002b8d9fE+0x2): undefined reference to `
60 //!
61 //!           ERROR[no-panic]: detected panic in function `demo`
62 //!           '
63 //!           collect2: error: ld returned 1 exit status
64 //! ```
65 //!
66 //! The error is not stellar but notice the ERROR\[no-panic\] part at the end
67 //! that provides the name of the offending function.
68 //!
69 //! *Compiler support: requires rustc 1.31+*
70 //!
71 //! <br>
72 //!
73 //! ## Caveats
74 //!
75 //! - Functions that require some amount of optimization to prove that they do
76 //!   not panic may no longer compile in debug mode after being marked
77 //!   `#[no_panic]`.
78 //!
79 //! - Panic detection happens at link time across the entire dependency graph,
80 //!   so any Cargo commands that do not invoke a linker will not trigger panic
81 //!   detection. This includes `cargo build` of library crates and `cargo check`
82 //!   of binary and library crates.
83 //!
84 //! - The attribute is useless in code built with `panic = "abort"`.
85 //!
86 //! If you find that code requires optimization to pass `#[no_panic]`, either
87 //! make no-panic an optional dependency that you only enable in release builds,
88 //! or add a section like the following to Cargo.toml to enable very basic
89 //! optimization in debug builds.
90 //!
91 //! ```toml
92 //! [profile.dev]
93 //! opt-level = 1
94 //! ```
95 //!
96 //! If the code that you need to prove isn't panicking makes function calls to
97 //! non-generic non-inline functions from a different crate, you may need thin
98 //! LTO enabled for the linker to deduce those do not panic.
99 //!
100 //! ```toml
101 //! [profile.release]
102 //! lto = "thin"
103 //! ```
104 //!
105 //! If you want no_panic to just assume that some function you call doesn't
106 //! panic, and get Undefined Behavior if it does at runtime, see
107 //! [dtolnay/no-panic#16]; try wrapping that call in an `unsafe extern "C"`
108 //! wrapper.
109 //!
110 //! [dtolnay/no-panic#16]: https://github.com/dtolnay/no-panic/issues/16
111 //!
112 //! <br>
113 //!
114 //! ## Acknowledgments
115 //!
116 //! The linker error technique is based on [Kixunil]'s crate [`dont_panic`].
117 //! Check out that crate for other convenient ways to require absence of panics.
118 //!
119 //! [Kixunil]: https://github.com/Kixunil
120 //! [`dont_panic`]: https://github.com/Kixunil/dont_panic
121 
122 #![doc(html_root_url = "https://docs.rs/no-panic/0.1.21")]
123 #![allow(
124     clippy::doc_markdown,
125     clippy::match_same_arms,
126     clippy::missing_panics_doc
127 )]
128 #![cfg_attr(all(test, exhaustive), feature(non_exhaustive_omitted_patterns_lint))]
129 
130 extern crate proc_macro;
131 
132 use proc_macro::TokenStream;
133 use proc_macro2::{Span, TokenStream as TokenStream2};
134 use quote::quote;
135 use syn::parse::{Error, Nothing, Result};
136 use syn::{
137     parse_quote, Attribute, FnArg, GenericArgument, Ident, ItemFn, Pat, PatType, Path,
138     PathArguments, ReturnType, Token, Type, TypeInfer, TypeParamBound,
139 };
140 
141 #[proc_macro_attribute]
no_panic(args: TokenStream, input: TokenStream) -> TokenStream142 pub fn no_panic(args: TokenStream, input: TokenStream) -> TokenStream {
143     let args = TokenStream2::from(args);
144     let input = TokenStream2::from(input);
145     let expanded = match parse(args, input.clone()) {
146         Ok(function) => expand_no_panic(function),
147         Err(parse_error) => {
148             let compile_error = parse_error.to_compile_error();
149             quote!(#compile_error #input)
150         }
151     };
152     TokenStream::from(expanded)
153 }
154 
parse(args: TokenStream2, input: TokenStream2) -> Result<ItemFn>155 fn parse(args: TokenStream2, input: TokenStream2) -> Result<ItemFn> {
156     let function: ItemFn = syn::parse2(input)?;
157     let _: Nothing = syn::parse2::<Nothing>(args)?;
158     if function.sig.asyncness.is_some() {
159         return Err(Error::new(
160             Span::call_site(),
161             "no_panic attribute on async fn is not supported",
162         ));
163     }
164     Ok(function)
165 }
166 
167 // Convert `Path<impl Trait>` to `Path<_>`
make_impl_trait_wild(ret: &mut Type)168 fn make_impl_trait_wild(ret: &mut Type) {
169     match ret {
170         Type::ImplTrait(impl_trait) => {
171             *ret = Type::Infer(TypeInfer {
172                 underscore_token: Token![_](impl_trait.impl_token.span),
173             });
174         }
175         Type::Array(ret) => make_impl_trait_wild(&mut ret.elem),
176         Type::Group(ret) => make_impl_trait_wild(&mut ret.elem),
177         Type::Paren(ret) => make_impl_trait_wild(&mut ret.elem),
178         Type::Path(ret) => make_impl_trait_wild_in_path(&mut ret.path),
179         Type::Ptr(ret) => make_impl_trait_wild(&mut ret.elem),
180         Type::Reference(ret) => make_impl_trait_wild(&mut ret.elem),
181         Type::Slice(ret) => make_impl_trait_wild(&mut ret.elem),
182         Type::TraitObject(ret) => {
183             for bound in &mut ret.bounds {
184                 if let TypeParamBound::Trait(bound) = bound {
185                     make_impl_trait_wild_in_path(&mut bound.path);
186                 }
187             }
188         }
189         Type::Tuple(ret) => ret.elems.iter_mut().for_each(make_impl_trait_wild),
190         Type::BareFn(_) | Type::Infer(_) | Type::Macro(_) | Type::Never(_) | Type::Verbatim(_) => {}
191         #[cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
192         _ => {}
193     }
194 }
195 
make_impl_trait_wild_in_path(path: &mut Path)196 fn make_impl_trait_wild_in_path(path: &mut Path) {
197     for segment in &mut path.segments {
198         if let PathArguments::AngleBracketed(bracketed) = &mut segment.arguments {
199             for arg in &mut bracketed.args {
200                 if let GenericArgument::Type(arg) = arg {
201                     make_impl_trait_wild(arg);
202                 }
203             }
204         }
205     }
206 }
207 
expand_no_panic(mut function: ItemFn) -> TokenStream2208 fn expand_no_panic(mut function: ItemFn) -> TokenStream2 {
209     let mut move_self = None;
210     let mut arg_pat = Vec::new();
211     let mut arg_val = Vec::new();
212     for (i, input) in function.sig.inputs.iter_mut().enumerate() {
213         let numbered = Ident::new(&format!("__arg{}", i), Span::call_site());
214         match input {
215             FnArg::Typed(PatType { pat, .. })
216                 if match pat.as_ref() {
217                     Pat::Ident(pat) => pat.ident != "self",
218                     _ => true,
219                 } =>
220             {
221                 arg_pat.push(quote!(#pat));
222                 arg_val.push(quote!(#numbered));
223                 *pat = parse_quote!(mut #numbered);
224             }
225             FnArg::Typed(_) | FnArg::Receiver(_) => {
226                 move_self = Some(quote! {
227                     if false {
228                         loop {}
229                         #[allow(unreachable_code)]
230                         {
231                             let __self = self;
232                         }
233                     }
234                 });
235             }
236         }
237     }
238 
239     let has_inline = function
240         .attrs
241         .iter()
242         .flat_map(Attribute::parse_meta)
243         .any(|meta| meta.path().is_ident("inline"));
244     if !has_inline {
245         function.attrs.push(parse_quote!(#[inline]));
246     }
247 
248     let ret = match &function.sig.output {
249         ReturnType::Default => quote!(-> ()),
250         ReturnType::Type(arrow, output) => {
251             let mut output = output.clone();
252             make_impl_trait_wild(&mut output);
253             quote!(#arrow #output)
254         }
255     };
256     let stmts = function.block.stmts;
257     let message = format!(
258         "\n\nERROR[no-panic]: detected panic in function `{}`\n",
259         function.sig.ident,
260     );
261     function.block = Box::new(parse_quote!({
262         struct __NoPanic;
263         extern "C" {
264             #[link_name = #message]
265             fn trigger() -> !;
266         }
267         impl core::ops::Drop for __NoPanic {
268             fn drop(&mut self) {
269                 unsafe {
270                     trigger();
271                 }
272             }
273         }
274         let __guard = __NoPanic;
275         let __result = (move || #ret {
276             #move_self
277             #(
278                 let #arg_pat = #arg_val;
279             )*
280             #(#stmts)*
281         })();
282         core::mem::forget(__guard);
283         __result
284     }));
285 
286     quote!(#function)
287 }
288