use crate::builtins::{exception_isa, is_exception_class};
use crate::host::{self, with_host, PyHost, PyObj};
use fusevm::Value;
use std::collections::HashSet;
pub const BASE_GROUP: &str = "BaseExceptionGroup";
pub const GROUP: &str = "ExceptionGroup";
const MATCHER_TYPE_ERROR: &str = "TypeError: expected an exception type, a tuple of exception \
types, or a callable (other than a class)";
pub fn class_is_group(h: &PyHost, class: &str) -> bool {
class == GROUP || class == BASE_GROUP || h.mro_of(class).iter().any(|c| c == BASE_GROUP)
}
pub fn is_group(h: &PyHost, v: &Value) -> bool {
match h.get(v) {
Some(PyObj::Exception { class, .. }) => class_is_group(h, class),
Some(PyObj::Instance(i)) => class_is_group(h, &i.class),
_ => false,
}
}
pub fn group_parts(h: &PyHost, v: &Value) -> Option<(Value, Vec<Value>)> {
if !is_group(h, v) {
return None;
}
let args = match h.get(v) {
Some(PyObj::Exception { args, .. }) => args.clone(),
Some(PyObj::Instance(_)) => h.exc_instance_args(v),
_ => return None,
};
let (msg, excs) = (args.first()?.clone(), args.get(1)?);
let items = match h.get(excs) {
Some(PyObj::List(l)) | Some(PyObj::Tuple(l)) => l.clone(),
_ => return None,
};
Some((msg, items))
}
fn group_excs(h: &PyHost, v: &Value) -> Vec<Value> {
group_parts(h, v).map(|(_, e)| e).unwrap_or_default()
}
fn class_of(h: &PyHost, v: &Value) -> String {
match h.get(v) {
Some(PyObj::Exception { class, .. }) => class.clone(),
Some(PyObj::Instance(i)) => i.class.clone(),
_ => h.type_name(v),
}
}
fn is_exception_instance(h: &PyHost, v: &Value) -> bool {
match h.get(v) {
Some(PyObj::Exception { .. }) => true,
Some(PyObj::Instance(i)) => h.class_is_exception(&i.class),
_ => false,
}
}
fn is_nonbase_exception(h: &PyHost, v: &Value) -> bool {
exception_isa(&class_of(h, v), "Exception", h)
}
pub fn construct(h: &mut PyHost, class: &str, args: &[Value]) -> Result<Value, String> {
if args.len() != 2 {
return Err(format!(
"TypeError: BaseExceptionGroup.__new__() takes exactly 2 arguments ({} given)",
args.len()
));
}
let message = &args[0];
if !matches!(h.get(message), Some(PyObj::Str(_))) && !matches!(message, Value::Str(_)) {
return Err(format!(
"TypeError: BaseExceptionGroup.__new__() argument 1 must be str, not {}",
h.type_name(message)
));
}
let items = match h.get(&args[1]) {
Some(PyObj::List(l)) | Some(PyObj::Tuple(l)) => l.clone(),
_ => return Err("TypeError: second argument (exceptions) must be a sequence".to_string()),
};
if items.is_empty() {
return Err(
"ValueError: second argument (exceptions) must be a non-empty sequence".to_string(),
);
}
let mut nested_base = false;
for (i, e) in items.iter().enumerate() {
if !is_exception_instance(h, e) {
return Err(format!(
"ValueError: Item {i} of second argument (exceptions) is not an exception"
));
}
if !is_nonbase_exception(h, e) {
nested_base = true;
}
}
let cls = match class {
GROUP if nested_base => {
return Err("TypeError: Cannot nest BaseExceptions in an ExceptionGroup".to_string())
}
BASE_GROUP if !nested_base => GROUP,
other => other,
};
Ok(h.alloc(PyObj::Exception {
class: cls.to_string(),
args: args.to_vec(),
}))
}
pub fn create(h: &mut PyHost, message: &str, excs: Vec<Value>) -> Value {
let msg = h.new_str(message);
let list = h.new_list(excs);
construct(h, BASE_GROUP, &[msg.clone(), list.clone()]).unwrap_or_else(|_| {
h.alloc(PyObj::Exception {
class: BASE_GROUP.to_string(),
args: vec![msg, list],
})
})
}
enum Matcher {
Type(Value),
Predicate(Value),
Ids(HashSet<u32>),
}
fn matcher_of(v: &Value) -> Result<Matcher, String> {
let ok = with_host(|h| {
if is_exception_class_value(h, v) {
return Some(true);
}
if let Some(PyObj::Tuple(ts)) = h.get(v) {
let all = ts.iter().all(|t| is_exception_class_value(h, t));
return if all { Some(true) } else { None };
}
if is_callable(h, v) {
return Some(false);
}
None
});
match ok {
Some(true) => Ok(Matcher::Type(v.clone())),
Some(false) => Ok(Matcher::Predicate(v.clone())),
None => Err(MATCHER_TYPE_ERROR.to_string()),
}
}
fn is_exception_class_value(h: &PyHost, v: &Value) -> bool {
match h.get(v) {
Some(PyObj::Builtin(n)) => is_exception_class(n),
Some(PyObj::Class(n)) => h.class_is_exception(n),
_ => false,
}
}
fn is_callable(h: &PyHost, v: &Value) -> bool {
match h.get(v) {
Some(PyObj::Func(_))
| Some(PyObj::Builtin(_))
| Some(PyObj::Class(_))
| Some(PyObj::Partial { .. })
| Some(PyObj::StaticMethod(_))
| Some(PyObj::ClassMethod(_))
| Some(PyObj::BoundMethod { .. }) => true,
Some(PyObj::Instance(i)) => h.class_lookup(&i.class, "__call__").is_some(),
_ => false,
}
}
fn check_match(exc: &Value, m: &Matcher) -> Result<bool, String> {
match m {
Matcher::Type(t) => Ok(with_host(|h| crate::builtins::exc_matches(h, exc, t))),
Matcher::Predicate(f) => {
let r = host::invoke(f, vec![exc.clone()], vec![])?;
Ok(with_host(|h| h.truthy(&r)))
}
Matcher::Ids(ids) => Ok(with_host(|h| {
!is_group(h, exc) && matches!(exc, Value::Obj(id) if ids.contains(id))
})),
}
}
fn subset(orig: &Value, excs: Vec<Value>) -> Option<Value> {
if excs.is_empty() {
return None;
}
Some(with_host(|h| derive_from(h, orig, excs)))
}
fn derive_from(h: &mut PyHost, orig: &Value, excs: Vec<Value>) -> Value {
let msg = group_parts(h, orig)
.map(|(m, _)| m)
.unwrap_or_else(|| h.new_str(""));
let list = h.new_list(excs);
let eg = construct(h, BASE_GROUP, &[msg.clone(), list.clone()]).unwrap_or_else(|_| {
h.alloc(PyObj::Exception {
class: BASE_GROUP.to_string(),
args: vec![msg, list],
})
});
if let (Value::Obj(src), Value::Obj(dst)) = (orig, &eg) {
if let Some(tb) = h.exc_tb.get(src).cloned() {
h.exc_tb.insert(*dst, tb);
}
if let Some(notes) = h.side_attr(*src, "__notes__") {
h.side_attr_set(*dst, "__notes__", notes);
}
if h.suppress_context.contains(src) {
h.suppress_context.insert(*dst);
}
let root = h.eg_split_root.get(src).copied().unwrap_or(*src);
h.eg_split_root.insert(*dst, root);
}
let (cause, context) = h.exc_link(orig);
h.set_exc_link(&eg, cause, context);
eg
}
fn split_recursive(
exc: &Value,
m: &Matcher,
construct_rest: bool,
) -> Result<(Option<Value>, Option<Value>), String> {
if check_match(exc, m)? {
return Ok((Some(exc.clone()), None));
}
if !with_host(|h| is_group(h, exc)) {
return Ok((None, construct_rest.then(|| exc.clone())));
}
let mut matched = Vec::new();
let mut rest = Vec::new();
for e in with_host(|h| group_excs(h, exc)) {
let (mm, rr) = split_recursive(&e, m, construct_rest)?;
matched.extend(mm);
rest.extend(rr);
}
Ok((
subset(exc, matched),
if construct_rest {
subset(exc, rest)
} else {
None
},
))
}
pub fn split(exc: &Value, matcher: &Value) -> Result<(Option<Value>, Option<Value>), String> {
let m = matcher_of(matcher)?;
split_recursive(exc, &m, true)
}
pub fn subgroup(exc: &Value, matcher: &Value) -> Result<Option<Value>, String> {
let m = matcher_of(matcher)?;
Ok(split_recursive(exc, &m, false)?.0)
}
pub fn derive(exc: &Value, excs: &Value) -> Result<Value, String> {
let items = with_host(|h| match h.get(excs) {
Some(PyObj::List(l)) | Some(PyObj::Tuple(l)) => Some(l.clone()),
_ => None,
})
.ok_or_else(|| "TypeError: second argument (exceptions) must be a sequence".to_string())?;
with_host(|h| {
let msg = group_parts(h, exc)
.map(|(m, _)| m)
.unwrap_or_else(|| h.new_str(""));
let list = h.new_list(items);
construct(h, BASE_GROUP, &[msg, list])
})
}
pub fn eg_match(exc: &Value, typ: &Value) -> Result<(Option<Value>, Option<Value>), String> {
if with_host(|h| crate::builtins::exc_matches(h, exc, typ)) {
let matched = with_host(|h| {
if is_group(h, exc) {
return exc.clone();
}
let msg = h.new_str("");
let tup = h.new_tuple(vec![exc.clone()]);
construct(h, BASE_GROUP, &[msg.clone(), tup.clone()]).unwrap_or_else(|_| {
h.alloc(PyObj::Exception {
class: BASE_GROUP.to_string(),
args: vec![msg, tup],
})
})
});
return Ok((Some(matched), None));
}
if with_host(|h| is_group(h, exc)) {
return split(exc, typ);
}
Ok((None, None))
}
fn collect_leaf_ids(h: &PyHost, exc: &Value, out: &mut HashSet<u32>) {
if !is_group(h, exc) {
if let Value::Obj(id) = exc {
out.insert(*id);
}
return;
}
for e in group_excs(h, exc) {
collect_leaf_ids(h, &e, out);
}
}
fn projection(eg: &Value, keep: &[Value]) -> Result<Option<Value>, String> {
let ids = with_host(|h| {
let mut ids = HashSet::new();
for e in keep {
collect_leaf_ids(h, e, &mut ids);
}
ids
});
Ok(split_recursive(eg, &Matcher::Ids(ids), false)?.0)
}
fn split_root(h: &PyHost, v: &Value) -> Option<u32> {
let Value::Obj(id) = v else { return None };
Some(h.eg_split_root.get(id).copied().unwrap_or(*id))
}
pub fn is_piece_of(h: &PyHost, v: &Value, orig: &Value) -> bool {
split_root(h, v) == split_root(h, orig)
}
pub fn prep_reraise_star(orig: &Value, excs: &[Value]) -> Result<Option<Value>, String> {
if excs.is_empty() {
return Ok(None);
}
if !with_host(|h| is_group(h, orig)) {
return Ok(Some(excs[0].clone()));
}
let (mut raised, reraised): (Vec<Value>, Vec<Value>) = with_host(|h| {
let root = split_root(h, orig);
excs.iter()
.cloned()
.partition(|e| split_root(h, e) != root || !is_group(h, e))
});
let reraised_eg = projection(orig, &reraised)?;
if raised.is_empty() {
return Ok(reraised_eg);
}
raised.extend(reraised_eg);
if raised.len() > 1 {
Ok(Some(with_host(|h| create(h, "", raised))))
} else {
Ok(raised.into_iter().next())
}
}