henitai 0.5.3 → 0.7.0

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.
Files changed (141) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +332 -1
  3. data/README.md +123 -19
  4. data/assets/schema/henitai.schema.json +26 -0
  5. data/lib/henitai/arid_node_filter.rb +4 -19
  6. data/lib/henitai/bootstrap_error_message.rb +38 -0
  7. data/lib/henitai/canonical_report_merger.rb +23 -2
  8. data/lib/henitai/checkpoint_reporter.rb +5 -0
  9. data/lib/henitai/cli/operator_command.rb +10 -3
  10. data/lib/henitai/cli/run_command.rb +25 -7
  11. data/lib/henitai/cli/run_options.rb +1 -1
  12. data/lib/henitai/cli.rb +6 -2
  13. data/lib/henitai/composite_progress_reporter.rb +15 -2
  14. data/lib/henitai/configuration.rb +9 -1
  15. data/lib/henitai/configuration_validator/rules.rb +9 -0
  16. data/lib/henitai/configuration_validator/scalars.rb +22 -0
  17. data/lib/henitai/configuration_validator.rb +4 -2
  18. data/lib/henitai/constant_path.rb +48 -0
  19. data/lib/henitai/control_gate.rb +78 -0
  20. data/lib/henitai/control_run.rb +67 -0
  21. data/lib/henitai/coverage_bootstrapper.rb +46 -11
  22. data/lib/henitai/coverage_formatter.rb +26 -3
  23. data/lib/henitai/coverage_report_reader.rb +21 -0
  24. data/lib/henitai/equivalence_detector/operand_predicates.rb +16 -0
  25. data/lib/henitai/equivalence_detector.rb +46 -38
  26. data/lib/henitai/example_summary.rb +24 -0
  27. data/lib/henitai/execution_engine/env_scope.rb +3 -3
  28. data/lib/henitai/execution_engine/fork_server_scope.rb +57 -0
  29. data/lib/henitai/execution_engine.rb +109 -119
  30. data/lib/henitai/execution_provenance.rb +67 -0
  31. data/lib/henitai/fidelity_check.rb +173 -0
  32. data/lib/henitai/flaky_detection_baseline.rb +63 -0
  33. data/lib/henitai/flaky_retry_decision.rb +23 -0
  34. data/lib/henitai/flaky_test_registry.rb +63 -0
  35. data/lib/henitai/fork_server/client.rb +222 -0
  36. data/lib/henitai/fork_server/group_killer.rb +48 -0
  37. data/lib/henitai/fork_server/launcher.rb +38 -0
  38. data/lib/henitai/fork_server/mutant_runner.rb +110 -0
  39. data/lib/henitai/fork_server/protocol.rb +73 -0
  40. data/lib/henitai/fork_server/reaper.rb +24 -0
  41. data/lib/henitai/fork_server/runtime.rb +109 -0
  42. data/lib/henitai/fork_server/server.rb +108 -0
  43. data/lib/henitai/fork_server/server_process.rb +73 -0
  44. data/lib/henitai/fork_server/status.rb +52 -0
  45. data/lib/henitai/fork_server.rb +42 -0
  46. data/lib/henitai/generated_artifacts.rb +3 -0
  47. data/lib/henitai/git_diff_analyzer.rb +28 -11
  48. data/lib/henitai/history_checkpointer.rb +72 -0
  49. data/lib/henitai/incremental_filter.rb +20 -10
  50. data/lib/henitai/integration/base.rb +78 -19
  51. data/lib/henitai/integration/capped_log_sink.rb +34 -0
  52. data/lib/henitai/integration/child_bootstrap.rb +7 -0
  53. data/lib/henitai/integration/child_report_store.rb +65 -0
  54. data/lib/henitai/integration/minitest.rb +8 -13
  55. data/lib/henitai/integration/minitest_autorun.rb +20 -0
  56. data/lib/henitai/integration/minitest_fail_fast.rb +43 -0
  57. data/lib/henitai/integration/minitest_outcome_reporter.rb +44 -0
  58. data/lib/henitai/integration/minitest_preload.rb +30 -0
  59. data/lib/henitai/integration/minitest_runnable_filter.rb +61 -0
  60. data/lib/henitai/integration/minitest_test_runner.rb +47 -18
  61. data/lib/henitai/integration/mutant_run_support.rb +80 -17
  62. data/lib/henitai/integration/rspec_child_runner.rb +49 -9
  63. data/lib/henitai/integration/rspec_file_order.rb +37 -0
  64. data/lib/henitai/integration/rspec_preload.rb +35 -0
  65. data/lib/henitai/integration/rspec_process_runner.rb +4 -20
  66. data/lib/henitai/integration/scenario_log_support.rb +31 -18
  67. data/lib/henitai/integration.rb +18 -6
  68. data/lib/henitai/kill_history/store.rb +67 -0
  69. data/lib/henitai/kill_history.rb +85 -0
  70. data/lib/henitai/minitest_coverage_reporter.rb +22 -6
  71. data/lib/henitai/minitest_result_file.rb +62 -0
  72. data/lib/henitai/mutant/activation.rb +32 -0
  73. data/lib/henitai/mutant/activator.rb +75 -55
  74. data/lib/henitai/mutant/def_injection.rb +136 -0
  75. data/lib/henitai/mutant/lexical_scope_check.rb +120 -0
  76. data/lib/henitai/mutant/lexical_target.rb +105 -0
  77. data/lib/henitai/mutant/replacement.rb +52 -0
  78. data/lib/henitai/mutant.rb +32 -8
  79. data/lib/henitai/mutant_generator.rb +62 -18
  80. data/lib/henitai/mutant_history_store/database.rb +61 -0
  81. data/lib/henitai/mutant_history_store/sql.rb +9 -3
  82. data/lib/henitai/mutant_history_store/subject_scans.rb +101 -0
  83. data/lib/henitai/mutant_history_store/verdict_cache.rb +48 -18
  84. data/lib/henitai/mutant_history_store.rb +77 -51
  85. data/lib/henitai/mutant_identity.rb +5 -1
  86. data/lib/henitai/mutant_verdict.rb +71 -0
  87. data/lib/henitai/operator.rb +6 -2
  88. data/lib/henitai/operators/array_declaration.rb +4 -0
  89. data/lib/henitai/operators/assignment_expression.rb +2 -0
  90. data/lib/henitai/operators/conditional_expression.rb +21 -1
  91. data/lib/henitai/operators/equality_identity_operator.rb +2 -2
  92. data/lib/henitai/operators/hash_key_type.rb +11 -1
  93. data/lib/henitai/operators/hash_literal.rb +37 -9
  94. data/lib/henitai/operators/method_expression.rb +14 -3
  95. data/lib/henitai/operators/regex_metacharacters.rb +89 -0
  96. data/lib/henitai/operators/regex_mutator.rb +23 -28
  97. data/lib/henitai/operators/return_value.rb +1 -1
  98. data/lib/henitai/operators/string_literal.rb +17 -4
  99. data/lib/henitai/operators.rb +1 -0
  100. data/lib/henitai/per_test_coverage.rb +11 -7
  101. data/lib/henitai/per_test_coverage_collector.rb +30 -31
  102. data/lib/henitai/per_test_coverage_delta.rb +60 -0
  103. data/lib/henitai/per_test_coverage_selector.rb +26 -13
  104. data/lib/henitai/process_wakeup.rb +8 -3
  105. data/lib/henitai/process_worker_runner.rb +41 -7
  106. data/lib/henitai/reporter.rb +15 -8
  107. data/lib/henitai/result.rb +32 -16
  108. data/lib/henitai/reuse_context.rb +52 -0
  109. data/lib/henitai/rspec_coverage_formatter.rb +4 -0
  110. data/lib/henitai/rspec_outcomes.rb +74 -0
  111. data/lib/henitai/runner.rb +112 -21
  112. data/lib/henitai/runner_dependencies.rb +44 -3
  113. data/lib/henitai/sampling_strategy.rb +36 -6
  114. data/lib/henitai/scenario_execution_result.rb +51 -5
  115. data/lib/henitai/signal_deferral.rb +25 -0
  116. data/lib/henitai/signature_line.rb +21 -0
  117. data/lib/henitai/slot_scheduler/control_slots.rb +58 -0
  118. data/lib/henitai/slot_scheduler/draining.rb +35 -6
  119. data/lib/henitai/slot_scheduler/process_control.rb +33 -0
  120. data/lib/henitai/slot_scheduler/retry_policy.rb +20 -6
  121. data/lib/henitai/slot_scheduler.rb +64 -21
  122. data/lib/henitai/source_file_selection.rb +1 -1
  123. data/lib/henitai/source_parser.rb +29 -9
  124. data/lib/henitai/static_filter.rb +45 -14
  125. data/lib/henitai/stillborn_filter.rb +70 -2
  126. data/lib/henitai/subject.rb +8 -3
  127. data/lib/henitai/subject_resolver.rb +65 -31
  128. data/lib/henitai/suite_boot_clock.rb +48 -0
  129. data/lib/henitai/survivor_activation_cache.rb +18 -11
  130. data/lib/henitai/survivor_rerun_strategy.rb +47 -43
  131. data/lib/henitai/test_file_outcomes.rb +93 -0
  132. data/lib/henitai/test_prioritizer.rb +10 -2
  133. data/lib/henitai/timeout_calibrator.rb +31 -9
  134. data/lib/henitai/timeout_ceiling.rb +37 -0
  135. data/lib/henitai/verdict_fingerprint.rb +29 -30
  136. data/lib/henitai/version.rb +1 -1
  137. data/lib/henitai.rb +21 -1
  138. data/sig/configuration_validator.rbs +1 -0
  139. data/sig/henitai.rbs +254 -56
  140. metadata +63 -5
  141. data/lib/henitai/survivor_test_filter.rb +0 -72
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ # Classifies one mutant run from the child's own report and the way the
5
+ # child process ended.
6
+ #
7
+ # The child reports what it got to: a failed activation, a finished test run
8
+ # with the exit code the tests returned, or a SystemExit raised while the
9
+ # tests ran. Only a finished test run yields a test verdict (Killed or
10
+ # Survived); everything else is a harness or runtime status that stays out of
11
+ # the detected count. In particular a child that died without a report, or
12
+ # was killed by a signal, is a RuntimeError, never a kill.
13
+ class MutantVerdict
14
+ def initialize(wait_result:, report:, stdout:, stderr:)
15
+ @wait_result = wait_result
16
+ @report = report
17
+ @output = "#{stdout}\n#{stderr}"
18
+ end
19
+
20
+ # @return [Array(Symbol, String|nil)] status and reason
21
+ def to_a
22
+ return [:timeout, nil] if @wait_result == :timeout
23
+ return [:runtime_error, "child terminated by signal #{signal_name}"] if signaled?
24
+ return [:runtime_error, "child exited with status #{exit_status} without reporting a result"] unless @report
25
+
26
+ reported_verdict
27
+ end
28
+
29
+ # @return [Array<String>] expanded paths of the test files that failed
30
+ # in the child, or an empty list when the child did not report them or
31
+ # also saw a failure it could not attribute to a file (which makes the
32
+ # kill genuine, never one a flaky file alone may have caused)
33
+ def killing_tests
34
+ return [] if @report.nil? || @report["unattributed_failures"]
35
+
36
+ Array(@report["failed_tests"]).map { |path| File.expand_path(path) }
37
+ end
38
+
39
+ private
40
+
41
+ def reported_verdict
42
+ case @report["outcome"]
43
+ when "activation_failed" then [:compile_error, "activation failed: #{@report['reason']}"]
44
+ when "environment_failed"
45
+ [:compile_error, "the test files failed to load, before the mutant was activated"]
46
+ when "system_exit"
47
+ [:runtime_error, "the test run ended early with SystemExit (status #{@report['status']})"]
48
+ when "tests_finished" then test_verdict
49
+ else [:runtime_error, "child reported an unknown outcome: #{@report['outcome']}"]
50
+ end
51
+ end
52
+
53
+ def test_verdict
54
+ return [:compile_error, "no examples ran"] if ExampleSummary.none_ran?(@output)
55
+
56
+ @report["exit_code"].to_i.zero? ? [:survived, nil] : [:killed, nil]
57
+ end
58
+
59
+ def signaled?
60
+ @wait_result.respond_to?(:signaled?) && @wait_result.signaled?
61
+ end
62
+
63
+ def signal_name
64
+ "SIG#{Signal.signame(@wait_result.termsig)}"
65
+ end
66
+
67
+ def exit_status
68
+ @wait_result.respond_to?(:exitstatus) ? @wait_result.exitstatus : "unknown"
69
+ end
70
+ end
71
+ end
@@ -7,6 +7,8 @@ module Henitai
7
7
  # Operator names follow the Stryker-compatible naming convention so that the
8
8
  # JSON report is compatible with stryker-dashboard filters and HTML reports.
9
9
  #
10
+ # The sets nest: light ⊂ full ⊂ hard.
11
+ #
10
12
  # Built-in operators (light set):
11
13
  # ArithmeticOperator, EqualityOperator, LogicalOperator, BooleanLiteral,
12
14
  # ConditionalExpression, StringLiteral, ReturnValue
@@ -14,8 +16,10 @@ module Henitai
14
16
  # Additional operators (full set):
15
17
  # ArrayDeclaration, HashLiteral, RangeLiteral, SafeNavigation,
16
18
  # PatternMatch, BlockStatement, MethodExpression, AssignmentExpression,
17
- # UnaryOperator, UpdateOperator, RegexMutator, MethodChainUnwrap,
18
- # EqualityIdentityOperator
19
+ # UnaryOperator, UpdateOperator, RegexMutator, MethodChainUnwrap
20
+ #
21
+ # Usually-unkillable operators (hard set, ADR-12):
22
+ # EqualityIdentityOperator, HashKeyType
19
23
  #
20
24
  # Each operator subclass must implement:
21
25
  # - .node_types → Array<Symbol> AST node types this operator handles
@@ -12,7 +12,11 @@ module Henitai
12
12
  NODE_TYPES
13
13
  end
14
14
 
15
+ # A list without brackets (rescue classes, multiple return values,
16
+ # multiple assignment) is not an array literal and has no empty form.
15
17
  def mutate(node, subject:)
18
+ return [] unless node.location.begin
19
+
16
20
  if node.children.empty?
17
21
  [empty_array_mutant(subject:, node:)]
18
22
  else
@@ -51,6 +51,8 @@ module Henitai
51
51
  when :casgn
52
52
  namespace, name = left.children
53
53
  Parser::AST::Node.new(:casgn, [namespace, name, right])
54
+ when :indexasgn
55
+ left.updated(nil, [*left.children, right])
54
56
  when :send
55
57
  assignment_name = left.children[1] == :[] ? :[]= : :"#{left.children[1]}="
56
58
  receiver, _method_name, *arguments = left.children
@@ -28,6 +28,8 @@ module Henitai
28
28
  private
29
29
 
30
30
  def mutate_if(node, subject:)
31
+ return elsif_condition_mutants(node, subject:) if elsif?(node)
32
+
31
33
  condition, then_branch, else_branch = node.children
32
34
  mutations = condition_variants(node, subject:, condition:)
33
35
 
@@ -38,6 +40,22 @@ module Henitai
38
40
  mutations
39
41
  end
40
42
 
43
+ # An elsif's source range starts at `elsif` and has no `end`, so a
44
+ # re-rendered `if ... end` cannot take its place. Only its condition is
45
+ # mutated, in place; removing a branch is what "replaced condition with
46
+ # false" already does.
47
+ def elsif_condition_mutants(node, subject:)
48
+ condition = node.children.first
49
+ [[true_node, "replaced condition with true"], [false_node, "replaced condition with false"],
50
+ [negate(condition), "negated condition"]].map do |replacement, description|
51
+ build_mutant(subject:, original_node: condition, mutated_node: replacement, description:)
52
+ end
53
+ end
54
+
55
+ def elsif?(node)
56
+ node.location.respond_to?(:keyword) && node.location.keyword&.source == "elsif"
57
+ end
58
+
41
59
  def mutate_case(node, subject:)
42
60
  condition = node.children.first
43
61
  when_nodes, else_branch = case_children(node.children.drop(1))
@@ -154,8 +172,10 @@ module Henitai
154
172
  Parser::AST::Node.new(node.type, children)
155
173
  end
156
174
 
175
+ # The parentheses are part of the mutation: `!a > b` would negate only
176
+ # `a` and compare the boolean, which is not the reported mutant.
157
177
  def negate(node)
158
- Parser::AST::Node.new(:send, [node, :!])
178
+ Parser::AST::Node.new(:send, [Parser::AST::Node.new(:begin, [node]), :!])
159
179
  end
160
180
 
161
181
  # rubocop:disable Lint/BooleanSymbol
@@ -10,8 +10,8 @@ module Henitai
10
10
  # This is the noisy half of the equality/identity pairing split out of
11
11
  # EqualityOperator: most Ruby objects don't observably distinguish `==`
12
12
  # from `eql?`/`equal?`, so these mutations are frequently unkillable by
13
- # ordinary tests. They stay available in the full operator set rather
14
- # than the default light set.
13
+ # ordinary tests. As of ADR-12 they live in the hard set — available on
14
+ # request, but out of both `light` and `full`.
15
15
  class EqualityIdentityOperator < Henitai::Operator
16
16
  NODE_TYPES = [:send].freeze
17
17
  RELATIONAL = %i[== != < > <= >= <=>].freeze
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../parser_current"
4
+
3
5
  module Henitai
4
6
  module Operators
5
7
  # Mutates symbol hash keys into string keys, one pair at a time
@@ -22,7 +24,7 @@ module Henitai
22
24
  subject:,
23
25
  original_node: node,
24
26
  mutated_node: mutated_hash(node, index),
25
- description: "replaced symbol key with string key"
27
+ description: "replaced symbol key #{key_label(pair, index)} with string key"
26
28
  )
27
29
  end
28
30
  end
@@ -33,6 +35,14 @@ module Henitai
33
35
  node.type == :pair && node.children.first&.type == :sym
34
36
  end
35
37
 
38
+ # Names the key so the mutants of one hash stay distinguishable. A
39
+ # symbol may contain a newline (`:"a\nb"`), which would break every
40
+ # single-line report surface, so such keys fall back to their position.
41
+ def key_label(pair, index)
42
+ label = pair.children.first.children.first.to_s
43
+ label.include?("\n") ? "##{index + 1}" : label
44
+ end
45
+
36
46
  def mutated_hash(node, index)
37
47
  pairs = node.children.each_with_index.map do |pair, pair_index|
38
48
  pair_index == index ? stringified_pair(pair) : pair
@@ -9,7 +9,18 @@ module Henitai
9
9
  # set) because framework key normalization makes it frequently unkillable
10
10
  # (ADR-12).
11
11
  class HashLiteral < Henitai::Operator
12
- NODE_TYPES = [:hash].freeze
12
+ # Keyword arguments (kwargs) are mutated like hash literals; the mutant
13
+ # keeps the node type, so a removed keyword never turns the remaining
14
+ # ones into a positional hash.
15
+ NODE_TYPES = %i[hash kwargs].freeze
16
+
17
+ # Key node types whose first child is the literal value itself.
18
+ SCALAR_KEY_TYPES = %i[sym int float].freeze
19
+ # Same, but rendered quoted so a string key stays distinguishable from
20
+ # the symbol key of the same name.
21
+ QUOTED_KEY_TYPES = [:str].freeze
22
+ # Keyword literals carry no children; the node type is the label.
23
+ KEYWORD_KEY_TYPES = %i[true false nil].freeze
13
24
 
14
25
  def self.node_types
15
26
  NODE_TYPES
@@ -29,8 +40,8 @@ module Henitai
29
40
  build_mutant(
30
41
  subject:,
31
42
  original_node: node,
32
- mutated_node: Parser::AST::Node.new(:hash, []),
33
- description: "replaced hash with empty hash"
43
+ mutated_node: node.updated(nil, []),
44
+ description: node.type == :kwargs ? "removed keyword arguments" : "replaced hash with empty hash"
34
45
  )
35
46
  end
36
47
 
@@ -45,20 +56,37 @@ module Henitai
45
56
  subject:,
46
57
  original_node: node,
47
58
  mutated_node: hash_without_pair(node, index),
48
- description: "removed hash pair #{pair_key_label(pair)}"
59
+ description: "removed hash pair #{pair_key_label(pair, index)}"
49
60
  )
50
61
  end
51
62
  end
52
63
 
53
64
  def hash_without_pair(node, pair_index)
54
65
  remaining = node.children.reject.with_index { |_pair, index| index == pair_index }
55
- Parser::AST::Node.new(:hash, remaining)
66
+ node.updated(nil, remaining)
56
67
  end
57
68
 
58
- # Pair keys are always AST nodes (sym/str/…); their first child is the
59
- # literal value used purely as a human-readable label.
60
- def pair_key_label(pair)
61
- pair.children.first.children.first
69
+ # Only literal keys have a meaningful name. Anything else — a variable,
70
+ # a method call, an array, a nested hash, an interpolated symbol — falls
71
+ # back to its position: rendering those nodes would put a raw
72
+ # s-expression (and, for a nested hash, embedded newlines) into every
73
+ # report surface and into MutantIdentity.stable_id.
74
+ def pair_key_label(pair, index)
75
+ label = literal_key_label(pair.children.first)
76
+ return "##{index + 1}" if label.nil? || label.include?("\n")
77
+
78
+ label
79
+ end
80
+
81
+ # A symbol can itself contain a newline (`:"a\nb"`), which would put the
82
+ # break straight back into every single-line surface — hence the
83
+ # newline check on the rendered label above, not just on the node type.
84
+ def literal_key_label(key)
85
+ case key.type
86
+ when *SCALAR_KEY_TYPES then key.children.first.to_s
87
+ when *QUOTED_KEY_TYPES then key.children.first.inspect
88
+ when *KEYWORD_KEY_TYPES then key.type.to_s
89
+ end
62
90
  end
63
91
  end
64
92
  end
@@ -5,8 +5,11 @@ require_relative "../parser_current"
5
5
  module Henitai
6
6
  module Operators
7
7
  # Replaces generic method call results with nil.
8
+ #
9
+ # A call with a block is replaced together with its block: replacing only
10
+ # the call would leave +nil { ... }+ behind, which does not parse.
8
11
  class MethodExpression < Henitai::Operator
9
- NODE_TYPES = [:send].freeze
12
+ NODE_TYPES = %i[send block numblock].freeze
10
13
  EXCLUDED_METHODS = %i[
11
14
  +
12
15
  -
@@ -31,9 +34,10 @@ module Henitai
31
34
  end
32
35
 
33
36
  def mutate(node, subject:)
34
- return [] unless node.type == :send
37
+ call = called_method(node)
38
+ return [] unless call&.type == :send
35
39
 
36
- _receiver, method_name, *_arguments = node.children
40
+ _receiver, method_name, *_arguments = call.children
37
41
  return [] if excluded_method?(method_name)
38
42
 
39
43
  [
@@ -48,6 +52,13 @@ module Henitai
48
52
 
49
53
  private
50
54
 
55
+ def called_method(node)
56
+ case node.type
57
+ when :send then node
58
+ when :block, :numblock then node.children.first
59
+ end
60
+ end
61
+
51
62
  def excluded_method?(method_name)
52
63
  method_name.to_s.end_with?("=") || EXCLUDED_METHODS.include?(method_name)
53
64
  end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ module Operators
5
+ # Locates the regexp metacharacters that RegexMutator edits.
6
+ #
7
+ # An escaped character and the contents of a character class are literal
8
+ # text: the +^+ in +[^0-9]+ negates the class and is no anchor, and the
9
+ # +++ in +[+-]+ or +\++ is no quantifier. The scan therefore skips
10
+ # escapes and tracks character-class nesting, including POSIX brackets
11
+ # such as +[[:alpha:]]+.
12
+ class RegexMetacharacters
13
+ ANCHORS = %w[^ $].freeze
14
+ QUANTIFIERS = %w[+ * ?].freeze
15
+ GROUPING = %w[( |].freeze
16
+
17
+ def initialize(source)
18
+ @source = source
19
+ @found = Hash.new { |hash, key| hash[key] = [] }
20
+ scan
21
+ end
22
+
23
+ # Indices of the +char+ quantifier ("+" or "*") applied to an atom.
24
+ def quantifiers(char)
25
+ @found[[:quantifier, char]].dup
26
+ end
27
+
28
+ # Indices of the +char+ anchor ("^" or "$").
29
+ def anchors(char)
30
+ @found[[:anchor, char]].dup
31
+ end
32
+
33
+ # Indices of the opening brackets of top-level, non-negated classes.
34
+ def class_openers
35
+ @found[:class_opener].dup
36
+ end
37
+
38
+ private
39
+
40
+ def scan
41
+ @index = 0
42
+ @depth = 0
43
+ @previous = nil
44
+ step while @index < @source.length
45
+ end
46
+
47
+ def step
48
+ char = @source[@index]
49
+ if char == "\\"
50
+ @previous = :atom
51
+ @index += 2
52
+ else
53
+ @depth.positive? ? within_class(char) : top_level(char)
54
+ @index += 1
55
+ end
56
+ end
57
+
58
+ def within_class(char)
59
+ @depth += 1 if char == "["
60
+ @depth -= 1 if char == "]"
61
+ @previous = :atom if @depth.zero?
62
+ end
63
+
64
+ def top_level(char)
65
+ record(char)
66
+ @previous = kind_of_token(char)
67
+ @depth = 1 if char == "["
68
+ end
69
+
70
+ def record(char)
71
+ if ANCHORS.include?(char)
72
+ @found[[:anchor, char]] << @index
73
+ elsif char == "["
74
+ @found[:class_opener] << @index unless @source[@index + 1] == "^"
75
+ elsif QUANTIFIERS.include?(char) && @previous == :atom
76
+ @found[[:quantifier, char]] << @index
77
+ end
78
+ end
79
+
80
+ def kind_of_token(char)
81
+ return :anchor if ANCHORS.include?(char)
82
+ return :quantifier if QUANTIFIERS.include?(char) || char == "}"
83
+ return :group if GROUPING.include?(char)
84
+
85
+ :atom
86
+ end
87
+ end
88
+ end
89
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../parser_current"
4
+ require_relative "regex_metacharacters"
4
5
 
5
6
  module Henitai
6
7
  module Operators
@@ -8,7 +9,10 @@ module Henitai
8
9
  # and character-class negation.
9
10
  #
10
11
  # Each applicable transformation yields a separate mutant. Invalid
11
- # results (unparseable regex) are discarded before emission.
12
+ # results (unparseable regex) are discarded before emission. Only static,
13
+ # single-segment literals are mutated: an interpolated or multi-line
14
+ # regexp is split into several parts, and rewriting one part alone would
15
+ # drop or misread the others.
12
16
  # Anchor removal and character-class negation are intentionally one-way:
13
17
  # they reduce noisy patterns rather than mirroring a full edit matrix.
14
18
  class RegexMutator < Henitai::Operator
@@ -30,11 +34,11 @@ module Henitai
30
34
  private
31
35
 
32
36
  def extract_parts(node)
33
- str_child = node.children.find { |c| c.is_a?(Parser::AST::Node) && c.type == :str }
34
- opts_node = node.children.find { |c| c.is_a?(Parser::AST::Node) && c.type == :regopt }
35
- return nil unless str_child
37
+ *parts, opts_node = node.children
38
+ return unless opts_node.is_a?(Parser::AST::Node) && opts_node.type == :regopt
39
+ return unless parts.size == 1 && parts.first.is_a?(Parser::AST::Node) && parts.first.type == :str
36
40
 
37
- [str_child.children[0], opts_node]
41
+ [parts.first.children[0], opts_node]
38
42
  end
39
43
 
40
44
  def build_regex_mutant(node, opts_node, new_source, original, description, subject:) # rubocop:disable Metrics/ParameterLists
@@ -47,35 +51,26 @@ module Henitai
47
51
  end
48
52
 
49
53
  def transformations(source)
54
+ found = RegexMetacharacters.new(source)
50
55
  [
51
- *quantifier_swaps(source),
52
- *anchor_removals(source),
53
- *char_class_negations(source)
56
+ [edit(source, found.quantifiers("+"), "*"), "replaced + quantifier with *"],
57
+ [edit(source, found.quantifiers("*"), "+"), "replaced * quantifier with +"],
58
+ # Anchors are removed, never added, and character classes are only
59
+ # negated: the reverse edits would just recreate an input.
60
+ [edit(source, found.anchors("^").first(1), ""), "removed ^ anchor"],
61
+ [edit(source, found.anchors("$").last(1), ""), "removed $ anchor"],
62
+ [insert_after(source, found.class_openers, "^"), "negated character class"]
54
63
  ]
55
64
  end
56
65
 
57
- def quantifier_swaps(source)
58
- # Quantifier swaps are symmetric. The other transforms are intentionally
59
- # one-way because they model reductions instead of reversible edits.
60
- [
61
- [source.gsub(/(?<=[^*+?\\])\+/, "*"), "replaced + quantifier with *"],
62
- [source.gsub(/(?<=[^*+?\\])\*/, "+"), "replaced * quantifier with +"]
63
- ]
64
- end
65
-
66
- def anchor_removals(source)
67
- # Anchors are removed, not added back. The mutation is deliberately
68
- # asymmetric because "restoring" anchors would just recreate the input.
69
- [
70
- [source.sub("^", ""), "removed ^ anchor"],
71
- [source.sub(/\$$/, ""), "removed $ anchor"]
72
- ]
66
+ # Replaces the single characters at +indices+, from the last to the
67
+ # first so earlier indices stay valid.
68
+ def edit(source, indices, text)
69
+ indices.sort.reverse.each_with_object(source.dup) { |index, result| result[index] = text }
73
70
  end
74
71
 
75
- def char_class_negations(source)
76
- # Negation only flips a positive class into a negated one. We do not
77
- # emit the reverse mutation because that would mirror the same edit.
78
- [[source.gsub(/\[(?!\^)/, "[^"), "negated character class"]]
72
+ def insert_after(source, indices, text)
73
+ indices.sort.reverse.each_with_object(source.dup) { |index, result| result.insert(index + 1, text) }
79
74
  end
80
75
 
81
76
  def valid_regex?(source)
@@ -47,7 +47,7 @@ module Henitai
47
47
  end
48
48
 
49
49
  def mutate_implicit_return(node, subject:)
50
- return [] unless node == final_expression_node(subject&.ast_node)
50
+ return [] unless node.equal?(final_expression_node(subject&.ast_node))
51
51
 
52
52
  replacement_nodes(node).map do |replacement|
53
53
  build_mutant(
@@ -16,9 +16,9 @@ module Henitai
16
16
  def mutate(node, subject:)
17
17
  case node.type
18
18
  when :str
19
- mutate_plain_string(node, subject:)
19
+ mutate_plain_string(node, node.children.first, subject:)
20
20
  when :dstr
21
- mutate_interpolated_string(node, subject:)
21
+ mutate_dstr(node, subject:)
22
22
  else
23
23
  []
24
24
  end
@@ -26,8 +26,21 @@ module Henitai
26
26
 
27
27
  private
28
28
 
29
- def mutate_plain_string(node, subject:)
30
- original_value = node.children.first
29
+ # Adjacent literals and heredocs without interpolation parse as a +dstr+
30
+ # of +str+ parts. Collapsing their "interpolation" would reproduce the
31
+ # original string -- an equivalent mutant -- so they are mutated like a
32
+ # plain string with the concatenated value.
33
+ def mutate_dstr(node, subject:)
34
+ return mutate_plain_string(node, static_string(node), subject:) if static?(node)
35
+
36
+ mutate_interpolated_string(node, subject:)
37
+ end
38
+
39
+ def static?(node)
40
+ node.children.all? { |child| child.type == :str }
41
+ end
42
+
43
+ def mutate_plain_string(node, original_value, subject:)
31
44
  REPLACEMENTS.reject { |r| r == original_value }.map do |replacement|
32
45
  build_mutant(
33
46
  subject:,
@@ -24,6 +24,7 @@ module Henitai
24
24
  autoload :MethodExpression, "henitai/operators/method_expression"
25
25
  autoload :AssignmentExpression, "henitai/operators/assignment_expression"
26
26
  autoload :MethodChainUnwrap, "henitai/operators/method_chain_unwrap"
27
+ autoload :RegexMetacharacters, "henitai/operators/regex_metacharacters"
27
28
  autoload :RegexMutator, "henitai/operators/regex_mutator"
28
29
  autoload :UnaryOperator, "henitai/operators/unary_operator"
29
30
  autoload :UpdateOperator, "henitai/operators/update_operator"
@@ -35,12 +35,7 @@ module Henitai
35
35
  # @return [Array<String>] sorted; empty when the test is unknown or the
36
36
  # map is unavailable.
37
37
  def source_files_covered_by(test_file)
38
- wanted = File.expand_path(test_file.to_s)
39
- map.select { |test, _| File.expand_path(test) == wanted }
40
- .values
41
- .flat_map(&:keys)
42
- .uniq
43
- .sort
38
+ Array(map_by_absolute_test_path[File.expand_path(test_file.to_s)]&.keys).sort
44
39
  end
45
40
 
46
41
  # True when the given test file's recorded coverage intersects the
@@ -63,11 +58,20 @@ module Henitai
63
58
  mutant.location[:end_line]
64
59
  end
65
60
 
61
+ # RSpec records test files as "./spec/x_spec.rb" while candidates arrive
62
+ # as "spec/x_spec.rb"; both resolve to the same absolute key.
66
63
  def coverage_lines_for(test, mutant)
67
- source_map = map[test.to_s] || {}
64
+ source_map = map_by_absolute_test_path[File.expand_path(test.to_s)] || {}
68
65
  Array(source_map[File.expand_path(mutant.location[:file])]).uniq
69
66
  end
70
67
 
68
+ def map_by_absolute_test_path
69
+ @map_by_absolute_test_path ||= map.each_with_object({}) do |(test, source_map), index|
70
+ merged = index[File.expand_path(test)] ||= {}
71
+ source_map.each { |file, lines| merged[file] = Array(merged[file]) + Array(lines) }
72
+ end
73
+ end
74
+
71
75
  def mutant_lines(mutant)
72
76
  (mutant.location[:start_line]..mutant.location[:end_line]).to_a
73
77
  end