From 2e09662ff3c8b4b724d77be857815f24cb5c3e08 Mon Sep 17 00:00:00 2001 From: Daniel Gollahon Date: Sat, 2 Jan 2021 16:23:40 -0800 Subject: [PATCH] Add unused group name mutation - Mutates capture group names: `/(?bar)/` -> `/(?<_foo>bar)/`. - Closes #573. NOTE: I have deviated from the issue slightly and chosen a `_` prefix so that, like with local variables, names can be left in unused if they are explicitly marked as such. I have decided to extend the behavior to not mutating to a non-capture group as well in this case because the `_` prefix seems like a clear choice that the user would rather keep the label even if the capturing functionality is unused. --- Changelog.md | 5 +++++ lib/mutant/mutator/node/regexp/named_group.rb | 16 +++++++++++++++- meta/regexp/regexp_named_group.rb | 10 ++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Changelog.md b/Changelog.md index 48c8688e0..17e432321 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,8 @@ +# Unreleased + +* [#1200](https://github.com/mbj/mutant/pull/1200) + * Add unused group name mutation: `/(?bar)/` -> `/(?<_foo>bar)/`. + # v0.10.25 2021-01-02-03 * [#1194](https://github.com/mbj/mutant/pull/1194) diff --git a/lib/mutant/mutator/node/regexp/named_group.rb b/lib/mutant/mutator/node/regexp/named_group.rb index a06044683..179289af5 100644 --- a/lib/mutant/mutator/node/regexp/named_group.rb +++ b/lib/mutant/mutator/node/regexp/named_group.rb @@ -15,8 +15,22 @@ class NamedGroup < Node def dispatch return unless group - emit(s(:regexp_passive_group, group)) emit_group_mutations + + # Allows unused captures to be kept and named if they are explicitly prefixed with an + # underscore, like we allow with unused local variables. + return unless name_underscored? + + emit(s(:regexp_passive_group, group)) + emit_name_underscore_mutation + end + + def emit_name_underscore_mutation + emit_type("_#{name}", group) + end + + def name_underscored? + name.start_with?('_') end end # EndOfLineAnchor end # Regexp diff --git a/meta/regexp/regexp_named_group.rb b/meta/regexp/regexp_named_group.rb index 1abe1bbb4..dd515ef6b 100644 --- a/meta/regexp/regexp_named_group.rb +++ b/meta/regexp/regexp_named_group.rb @@ -15,4 +15,14 @@ mutation '/(?:\w)/' mutation '/(?\W)/' + mutation '/(?<_foo>\w)/' +end + +Mutant::Meta::Example.add :regexp_named_group do + source '/(?<_foo>\w)/' + + singleton_mutations + regexp_mutations + + mutation '/(?<_foo>\W)/' end