| 1 | use defmt_parser::Level; |
| 2 | use proc_macro::TokenStream; |
| 3 | use quote::quote; |
| 4 | use syn::{parse_macro_input, punctuated::Punctuated}; |
| 5 | |
| 6 | use crate::{construct, function_like::log}; |
| 7 | |
| 8 | pub(crate) fn expand(args: TokenStream) -> TokenStream { |
| 9 | let args = parse_macro_input!(args as super::Args); |
| 10 | |
| 11 | let condition = args.condition; |
| 12 | let (format_string, formatting_args) = if let Some(log_args) = args.log_args { |
| 13 | let format_string = format!("panicked at ' {}'" , log_args.format_string.value()); |
| 14 | (format_string, log_args.formatting_args) |
| 15 | } else { |
| 16 | let format_string = format!( |
| 17 | "panicked at 'unwrap failed: {}' \nerror: ` {{:? }}`" , |
| 18 | construct::escaped_expr_string(&condition) |
| 19 | ); |
| 20 | |
| 21 | let mut formatting_args = Punctuated::new(); |
| 22 | formatting_args.push(construct::variable("_unwrap_err" )); |
| 23 | |
| 24 | (format_string, Some(formatting_args)) |
| 25 | }; |
| 26 | |
| 27 | let format_string = construct::string_literal(&format_string); |
| 28 | let log_stmt = log::expand_parsed( |
| 29 | Level::Error, |
| 30 | log::Args { |
| 31 | format_string, |
| 32 | formatting_args, |
| 33 | }, |
| 34 | ); |
| 35 | |
| 36 | quote!( |
| 37 | match defmt::export::into_result(#condition) { |
| 38 | ::core::result::Result::Ok(res) => res, |
| 39 | ::core::result::Result::Err(_unwrap_err) => { |
| 40 | #log_stmt; |
| 41 | defmt::export::panic() |
| 42 | } |
| 43 | } |
| 44 | ) |
| 45 | .into() |
| 46 | } |
| 47 | |