1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
use proc_macro2::TokenStream;
use pyo3::{Borrowed, FromPyObject, PyAny, PyResult, prelude::PyAnyMethods};
use quote::quote;
use serde::{Deserialize, Serialize};
use crate::{
CodeGen, CodeGenContext, ExprType, Node, PythonOptions, SymbolTableScopes,
};
/// Raise statement (raise [exception [from cause]])
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Raise {
/// The exception to raise (optional - bare raise re-raises current exception)
pub exc: Option<ExprType>,
/// The cause of the exception (optional - used with 'from' clause)
pub cause: Option<ExprType>,
/// Position information
pub lineno: Option<usize>,
pub col_offset: Option<usize>,
pub end_lineno: Option<usize>,
pub end_col_offset: Option<usize>,
}
impl<'a, 'py> FromPyObject<'a, 'py> for Raise {
type Error = pyo3::PyErr;
fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
// Extract exc (optional)
let exc: Option<ExprType> = if let Ok(exc_attr) = ob.getattr("exc") {
if exc_attr.is_none() {
None
} else {
Some(exc_attr.extract()?)
}
} else {
None
};
// Extract cause (optional)
let cause: Option<ExprType> = if let Ok(cause_attr) = ob.getattr("cause") {
if cause_attr.is_none() {
None
} else {
Some(cause_attr.extract()?)
}
} else {
None
};
Ok(Raise {
exc,
cause,
lineno: ob.lineno(),
col_offset: ob.col_offset(),
end_lineno: ob.end_lineno(),
end_col_offset: ob.end_col_offset(),
})
}
}
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 {
// `raise X from Y`: keep the cause visible in the message
// rather than dropping it.
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 => {
// Bare `raise` re-raises the exception the enclosing except
// handler caught (a runtime error outside a handler, as in
// Python).
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())
}
};
// Functions return Result<T, PyException>, so raising is returning
// Err: inside a try block it returns out of the block's Result
// closure to be caught by the handlers, and anywhere else it
// propagates out of the function, as in Python.
Ok(quote!(return Err(#exc_tokens)))
}
}
/// Names that look like Python exception classes, so `raise Name` /
/// `raise Name(...)` can construct a PyException carrying that class name.
/// Anything else is treated as an expression already producing a
/// PyException value (e.g. a variable bound by `except ... as e`).
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")
}
/// Lower the raised expression to a PyException value: `Name(...)` and bare
/// `Name` forms that look like exception classes construct one carrying the
/// class name (so handlers can match on it); any other expression is
/// assumed to already be a PyException.
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(test)]
mod tests {
// Tests would go here - currently commented out as they need full AST infrastructure
// create_parse_test!(test_simple_raise, "raise ValueError('error')", "test.py");
}