Debian Codegraph @

pypy/module/exceptions/app_group.py

raw symbols SCIP
1 # helper functions for interp_group.py that are exposed via a gateway.applevel
2
3
4 def check_new_args(cls, message, exceptions):
5 if not isinstance(message, str):
6 raise TypeError(f"argument 1 must be str, not {type(message)}")
7 if not isinstance(exceptions, (list, tuple)):
8 from collections.abc import Sequence
9 if not isinstance(exceptions, Sequence):
10 raise TypeError("second argument (exceptions) must be a sequence")
11 if not exceptions or not exceptions.count:
12 raise ValueError("second argument (exceptions) must be a non-empty sequence")
13
14 for i, exc in enumerate(exceptions):
15 if not isinstance(exc, BaseException):
16 raise ValueError(f"Item {i} of second argument (exceptions) is not an exception")
17
18 if cls is BaseExceptionGroup:
19 if all(isinstance(exc, Exception) for exc in exceptions):
20 cls = ExceptionGroup
21
22 if issubclass(cls, Exception):
23 for exc in exceptions:
24 if not isinstance(exc, Exception):
25 if cls is ExceptionGroup:
26 raise TypeError("Cannot nest BaseExceptions in an ExceptionGroup")
27 else:
28 raise TypeError(f"Cannot nest BaseExceptions in {cls.__name__!r}")
29 return cls, tuple(exceptions)
30
31 def subgroup(self, condition):
32 condition = get_condition_filter(condition)
33 modified = False
34 if condition(self):
35 return self
36
37 exceptions = []
38 for exc in self.exceptions:
39 if isinstance(exc, BaseExceptionGroup):
40 subgroup = exc.subgroup(condition)
41 if subgroup is not None:
42 exceptions.append(subgroup)
43 if subgroup is not exc:
44 modified = True
45 elif condition(exc):
46 exceptions.append(exc)
47 else:
48 modified = True
49
50 if not modified:
51 # this is the difference to split!
52 return self
53 elif exceptions:
54 group = _derive_and_copy_attrs(self, exceptions)
55 return group
56 else:
57 return None
58
59 def split(self, condition):
60 condition = get_condition_filter(condition)
61 if condition(self):
62 return self, None
63
64 matching_exceptions = []
65 nonmatching_exceptions = []
66 for exc in self.exceptions:
67 if isinstance(exc, BaseExceptionGroup):
68 matching, nonmatching = exc.split(condition)
69 if matching is not None:
70 matching_exceptions.append(matching)
71 if nonmatching is not None:
72 nonmatching_exceptions.append(nonmatching)
73 elif condition(exc):
74 matching_exceptions.append(exc)
75 else:
76 nonmatching_exceptions.append(exc)
77
78 matching_group = None
79 if matching_exceptions:
80 matching_group = _derive_and_copy_attrs(self, matching_exceptions)
81
82 nonmatching_group = None
83 if nonmatching_exceptions:
84 nonmatching_group = _derive_and_copy_attrs(self, nonmatching_exceptions)
85
86 return (matching_group, nonmatching_group)
87
88 def __str__(self):
89 suffix = "" if len(self.exceptions) == 1 else "s"
90 return f"{self.message} ({len(self.exceptions)} sub-exception{suffix})"
91
92 def __repr__(self):
93 return f"{self.__class__.__name__}({self.message!r}, {list(self.exceptions)!r})"
94
95 def _derive_and_copy_attrs(self, excs):
96 eg = self.derive(excs)
97 if hasattr(self, "__notes__"):
98 # Create a new list so that add_note() only affects one exceptiongroup
99 try:
100 eg.__notes__ = list(self.__notes__)
101 except TypeError:
102 # ignore non-sequence __notes__
103 pass
104 eg.__cause__ = self.__cause__
105 eg.__context__ = self.__context__
106 eg.__traceback__ = self.__traceback__
107 return eg
108
109
110 _SENTINEL = object()
111
112 def _is_same_exception_metadata(exc1, exc2):
113 # TODO: Exception or BaseException?
114 assert isinstance(exc1, Exception)
115 assert isinstance(exc2, Exception)
116
117 return (getattr(exc1, '__notes__', _SENTINEL) is getattr(exc2, '__notes__', _SENTINEL) and
118 exc1.__traceback__ is exc2.__traceback__ and
119 exc1.__cause__ is exc2.__cause__ and
120 exc1.__context__ is exc2.__context__)
121
122 def get_condition_filter(condition):
123 if isinstance(condition, type) and issubclass(condition, BaseException):
124 return lambda exc: isinstance(exc, condition)
125 elif isinstance(condition, tuple) and \
126 all((isinstance(c, type) and issubclass(c, BaseException)) for c in condition):
127 return lambda exc: isinstance(exc, condition)
128 elif callable(condition):
129 return condition
130 # otherwise
131 raise TypeError("expected a function, exception type or tuple of exception types")
132
133 # helper functions for the interpreter
134
135 def _exception_group_projection(eg, keep_list):
136 """
137 From CPython:
138 /* This function is used by the interpreter to construct reraised
139 * exception groups. It takes an exception group eg and a list
140 * of exception groups keep and returns the sub-exception group
141 * of eg which contains all leaf exceptions that are contained
142 * in any exception group in keep.
143 */
144 """
145 from __pypy__ import identity_dict
146 # TODO: muss es nicht eigentlich anders herum sein
147 # (return rest instead of match)?
148 assert isinstance(eg, BaseExceptionGroup)
149 assert isinstance(keep_list, list)
150
151 resultset = identity_dict()
152 for keep in keep_list:
153 _collect_eg_leafs(keep, resultset)
154
155 # TODO: maybe don't construct rest eg
156 split_match, _ = eg.split(lambda element: element in resultset)
157
158 return split_match
159
160 def _collect_eg_leafs(eg_or_exc, resultset):
161 if eg_or_exc is None:
162 # empty exception groups appear as a result
163 # of matches (split, subgroup) and thus are valid
164 pass
165 elif isinstance(eg_or_exc, BaseExceptionGroup):
166 # recursively collect children of eg
167 for subexc in eg_or_exc.exceptions:
168 _collect_eg_leafs(subexc, resultset)
169 elif isinstance(eg_or_exc, BaseException):
170 # we have a single exception (not a group),
171 # return a singleton list containing the exc
172 resultset[eg_or_exc] = None
173 else:
174 raise TypeError(f"expected BaseException, got {type(eg_or_exc)}")
175
176 def _prep_reraise_star(orig, exc_list):
177 assert isinstance(orig, BaseException)
178 assert isinstance(exc_list, list)
179
180 # TODO: test this:
181 if len(exc_list) < 1:
182 return None
183
184 for exc in exc_list: assert isinstance(exc, BaseException) or exc is None
185
186 if not isinstance(orig, BaseExceptionGroup):
187 # a naked exception was caught and wrapped. Only one except* clause
188 # could have executed,so there is at most one exception to raise.
189 assert len(exc_list) == 1 or (len(exc_list) == 2 and exc_list[1] is None)
190 return exc_list[0]
191
192 raised_list = []
193 reraised_list = []
194 for exc in exc_list:
195 if exc is not None:
196 if _is_same_exception_metadata(exc, orig):
197 reraised_list.append(exc)
198 else:
199 raised_list.append(exc)
200
201 reraised_eg = _exception_group_projection(orig, reraised_list)
202 if reraised_eg is not None:
203 assert _is_same_exception_metadata(reraised_eg, orig)
204
205 if not raised_list:
206 return reraised_eg
207 if reraised_eg is not None:
208 raised_list.append(reraised_eg)
209 if len(raised_list) == 1:
210 return raised_list[0]
211 return ExceptionGroup("", raised_list)
212