use proc_macro2::TokenStream;
use quote::quote;
use serde::{Deserialize, Serialize};
use crate::python_ast::{CodeGen, CodeGenContext, ExprType, Node, PythonOptions, SymbolTableScopes};
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Raise {
pub exc: Option<ExprType>,
pub cause: Option<ExprType>,
pub lineno: Option<usize>,
pub col_offset: Option<usize>,
pub end_lineno: Option<usize>,
pub end_col_offset: Option<usize>,
}
impl Node for Raise {
fn lineno(&self) -> Option<usize> {
self.lineno
}
fn col_offset(&self) -> Option<usize> {
self.col_offset
}
fn end_lineno(&self) -> Option<usize> {
self.end_lineno
}
fn end_col_offset(&self) -> Option<usize> {
self.end_col_offset
}
}
impl CodeGen for Raise {
type Context = CodeGenContext;
type Options = PythonOptions;
type SymbolTable = SymbolTableScopes;
fn find_symbols(self, symbols: Self::SymbolTable) -> Self::SymbolTable {
let symbols = if let Some(exc) = self.exc { exc.find_symbols(symbols) } else { symbols };
if let Some(cause) = self.cause { cause.find_symbols(symbols) } else { symbols }
}
fn to_rust(self, ctx: Self::Context, options: Self::Options, symbols: Self::SymbolTable) -> Result<TokenStream, Box<dyn std::error::Error>> {
let exc_tokens = match self.exc {
Some(exc) => {
let mut tokens = exception_value(&exc, ctx.clone(), options.clone(), symbols.clone())?;
if let Some(cause) = self.cause {
let cause_tokens = cause.to_rust(ctx.clone(), options, symbols)?;
tokens = quote! {
{
let mut __rython_raised = #tokens;
__rython_raised.message =
format!("{} [from {}]", __rython_raised.message, #cause_tokens);
__rython_raised
}
};
}
tokens
}
None => {
if !ctx.in_except_handler() {
return Err("bare `raise` outside an except handler has no exception to re-raise".to_string().into());
}
quote!(__rython_exc.clone())
}
};
Ok(quote!(return Err(#exc_tokens)))
}
}
fn is_exception_class_name(name: &str) -> bool {
matches!(
name,
"Exception"
| "BaseException"
| "ArithmeticError"
| "AssertionError"
| "AttributeError"
| "BufferError"
| "EOFError"
| "FileExistsError"
| "FileNotFoundError"
| "FloatingPointError"
| "ImportError"
| "IndentationError"
| "IndexError"
| "InterruptedError"
| "IsADirectoryError"
| "KeyError"
| "KeyboardInterrupt"
| "LookupError"
| "MemoryError"
| "ModuleNotFoundError"
| "NameError"
| "NotADirectoryError"
| "NotImplementedError"
| "OSError"
| "OverflowError"
| "PermissionError"
| "RecursionError"
| "ReferenceError"
| "RuntimeError"
| "StopAsyncIteration"
| "StopIteration"
| "SyntaxError"
| "SystemError"
| "SystemExit"
| "TabError"
| "TimeoutError"
| "TypeError"
| "UnboundLocalError"
| "UnicodeDecodeError"
| "UnicodeEncodeError"
| "UnicodeError"
| "ValueError"
| "ZeroDivisionError"
) || name.ends_with("Error")
|| name.ends_with("Exception")
|| name.ends_with("Warning")
}
fn exception_value(
exc: &ExprType,
ctx: CodeGenContext,
options: PythonOptions,
symbols: SymbolTableScopes,
) -> Result<TokenStream, Box<dyn std::error::Error>> {
match exc {
ExprType::Call(call) => {
if let ExprType::Name(name) = call.func.as_ref() {
if is_exception_class_name(&name.id) {
let kind = &name.id;
let msg = match call.args.len() {
0 => quote!(String::new()),
1 => {
let arg = call.args[0].clone().to_rust(ctx, options, symbols)?;
quote!(format!("{}", #arg))
}
_ => {
let args: Result<Vec<TokenStream>, Box<dyn std::error::Error>> =
call.args.iter().map(|a| a.clone().to_rust(ctx.clone(), options.clone(), symbols.clone())).collect();
let args = args?;
let fmt = vec!["{}"; args.len()].join(", ");
quote!(format!(#fmt, #(#args),*))
}
};
return Ok(quote!(PyException::new(#kind, #msg)));
}
}
let tokens = exc.clone().to_rust(ctx, options, symbols)?;
Ok(quote!(#tokens))
}
ExprType::Name(name) if is_exception_class_name(&name.id) => {
let kind = &name.id;
Ok(quote!(PyException::new(#kind, String::new())))
}
other => {
let tokens = other.clone().to_rust(ctx, options, symbols)?;
Ok(quote!(#tokens))
}
}
}
#[cfg(python_ast_upstream_tests)]
mod tests {
}