mutagroup 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mutagroup/__init__.py +9 -0
- mutagroup/collection.py +213 -0
- mutagroup/ignores.py +112 -0
- mutagroup/py.typed +0 -0
- mutagroup/supercollection.py +151 -0
- mutagroup-0.0.1.dist-info/LICENSE +131 -0
- mutagroup-0.0.1.dist-info/METADATA +110 -0
- mutagroup-0.0.1.dist-info/RECORD +10 -0
- mutagroup-0.0.1.dist-info/WHEEL +5 -0
- mutagroup-0.0.1.dist-info/top_level.txt +1 -0
mutagroup/__init__.py
ADDED
mutagroup/collection.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from copy import copy
|
|
3
|
+
from functools import update_wrapper
|
|
4
|
+
from re import fullmatch
|
|
5
|
+
from threading import Lock
|
|
6
|
+
from typing import (
|
|
7
|
+
Callable,
|
|
8
|
+
Dict,
|
|
9
|
+
FrozenSet,
|
|
10
|
+
Generic,
|
|
11
|
+
Iterable,
|
|
12
|
+
Optional,
|
|
13
|
+
TypeVar,
|
|
14
|
+
Union,
|
|
15
|
+
cast,
|
|
16
|
+
overload,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from cstvis import Collector, Context, Converter
|
|
20
|
+
from cstvis.converter import ConverterFilter, ConverterFunction
|
|
21
|
+
from cstvis.wrapper import CallableWrapper, _unwrap_partial
|
|
22
|
+
from libcst import CSTNode
|
|
23
|
+
|
|
24
|
+
from mutagroup.ignores import (
|
|
25
|
+
DEFAULT_METACODE_KEY,
|
|
26
|
+
CommentIgnores,
|
|
27
|
+
ignored_ids,
|
|
28
|
+
make_ignore_filter,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
if sys.version_info >= (3, 10): # pragma: no cover (<py310)
|
|
32
|
+
from typing import ParamSpec
|
|
33
|
+
else: # pragma: no cover (>=py310)
|
|
34
|
+
from typing_extensions import ParamSpec
|
|
35
|
+
|
|
36
|
+
_Parameters = ParamSpec('_Parameters')
|
|
37
|
+
_Replacement = TypeVar('_Replacement', bound=CSTNode)
|
|
38
|
+
_FilterParameters = ParamSpec('_FilterParameters')
|
|
39
|
+
_Filter = Callable[_FilterParameters, bool]
|
|
40
|
+
_Meta = Optional[Dict[str, object]]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _NodeFilter(CallableWrapper[bool]):
|
|
44
|
+
def call_with_context(self, node: CSTNode, context: Context) -> bool:
|
|
45
|
+
node_types = self.first_node_annotations
|
|
46
|
+
if type(node) in node_types or CSTNode in node_types:
|
|
47
|
+
return super().call_with_context(node, context)
|
|
48
|
+
return True
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _MutationConverter(Converter):
|
|
52
|
+
def __init__(self, mutation_id: str, function: ConverterFunction, meta: _Meta) -> None:
|
|
53
|
+
self.mutation_id = mutation_id
|
|
54
|
+
handler = cast(object, _unwrap_partial(function))
|
|
55
|
+
self.mutation_name = cast(str, getattr(handler, '__name__', type(handler).__name__))
|
|
56
|
+
super().__init__(function, meta=self._with_identity(meta))
|
|
57
|
+
|
|
58
|
+
def get_function_id(self) -> str:
|
|
59
|
+
return self.mutation_id
|
|
60
|
+
|
|
61
|
+
def _with_identity(self, meta: _Meta) -> Dict[str, object]:
|
|
62
|
+
return {**(meta or {}), 'mutation_id': self.mutation_id, 'mutation_name': self.mutation_name}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Mutation(Generic[_Parameters, _Replacement]):
|
|
66
|
+
"""A registered mutation that can be called directly or given bound filters."""
|
|
67
|
+
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
converter: _MutationConverter,
|
|
71
|
+
function: Callable[_Parameters, _Replacement],
|
|
72
|
+
) -> None:
|
|
73
|
+
self._converter = converter
|
|
74
|
+
self._function = function
|
|
75
|
+
update_wrapper(self, function, updated=())
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def id(self) -> str:
|
|
79
|
+
return self._converter.mutation_id
|
|
80
|
+
|
|
81
|
+
def __call__(self, *args: _Parameters.args, **kwargs: _Parameters.kwargs) -> _Replacement:
|
|
82
|
+
return self._function(*args, **kwargs)
|
|
83
|
+
|
|
84
|
+
@overload # pragma: no cover
|
|
85
|
+
def filter(self, function: _Filter[_FilterParameters], meta: _Meta = None) -> _Filter[_FilterParameters]: ...
|
|
86
|
+
|
|
87
|
+
@overload # pragma: no cover
|
|
88
|
+
def filter(
|
|
89
|
+
self, function: None = None, meta: _Meta = None,
|
|
90
|
+
) -> Callable[[_Filter[_FilterParameters]], _Filter[_FilterParameters]]: ...
|
|
91
|
+
|
|
92
|
+
def filter(
|
|
93
|
+
self,
|
|
94
|
+
function: Optional[_Filter[_FilterParameters]] = None,
|
|
95
|
+
meta: _Meta = None,
|
|
96
|
+
) -> Union[_Filter[_FilterParameters], Callable[[_Filter[_FilterParameters]], _Filter[_FilterParameters]]]:
|
|
97
|
+
"""Register a filter for this mutation on the node types it annotates."""
|
|
98
|
+
|
|
99
|
+
def register(predicate: _Filter[_FilterParameters]) -> _Filter[_FilterParameters]:
|
|
100
|
+
self._converter.filters.append(_NodeFilter(cast(ConverterFilter, predicate), meta=self._converter._with_identity(meta)))
|
|
101
|
+
return predicate
|
|
102
|
+
|
|
103
|
+
return register if function is None else register(function)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class MutationsCollection:
|
|
107
|
+
"""Register mutations and node-type filters for one pack of mutations."""
|
|
108
|
+
|
|
109
|
+
def __init__(self, prefix: str, *, meta: _Meta = None) -> None:
|
|
110
|
+
if not isinstance(prefix, str) or not fullmatch(r'[^\s,#]+', prefix):
|
|
111
|
+
raise ValueError('The mutation collection prefix must be a nonempty token without whitespace, commas or #.')
|
|
112
|
+
|
|
113
|
+
self._prefix = prefix
|
|
114
|
+
self._collector = Collector(meta=meta)
|
|
115
|
+
self._converters: Dict[int, _MutationConverter] = {}
|
|
116
|
+
self._next_number = 1
|
|
117
|
+
self._lock = Lock()
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def prefix(self) -> str:
|
|
121
|
+
return self._prefix
|
|
122
|
+
|
|
123
|
+
@overload # pragma: no cover
|
|
124
|
+
def mutation(
|
|
125
|
+
self, number: Callable[_Parameters, _Replacement], *, meta: _Meta = None,
|
|
126
|
+
) -> Mutation[_Parameters, _Replacement]: ...
|
|
127
|
+
|
|
128
|
+
@overload # pragma: no cover
|
|
129
|
+
def mutation(
|
|
130
|
+
self, number: Optional[int] = None, *, meta: _Meta = None,
|
|
131
|
+
) -> Callable[[Callable[_Parameters, _Replacement]], Mutation[_Parameters, _Replacement]]: ...
|
|
132
|
+
|
|
133
|
+
def mutation(
|
|
134
|
+
self,
|
|
135
|
+
number: Union[int, Callable[_Parameters, _Replacement], None] = None,
|
|
136
|
+
*,
|
|
137
|
+
meta: _Meta = None,
|
|
138
|
+
) -> Union[
|
|
139
|
+
Mutation[_Parameters, _Replacement],
|
|
140
|
+
Callable[[Callable[_Parameters, _Replacement]], Mutation[_Parameters, _Replacement]],
|
|
141
|
+
]:
|
|
142
|
+
"""Register a mutation with an explicit number or the next free number."""
|
|
143
|
+
if callable(number):
|
|
144
|
+
return self._register_mutation(number, None, meta)
|
|
145
|
+
if number is not None and (type(number) is not int or number < 1):
|
|
146
|
+
raise ValueError('Mutation numbers must be positive integers.')
|
|
147
|
+
|
|
148
|
+
def register(
|
|
149
|
+
function: Callable[_Parameters, _Replacement],
|
|
150
|
+
) -> Mutation[_Parameters, _Replacement]:
|
|
151
|
+
return self._register_mutation(function, number, meta)
|
|
152
|
+
|
|
153
|
+
return register
|
|
154
|
+
|
|
155
|
+
def _register_mutation(
|
|
156
|
+
self,
|
|
157
|
+
function: Callable[_Parameters, _Replacement],
|
|
158
|
+
number: Optional[int],
|
|
159
|
+
meta: _Meta,
|
|
160
|
+
) -> Mutation[_Parameters, _Replacement]:
|
|
161
|
+
with self._lock:
|
|
162
|
+
if number is None:
|
|
163
|
+
while self._next_number in self._converters:
|
|
164
|
+
self._next_number += 1
|
|
165
|
+
number = self._next_number
|
|
166
|
+
elif number in self._converters:
|
|
167
|
+
raise ValueError(f'Mutation {self.prefix}-{number} is already registered.')
|
|
168
|
+
|
|
169
|
+
converter = _MutationConverter(
|
|
170
|
+
f'{self.prefix}-{number}',
|
|
171
|
+
cast(ConverterFunction, function),
|
|
172
|
+
meta=cast(_Meta, self._collector._merge_meta(meta)),
|
|
173
|
+
)
|
|
174
|
+
mutation = Mutation(converter, function)
|
|
175
|
+
self._converters[number] = converter
|
|
176
|
+
return mutation
|
|
177
|
+
|
|
178
|
+
@overload # pragma: no cover
|
|
179
|
+
def filter(self, function: _Filter[_FilterParameters], meta: _Meta = None) -> _Filter[_FilterParameters]: ...
|
|
180
|
+
|
|
181
|
+
@overload # pragma: no cover
|
|
182
|
+
def filter(
|
|
183
|
+
self, function: None = None, meta: _Meta = None,
|
|
184
|
+
) -> Callable[[_Filter[_FilterParameters]], _Filter[_FilterParameters]]: ...
|
|
185
|
+
|
|
186
|
+
def filter(
|
|
187
|
+
self,
|
|
188
|
+
function: Optional[_Filter[_FilterParameters]] = None,
|
|
189
|
+
meta: _Meta = None,
|
|
190
|
+
) -> Union[_Filter[_FilterParameters], Callable[[_Filter[_FilterParameters]], _Filter[_FilterParameters]]]:
|
|
191
|
+
"""Register a cstvis node-type filter for this collection."""
|
|
192
|
+
|
|
193
|
+
def register(predicate: _Filter[_FilterParameters]) -> _Filter[_FilterParameters]:
|
|
194
|
+
with self._lock:
|
|
195
|
+
self._collector.filter(cast(ConverterFilter, predicate), meta=meta)
|
|
196
|
+
return predicate
|
|
197
|
+
|
|
198
|
+
return register if function is None else register(function)
|
|
199
|
+
|
|
200
|
+
def collector(self, *, ignored: Iterable[str] = ()) -> Collector:
|
|
201
|
+
"""Build a snapshot of this pack for a cstvis Changer."""
|
|
202
|
+
return self._snapshot(ignored_ids(ignored), CommentIgnores(DEFAULT_METACODE_KEY))
|
|
203
|
+
|
|
204
|
+
def _snapshot(self, project_ignores: FrozenSet[str], comment_ignores: CommentIgnores) -> Collector:
|
|
205
|
+
with self._lock:
|
|
206
|
+
collector = self._collector + Collector()
|
|
207
|
+
for mutation in self._converters.values():
|
|
208
|
+
converter = copy(mutation)
|
|
209
|
+
default_filter = make_ignore_filter(mutation.mutation_id, self.prefix, project_ignores, comment_ignores)
|
|
210
|
+
converter.filters = [default_filter, *mutation.filters]
|
|
211
|
+
# Collector.converter creates its own Converter with a function-based ID.
|
|
212
|
+
collector._converters.append(converter)
|
|
213
|
+
return collector
|
mutagroup/ignores.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from ast import BinOp, Constant, Name, Sub
|
|
2
|
+
from io import StringIO
|
|
3
|
+
from tokenize import COMMENT, TokenError, generate_tokens
|
|
4
|
+
from typing import Dict, FrozenSet, Iterable, Iterator, Optional, cast
|
|
5
|
+
|
|
6
|
+
from cstvis import Context
|
|
7
|
+
from cstvis.wrapper import CallableWrapper
|
|
8
|
+
from libcst import CSTNode, ParserSyntaxError
|
|
9
|
+
from metacode import UnknownArgumentTypeError, parse
|
|
10
|
+
|
|
11
|
+
DEFAULT_METACODE_KEY = 'muta'
|
|
12
|
+
_NO_IGNORES: FrozenSet[str] = frozenset()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _identifier(argument: object) -> Optional[str]:
|
|
16
|
+
if isinstance(argument, str):
|
|
17
|
+
return argument
|
|
18
|
+
if isinstance(argument, Name):
|
|
19
|
+
return argument.id
|
|
20
|
+
if isinstance(argument, BinOp) and isinstance(argument.op, Sub):
|
|
21
|
+
prefix = _identifier(argument.left)
|
|
22
|
+
suffix = argument.right
|
|
23
|
+
if prefix is not None and isinstance(suffix, Name):
|
|
24
|
+
return f'{prefix}-{suffix.id}'
|
|
25
|
+
if prefix is not None and isinstance(suffix, Constant): # type: ignore[misc]
|
|
26
|
+
number = cast(object, suffix.value)
|
|
27
|
+
if type(number) is int:
|
|
28
|
+
return f'{prefix}-{number}'
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _comment_parts(comment: str) -> Iterator[str]:
|
|
33
|
+
while comment:
|
|
34
|
+
tokens = generate_tokens(StringIO(comment).readline)
|
|
35
|
+
try:
|
|
36
|
+
boundary = next((token.start[1] for token in tokens if token.type == COMMENT), len(comment))
|
|
37
|
+
except TokenError:
|
|
38
|
+
boundary = len(comment)
|
|
39
|
+
yield comment[:boundary]
|
|
40
|
+
comment = comment[boundary + 1:]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _legacy_ids(comment: str, key: str) -> Iterator[str]:
|
|
44
|
+
if key not in comment or 'ignore' not in comment:
|
|
45
|
+
return
|
|
46
|
+
for part in _comment_parts(comment):
|
|
47
|
+
words = part.split(maxsplit=2)
|
|
48
|
+
if len(words) == 3 and words[:2] == [key, 'ignore']:
|
|
49
|
+
yield from words[2].replace(',', ' ').split()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class CommentIgnores:
|
|
53
|
+
"""Reuse parsed ignore directives for every mutation on a comment's line."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, key: str) -> None:
|
|
56
|
+
self._key = key
|
|
57
|
+
self._parsed: Dict[str, FrozenSet[str]] = {}
|
|
58
|
+
|
|
59
|
+
def for_context(self, context: Context) -> FrozenSet[str]:
|
|
60
|
+
comment = context.comment
|
|
61
|
+
if comment is None:
|
|
62
|
+
return _NO_IGNORES
|
|
63
|
+
if comment not in self._parsed:
|
|
64
|
+
self._parsed[comment] = self._read(context, comment)
|
|
65
|
+
return self._parsed[comment]
|
|
66
|
+
|
|
67
|
+
def _read(self, context: Context, comment: str) -> FrozenSet[str]:
|
|
68
|
+
try:
|
|
69
|
+
try:
|
|
70
|
+
directives = context.get_metacodes(self._key)
|
|
71
|
+
except UnknownArgumentTypeError:
|
|
72
|
+
# metacode 0.0.7 represents an unquoted ID such as I-13 as a subtraction AST.
|
|
73
|
+
directives = parse(comment, self._key, allow_ast=True)
|
|
74
|
+
except (AttributeError, ParserSyntaxError):
|
|
75
|
+
# A qualified annotation such as type: typing.List[int] can break the parser.
|
|
76
|
+
directives = []
|
|
77
|
+
for part in _comment_parts(comment):
|
|
78
|
+
try:
|
|
79
|
+
directives.extend(parse(part, self._key, allow_ast=True))
|
|
80
|
+
except (AttributeError, ParserSyntaxError):
|
|
81
|
+
continue
|
|
82
|
+
|
|
83
|
+
if not directives:
|
|
84
|
+
return frozenset(_legacy_ids(comment, self._key))
|
|
85
|
+
|
|
86
|
+
return frozenset(
|
|
87
|
+
code
|
|
88
|
+
for directive in directives if directive.command == 'ignore'
|
|
89
|
+
for argument in cast(Iterable[object], directive.arguments)
|
|
90
|
+
if (code := _identifier(argument)) is not None
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def ignored_ids(ignored: Iterable[str]) -> FrozenSet[str]:
|
|
95
|
+
return frozenset((ignored,)) if isinstance(ignored, str) else frozenset(ignored)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def make_ignore_filter(
|
|
99
|
+
mutation_id: str,
|
|
100
|
+
prefix: str,
|
|
101
|
+
project_ignores: FrozenSet[str],
|
|
102
|
+
comment_ignores: CommentIgnores,
|
|
103
|
+
) -> CallableWrapper[bool]:
|
|
104
|
+
ignored_in_project = mutation_id in project_ignores
|
|
105
|
+
|
|
106
|
+
def allows(_node: CSTNode, context: Context) -> bool:
|
|
107
|
+
if ignored_in_project:
|
|
108
|
+
return False
|
|
109
|
+
ignored = comment_ignores.for_context(context)
|
|
110
|
+
return mutation_id not in ignored and prefix not in ignored
|
|
111
|
+
|
|
112
|
+
return CallableWrapper(allows)
|
mutagroup/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
from collections import defaultdict
|
|
2
|
+
from dataclasses import replace
|
|
3
|
+
from functools import cached_property
|
|
4
|
+
from keyword import iskeyword
|
|
5
|
+
from typing import Dict, Generator, Iterable, List, NamedTuple, Optional, Type
|
|
6
|
+
|
|
7
|
+
from cstvis import Changer, Collector, Converter, Coordinate
|
|
8
|
+
from cstvis.converter import resolve_converters
|
|
9
|
+
from cstvis.source_offsets import SourceOffsetResolver
|
|
10
|
+
from cstvis.visitors.bloodhound import Bloodhound
|
|
11
|
+
from cstvis.visitors.comments_aggregator import CommentsAggregator
|
|
12
|
+
from cstvis.wrapper import CallableWrapper
|
|
13
|
+
from libcst import Comment, CSTNode
|
|
14
|
+
from libcst.metadata import PositionProvider
|
|
15
|
+
|
|
16
|
+
from mutagroup.collection import MutationsCollection
|
|
17
|
+
from mutagroup.ignores import DEFAULT_METACODE_KEY, CommentIgnores, ignored_ids
|
|
18
|
+
|
|
19
|
+
_FilterIndex = Dict[Type[CSTNode], List[CallableWrapper[bool]]]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _matching_filters(index: _FilterIndex, node_type: Type[CSTNode]) -> List[CallableWrapper[bool]]:
|
|
23
|
+
matches = index.get(node_type, []) + index.get(CSTNode, []) # type: ignore[type-abstract]
|
|
24
|
+
return list(dict.fromkeys(matches, True))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _PackFilters(NamedTuple):
|
|
28
|
+
prefix: str
|
|
29
|
+
by_type: _FilterIndex
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _Candidate(NamedTuple):
|
|
33
|
+
converter: Converter
|
|
34
|
+
mutation_id: str
|
|
35
|
+
prefix: Optional[str]
|
|
36
|
+
pack_filters: List[CallableWrapper[bool]]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _ScopedDiscovery(Bloodhound):
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
converters: Dict[Type[CSTNode], List[Converter]],
|
|
43
|
+
comments: Dict[int, str],
|
|
44
|
+
source_offsets: SourceOffsetResolver,
|
|
45
|
+
pack_by_converter: Dict[Converter, _PackFilters],
|
|
46
|
+
filters: _FilterIndex,
|
|
47
|
+
) -> None:
|
|
48
|
+
super().__init__(converters, comments, filters, source_offsets)
|
|
49
|
+
self._pack_by_converter = pack_by_converter
|
|
50
|
+
self._candidates_by_type: Dict[Type[CSTNode], List[_Candidate]] = {}
|
|
51
|
+
|
|
52
|
+
def _candidates(self, node_type: Type[CSTNode]) -> List[_Candidate]:
|
|
53
|
+
candidates = self._candidates_by_type.get(node_type)
|
|
54
|
+
if candidates is None:
|
|
55
|
+
candidates = []
|
|
56
|
+
for converter, mutation_id in resolve_converters(self.nodes_mapping, node_type).items():
|
|
57
|
+
pack = self._pack_by_converter.get(converter)
|
|
58
|
+
if pack is None:
|
|
59
|
+
candidates.append(_Candidate(converter, mutation_id, None, []))
|
|
60
|
+
else:
|
|
61
|
+
candidates.append(_Candidate(converter, mutation_id, pack.prefix, _matching_filters(pack.by_type, node_type)))
|
|
62
|
+
self._candidates_by_type[node_type] = candidates
|
|
63
|
+
return candidates
|
|
64
|
+
|
|
65
|
+
def on_visit(self, node: CSTNode) -> bool:
|
|
66
|
+
candidates = self._candidates(type(node))
|
|
67
|
+
if not candidates:
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
position = self.get_metadata(PositionProvider, node)
|
|
71
|
+
coordinate = Coordinate(
|
|
72
|
+
file=None,
|
|
73
|
+
class_name=type(node).__name__,
|
|
74
|
+
start_line=position.start.line,
|
|
75
|
+
start_column=position.start.column,
|
|
76
|
+
end_line=position.end.line,
|
|
77
|
+
end_column=position.end.column,
|
|
78
|
+
)
|
|
79
|
+
context = self._build_context(node, coordinate)
|
|
80
|
+
if self.filters and not all(predicate.call_with_context(node, context) for predicate in _matching_filters(self.filters, type(node))):
|
|
81
|
+
return True
|
|
82
|
+
|
|
83
|
+
accepted_packs: Dict[Optional[str], bool] = {}
|
|
84
|
+
for candidate in candidates:
|
|
85
|
+
if candidate.prefix not in accepted_packs:
|
|
86
|
+
accepted_packs[candidate.prefix] = all(predicate.call_with_context(node, context) for predicate in candidate.pack_filters)
|
|
87
|
+
if accepted_packs[candidate.prefix] and all(predicate.call_with_context(node, context) for predicate in candidate.converter.filters):
|
|
88
|
+
self.coordinates.append(replace(coordinate, converter_id=candidate.mutation_id))
|
|
89
|
+
return True
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class _ScopedChanger(Changer):
|
|
93
|
+
def __init__(self, source: str, collector: Collector, pack_by_converter: Dict[Converter, _PackFilters]) -> None:
|
|
94
|
+
super().__init__(source, collector=collector)
|
|
95
|
+
self._pack_by_converter = pack_by_converter
|
|
96
|
+
|
|
97
|
+
@cached_property
|
|
98
|
+
def _comments_by_lines(self) -> Dict[int, str]:
|
|
99
|
+
wrapper, _ = self._traversal
|
|
100
|
+
aggregator = CommentsAggregator()
|
|
101
|
+
# The position index already contains the comment nodes in this module.
|
|
102
|
+
with aggregator.resolve(wrapper):
|
|
103
|
+
for node in wrapper.resolve(PositionProvider):
|
|
104
|
+
if isinstance(node, Comment):
|
|
105
|
+
aggregator.on_visit(node)
|
|
106
|
+
return aggregator.comments
|
|
107
|
+
|
|
108
|
+
def iterate_coordinates(self) -> Generator[Coordinate, None, None]:
|
|
109
|
+
wrapper, source_offsets = self._traversal
|
|
110
|
+
discovery = _ScopedDiscovery(
|
|
111
|
+
self.converters_by_types,
|
|
112
|
+
self._comments_by_lines,
|
|
113
|
+
source_offsets,
|
|
114
|
+
self._pack_by_converter,
|
|
115
|
+
self.filters_by_types,
|
|
116
|
+
)
|
|
117
|
+
wrapper.visit(discovery)
|
|
118
|
+
yield from discovery.coordinates
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class MutationsSuperCollection:
|
|
122
|
+
"""Prepare one cstvis Changer per source for a set of mutation packs."""
|
|
123
|
+
|
|
124
|
+
def __init__(self, collections: Iterable[MutationsCollection], *, metacode_key: str = DEFAULT_METACODE_KEY) -> None:
|
|
125
|
+
if not metacode_key.isidentifier() or iskeyword(metacode_key):
|
|
126
|
+
raise ValueError('The metacode key must be a valid Python identifier.')
|
|
127
|
+
|
|
128
|
+
by_prefix: Dict[str, MutationsCollection] = {}
|
|
129
|
+
for collection in collections:
|
|
130
|
+
if collection.prefix in by_prefix:
|
|
131
|
+
raise ValueError(f'Mutation collection prefix {collection.prefix!r} is already present.')
|
|
132
|
+
by_prefix[collection.prefix] = collection
|
|
133
|
+
self._collections = tuple(by_prefix.values())
|
|
134
|
+
self._metacode_key = metacode_key
|
|
135
|
+
|
|
136
|
+
def get_changer(self, source: str, *, ignored: Iterable[str] = ()) -> Changer:
|
|
137
|
+
"""Snapshot the packs and discover their coordinates together in this source."""
|
|
138
|
+
project_ignores = ignored_ids(ignored)
|
|
139
|
+
comment_ignores = CommentIgnores(self._metacode_key)
|
|
140
|
+
collector = Collector()
|
|
141
|
+
pack_by_converter: Dict[Converter, _PackFilters] = {}
|
|
142
|
+
for collection in self._collections:
|
|
143
|
+
pack = collection._snapshot(project_ignores, comment_ignores)
|
|
144
|
+
collector._converters.extend(pack._converters)
|
|
145
|
+
filters: _FilterIndex = defaultdict(list)
|
|
146
|
+
for predicate in pack._filters:
|
|
147
|
+
for node_type in predicate.first_node_annotations:
|
|
148
|
+
filters[node_type].append(predicate)
|
|
149
|
+
scope = _PackFilters(collection.prefix, filters)
|
|
150
|
+
pack_by_converter.update(dict.fromkeys(pack._converters, scope))
|
|
151
|
+
return _ScopedChanger(source, collector, pack_by_converter)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# PolyForm Noncommercial License 1.0.0
|
|
2
|
+
|
|
3
|
+
<https://polyformproject.org/licenses/noncommercial/1.0.0>
|
|
4
|
+
|
|
5
|
+
## Acceptance
|
|
6
|
+
|
|
7
|
+
In order to get any license under these terms, you must agree
|
|
8
|
+
to them as both strict obligations and conditions to all
|
|
9
|
+
your licenses.
|
|
10
|
+
|
|
11
|
+
## Copyright License
|
|
12
|
+
|
|
13
|
+
The licensor grants you a copyright license for the
|
|
14
|
+
software to do everything you might do with the software
|
|
15
|
+
that would otherwise infringe the licensor's copyright
|
|
16
|
+
in it for any permitted purpose. However, you may
|
|
17
|
+
only distribute the software according to [Distribution
|
|
18
|
+
License](#distribution-license) and make changes or new works
|
|
19
|
+
based on the software according to [Changes and New Works
|
|
20
|
+
License](#changes-and-new-works-license).
|
|
21
|
+
|
|
22
|
+
## Distribution License
|
|
23
|
+
|
|
24
|
+
The licensor grants you an additional copyright license
|
|
25
|
+
to distribute copies of the software. Your license
|
|
26
|
+
to distribute covers distributing the software with
|
|
27
|
+
changes and new works permitted by [Changes and New Works
|
|
28
|
+
License](#changes-and-new-works-license).
|
|
29
|
+
|
|
30
|
+
## Notices
|
|
31
|
+
|
|
32
|
+
You must ensure that anyone who gets a copy of any part of
|
|
33
|
+
the software from you also gets a copy of these terms or the
|
|
34
|
+
URL for them above, as well as copies of any plain-text lines
|
|
35
|
+
beginning with `Required Notice:` that the licensor provided
|
|
36
|
+
with the software. For example:
|
|
37
|
+
|
|
38
|
+
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
|
39
|
+
|
|
40
|
+
## Changes and New Works License
|
|
41
|
+
|
|
42
|
+
The licensor grants you an additional copyright license to
|
|
43
|
+
make changes and new works based on the software for any
|
|
44
|
+
permitted purpose.
|
|
45
|
+
|
|
46
|
+
## Patent License
|
|
47
|
+
|
|
48
|
+
The licensor grants you a patent license for the software that
|
|
49
|
+
covers patent claims the licensor can license, or becomes able
|
|
50
|
+
to license, that you would infringe by using the software.
|
|
51
|
+
|
|
52
|
+
## Noncommercial Purposes
|
|
53
|
+
|
|
54
|
+
Any noncommercial purpose is a permitted purpose.
|
|
55
|
+
|
|
56
|
+
## Personal Uses
|
|
57
|
+
|
|
58
|
+
Personal use for research, experiment, and testing for
|
|
59
|
+
the benefit of public knowledge, personal study, private
|
|
60
|
+
entertainment, hobby projects, amateur pursuits, or religious
|
|
61
|
+
observance, without any anticipated commercial application,
|
|
62
|
+
is use for a permitted purpose.
|
|
63
|
+
|
|
64
|
+
## Noncommercial Organizations
|
|
65
|
+
|
|
66
|
+
Use by any charitable organization, educational institution,
|
|
67
|
+
public research organization, public safety or health
|
|
68
|
+
organization, environmental protection organization,
|
|
69
|
+
or government institution is use for a permitted purpose
|
|
70
|
+
regardless of the source of funding or obligations resulting
|
|
71
|
+
from the funding.
|
|
72
|
+
|
|
73
|
+
## Fair Use
|
|
74
|
+
|
|
75
|
+
You may have "fair use" rights for the software under the
|
|
76
|
+
law. These terms do not limit them.
|
|
77
|
+
|
|
78
|
+
## No Other Rights
|
|
79
|
+
|
|
80
|
+
These terms do not allow you to sublicense or transfer any of
|
|
81
|
+
your licenses to anyone else, or prevent the licensor from
|
|
82
|
+
granting licenses to anyone else. These terms do not imply
|
|
83
|
+
any other licenses.
|
|
84
|
+
|
|
85
|
+
## Patent Defense
|
|
86
|
+
|
|
87
|
+
If you make any written claim that the software infringes or
|
|
88
|
+
contributes to infringement of any patent, your patent license
|
|
89
|
+
for the software granted under these terms ends immediately. If
|
|
90
|
+
your company makes such a claim, your patent license ends
|
|
91
|
+
immediately for work on behalf of your company.
|
|
92
|
+
|
|
93
|
+
## Violations
|
|
94
|
+
|
|
95
|
+
The first time you are notified in writing that you have
|
|
96
|
+
violated any of these terms, or done anything with the software
|
|
97
|
+
not covered by your licenses, your licenses can nonetheless
|
|
98
|
+
continue if you come into full compliance with these terms,
|
|
99
|
+
and take practical steps to correct past violations, within
|
|
100
|
+
32 days of receiving notice. Otherwise, all your licenses
|
|
101
|
+
end immediately.
|
|
102
|
+
|
|
103
|
+
## No Liability
|
|
104
|
+
|
|
105
|
+
***As far as the law allows, the software comes as is, without
|
|
106
|
+
any warranty or condition, and the licensor will not be liable
|
|
107
|
+
to you for any damages arising out of these terms or the use
|
|
108
|
+
or nature of the software, under any kind of legal claim.***
|
|
109
|
+
|
|
110
|
+
## Definitions
|
|
111
|
+
|
|
112
|
+
The **licensor** is the individual or entity offering these
|
|
113
|
+
terms, and the **software** is the software the licensor makes
|
|
114
|
+
available under these terms.
|
|
115
|
+
|
|
116
|
+
**You** refers to the individual or entity agreeing to these
|
|
117
|
+
terms.
|
|
118
|
+
|
|
119
|
+
**Your company** is any legal entity, sole proprietorship,
|
|
120
|
+
or other kind of organization that you work for, plus all
|
|
121
|
+
organizations that have control over, are under the control of,
|
|
122
|
+
or are under common control with that organization. **Control**
|
|
123
|
+
means ownership of substantially all the assets of an entity,
|
|
124
|
+
or the power to direct its management and policies by vote,
|
|
125
|
+
contract, or otherwise. Control can be direct or indirect.
|
|
126
|
+
|
|
127
|
+
**Your licenses** are all the licenses granted to you for the
|
|
128
|
+
software under these terms.
|
|
129
|
+
|
|
130
|
+
**Use** means anything you do with the software requiring one
|
|
131
|
+
of your licenses.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: mutagroup
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Author-email: Evgeniy Blinov <zheni-b@yandex.ru>
|
|
5
|
+
Project-URL: Source, https://github.com/mutating/mutagroup
|
|
6
|
+
Project-URL: Tracker, https://github.com/mutating/mutagroup/issues
|
|
7
|
+
Keywords: CST,mutation testing
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
10
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
11
|
+
Classifier: Operating System :: POSIX
|
|
12
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
22
|
+
Classifier: Programming Language :: Python :: Free Threading
|
|
23
|
+
Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable
|
|
24
|
+
Classifier: License :: Free for non-commercial use
|
|
25
|
+
Classifier: Intended Audience :: Developers
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.8
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Requires-Dist: cstvis>=0.0.12
|
|
32
|
+
Requires-Dist: typing-extensions>=4.6; python_version < "3.10"
|
|
33
|
+
|
|
34
|
+
# mutagroup
|
|
35
|
+
|
|
36
|
+
`mutagroup` defines mutation packs for a mutation-testing engine. A pack registers
|
|
37
|
+
LibCST mutations and filters and supplies a `cstvis.Collector` for discovery and
|
|
38
|
+
application of individual mutations. A supercollection runs multiple packs over
|
|
39
|
+
the same source in a single coordinate discovery pass.
|
|
40
|
+
|
|
41
|
+
## Define a pack
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from libcst import Add, Subtract
|
|
45
|
+
from mutagroup import Context, MutationsCollection
|
|
46
|
+
|
|
47
|
+
mutations = MutationsCollection('I')
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@mutations.mutation(13)
|
|
51
|
+
def change_add(node: Add) -> Subtract:
|
|
52
|
+
return Subtract(
|
|
53
|
+
whitespace_before=node.whitespace_before,
|
|
54
|
+
whitespace_after=node.whitespace_after,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@mutations.filter
|
|
59
|
+
def formatted_adds(node: Add) -> bool:
|
|
60
|
+
return not node.whitespace_before.empty
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@change_add.filter
|
|
64
|
+
def skip_generated(_node: Add, context: Context) -> bool:
|
|
65
|
+
return context.comment != ' generated'
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`change_add.id` is `I-13`. Use `@mutations.mutation` to take the lowest free
|
|
69
|
+
positive number at registration time. Explicit numbers keep public IDs stable
|
|
70
|
+
as a pack evolves. Registering a number twice in the same pack raises an error.
|
|
71
|
+
|
|
72
|
+
Mutations and both kinds of filters accept a node and an optional `Context`.
|
|
73
|
+
cstvis resolves the first parameter's annotation. Matching collection filters
|
|
74
|
+
run at most once per node, before bound filters. Bound filters apply to their
|
|
75
|
+
own mutation and matching node types. A false result suppresses the corresponding
|
|
76
|
+
coordinates.
|
|
77
|
+
|
|
78
|
+
When cstvis calls a mutation or one of its bound filters, `context.meta` includes
|
|
79
|
+
`mutation_id` and `mutation_name`. These are the registered ID and the mutation
|
|
80
|
+
handler's Python name. Custom metadata can use other keys.
|
|
81
|
+
|
|
82
|
+
## Run one or more packs
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from mutagroup import MutationsSuperCollection
|
|
86
|
+
|
|
87
|
+
packs = MutationsSuperCollection([mutations], metacode_key='muta')
|
|
88
|
+
source = 'a = 1 + 2 # muta: ignore[I-13]\nb = 3 + 4\n'
|
|
89
|
+
changer = packs.get_changer(source)
|
|
90
|
+
for coordinate in changer.iterate_coordinates():
|
|
91
|
+
print(coordinate.converter_id, changer.apply_coordinate(coordinate))
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Each `.get_changer(source)` call snapshots the registered mutations and filters.
|
|
95
|
+
`iterate_coordinates()` discovers candidates from all packs in source order,
|
|
96
|
+
with each pack's filters scoped to that pack. `apply_coordinate()` produces one
|
|
97
|
+
mutant of the original source. Pack prefixes must be unique within a
|
|
98
|
+
supercollection.
|
|
99
|
+
|
|
100
|
+
The default metacode key is `muta`. On the line where a node starts,
|
|
101
|
+
`# muta: ignore[I-13]` and `# muta: ignore["I-13"]` suppress that mutation.
|
|
102
|
+
`# muta: ignore[I]` suppresses mutations from pack `I`. A directive can list
|
|
103
|
+
multiple IDs, as in `# muta: ignore[I-13, J]`. The short `# muta ignore I-13`
|
|
104
|
+
form also works on its own.
|
|
105
|
+
|
|
106
|
+
Pass project-wide mutation IDs to `packs.get_changer(source, ignored=ids)`. For a
|
|
107
|
+
standalone pack, use `Changer(source, collector=mutations.collector(ignored=ids))`
|
|
108
|
+
from cstvis.
|
|
109
|
+
|
|
110
|
+
A plugin library can expose its `MutationsCollection` instance to the engine.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
mutagroup/__init__.py,sha256=s0eUyWva8d3JhTx4V5iwoCEgn7s5-pxFF8CcsWG-A68,250
|
|
2
|
+
mutagroup/collection.py,sha256=nZDLZtA-Fgegz4wf8Q_TQdgN0Ba4wtKhTq0t3toBvfA,8151
|
|
3
|
+
mutagroup/ignores.py,sha256=HLtiNXo91RIIsVWooTNDlHbuH57sQFcDUT2mBxeD_5k,4103
|
|
4
|
+
mutagroup/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
mutagroup/supercollection.py,sha256=1HXdIHjf_MW2P6tVM4NYD4JbKf_oCA-5KynG2M2XdBk,6690
|
|
6
|
+
mutagroup-0.0.1.dist-info/LICENSE,sha256=_8yjiEGttpS284BkfhXxfERqTRZW_tUaHiBB0GTJTMg,4563
|
|
7
|
+
mutagroup-0.0.1.dist-info/METADATA,sha256=PDTTjiaYJRU53PrhVzdntaQiXcSMlJc1Jr6ZpHrDaAk,4385
|
|
8
|
+
mutagroup-0.0.1.dist-info/WHEEL,sha256=EWGgdj_eH-g9dwsWZOTG0kmGucEuKPxGzOKD-jAVUHs,92
|
|
9
|
+
mutagroup-0.0.1.dist-info/top_level.txt,sha256=M-jDRxkwiOOzIBBjYRoK__0GUvzXHf06E1WwiwI9Xn8,10
|
|
10
|
+
mutagroup-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mutagroup
|