From 037673a849b35aa71d802da47bbcd16a80591790 Mon Sep 17 00:00:00 2001 From: Daniel Gollahon Date: Sat, 2 Jan 2021 10:55:04 -0800 Subject: [PATCH] Add named capture to non-capturing group mutation - Mutate named capture groups to passive groups: `/(?bar)/` -> `/(?:bar)/`. --- Changelog.md | 4 +++ lib/mutant.rb | 1 + lib/mutant/mutator/node/regexp/named_group.rb | 25 +++++++++++++++++++ meta/regexp.rb | 1 + meta/regexp/regexp_named_group.rb | 18 +++++++++++++ 5 files changed, 49 insertions(+) create mode 100644 lib/mutant/mutator/node/regexp/named_group.rb create mode 100644 meta/regexp/regexp_named_group.rb diff --git a/Changelog.md b/Changelog.md index 5c405f0e0..a7a7da443 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,9 @@ # Unreleased +* [#1194](https://github.com/mbj/mutant/pull/1194) + + * Add mutation from named capturing group to non-capturing group: `/(?bar)/` -> `/(?:bar)`. + * [#1189](https://github.com/mbj/mutant/pull/1189) * Add mutation from `=~` -> `#match?` diff --git a/lib/mutant.rb b/lib/mutant.rb index cf0a114e0..98e8a4432 100644 --- a/lib/mutant.rb +++ b/lib/mutant.rb @@ -89,6 +89,7 @@ module Mutant require 'mutant/mutator/node/regexp' require 'mutant/mutator/node/regexp/alternation_meta' require 'mutant/mutator/node/regexp/capture_group' +require 'mutant/mutator/node/regexp/named_group' require 'mutant/mutator/node/regexp/character_type' require 'mutant/mutator/node/regexp/end_of_line_anchor' require 'mutant/mutator/node/regexp/end_of_string_or_before_end_of_line_anchor' diff --git a/lib/mutant/mutator/node/regexp/named_group.rb b/lib/mutant/mutator/node/regexp/named_group.rb new file mode 100644 index 000000000..a06044683 --- /dev/null +++ b/lib/mutant/mutator/node/regexp/named_group.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +module Mutant + class Mutator + class Node + module Regexp + # Mutator for regexp named capture groups, such as `/(?bar)/` + class NamedGroup < Node + handle(:regexp_named_group) + + children :name, :group + + private + + def dispatch + return unless group + + emit(s(:regexp_passive_group, group)) + emit_group_mutations + end + end # EndOfLineAnchor + end # Regexp + end # Node + end # Mutator +end # Mutant diff --git a/meta/regexp.rb b/meta/regexp.rb index 31e8fcd7c..fbcaff7d3 100644 --- a/meta/regexp.rb +++ b/meta/regexp.rb @@ -93,6 +93,7 @@ singleton_mutations mutation '//' mutation '/nomatch\A/' + mutation '/(?:.)/' end Pathname diff --git a/meta/regexp/regexp_named_group.rb b/meta/regexp/regexp_named_group.rb new file mode 100644 index 000000000..1abe1bbb4 --- /dev/null +++ b/meta/regexp/regexp_named_group.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +Mutant::Meta::Example.add :regexp_named_group do + source '/(?)/' + + singleton_mutations + regexp_mutations +end + +Mutant::Meta::Example.add :regexp_named_group do + source '/(?\w)/' + + singleton_mutations + regexp_mutations + + mutation '/(?:\w)/' + mutation '/(?\W)/' +end