nukadoko 0.1.0 → 0.2.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 (147) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +291 -0
  3. data/README.ja.md +58 -5
  4. data/README.md +15 -3
  5. data/exe/nuka +8 -0
  6. data/lib/nukadoko/aria_snapshot.rb +1008 -0
  7. data/lib/nukadoko/aria_tree.rb +150 -0
  8. data/lib/nukadoko/base.rb +274 -0
  9. data/lib/nukadoko/check.rb +669 -22
  10. data/lib/nukadoko/claim_check.rb +177 -0
  11. data/lib/nukadoko/claim_check_run.rb +293 -0
  12. data/lib/nukadoko/claim_line.rb +381 -0
  13. data/lib/nukadoko/claim_rules.rb +519 -0
  14. data/lib/nukadoko/claims.rb +407 -30
  15. data/lib/nukadoko/cli.rb +802 -19
  16. data/lib/nukadoko/codes.json +942 -0
  17. data/lib/nukadoko/codes.rb +19 -0
  18. data/lib/nukadoko/command.rb +214 -12
  19. data/lib/nukadoko/criteria.rb +172 -0
  20. data/lib/nukadoko/definition.rb +33 -41
  21. data/lib/nukadoko/env_check.rb +90 -0
  22. data/lib/nukadoko/features.rb +80 -10
  23. data/lib/nukadoko/fixtures.rb +296 -10
  24. data/lib/nukadoko/http_recording.rb +68 -0
  25. data/lib/nukadoko/init.rb +130 -0
  26. data/lib/nukadoko/judge.rb +221 -0
  27. data/lib/nukadoko/judgment_file.rb +78 -0
  28. data/lib/nukadoko/judgments.rb +256 -0
  29. data/lib/nukadoko/literal.rb +129 -0
  30. data/lib/nukadoko/measured.rb +105 -0
  31. data/lib/nukadoko/order.rb +84 -0
  32. data/lib/nukadoko/parts.rb +42 -21
  33. data/lib/nukadoko/pattern.rb +11 -1
  34. data/lib/nukadoko/poll.rb +17 -6
  35. data/lib/nukadoko/program.rb +105 -17
  36. data/lib/nukadoko/project_fixtures.rb +17 -2
  37. data/lib/nukadoko/report_allure.rb +751 -0
  38. data/lib/nukadoko/report_messages.rb +167 -0
  39. data/lib/nukadoko/report_run.rb +169 -0
  40. data/lib/nukadoko/run.rb +865 -88
  41. data/lib/nukadoko/run_record.rb +532 -0
  42. data/lib/nukadoko/scaffold.rb +1015 -0
  43. data/lib/nukadoko/schema.rb +61 -4
  44. data/lib/nukadoko/secrets.rb +359 -0
  45. data/lib/nukadoko/selection.rb +163 -0
  46. data/lib/nukadoko/signature.rb +4 -1
  47. data/lib/nukadoko/skill.rb +36 -0
  48. data/lib/nukadoko/step.rb +62 -21
  49. data/lib/nukadoko/summary.rb +662 -0
  50. data/lib/nukadoko/table.rb +34 -2
  51. data/lib/nukadoko/text_fit.rb +179 -0
  52. data/lib/nukadoko/trace.rb +244 -0
  53. data/lib/nukadoko/trace_actions.rb +116 -0
  54. data/lib/nukadoko/tree_passes.rb +119 -0
  55. data/lib/nukadoko/verdict.rb +128 -0
  56. data/lib/nukadoko/version.rb +2 -1
  57. data/lib/nukadoko/vocabulary.rb +6 -0
  58. data/lib/nukadoko/walk.rb +305 -0
  59. data/lib/nukadoko/walk_files.rb +473 -0
  60. data/lib/nukadoko/walk_step.rb +149 -0
  61. data/lib/nukadoko.rb +36 -0
  62. data/llms.txt +296 -0
  63. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  64. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  65. data/sig/generated/nukadoko/base.rbs +136 -0
  66. data/sig/generated/nukadoko/check.rbs +255 -0
  67. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  68. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  69. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  70. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  71. data/sig/generated/nukadoko/claims.rbs +165 -0
  72. data/sig/generated/nukadoko/cli.rbs +182 -0
  73. data/sig/generated/nukadoko/codes.rbs +16 -0
  74. data/sig/generated/nukadoko/command.rbs +109 -0
  75. data/sig/generated/nukadoko/criteria.rbs +83 -0
  76. data/sig/generated/nukadoko/definition.rbs +30 -0
  77. data/sig/generated/nukadoko/env_check.rbs +38 -0
  78. data/sig/generated/nukadoko/features.rbs +101 -0
  79. data/sig/generated/nukadoko/fixtures.rbs +152 -0
  80. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  81. data/sig/generated/nukadoko/init.rbs +66 -0
  82. data/sig/generated/nukadoko/judge.rbs +64 -0
  83. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  84. data/sig/generated/nukadoko/judgments.rbs +120 -0
  85. data/sig/generated/nukadoko/literal.rbs +71 -0
  86. data/sig/generated/nukadoko/measured.rbs +42 -0
  87. data/sig/generated/nukadoko/order.rbs +54 -0
  88. data/sig/generated/nukadoko/parts.rbs +35 -0
  89. data/sig/generated/nukadoko/pattern.rbs +28 -0
  90. data/sig/generated/nukadoko/poll.rbs +40 -0
  91. data/sig/generated/nukadoko/program.rbs +101 -0
  92. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  93. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  94. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  95. data/sig/generated/nukadoko/report_run.rbs +102 -0
  96. data/sig/generated/nukadoko/run.rbs +257 -0
  97. data/sig/generated/nukadoko/run_record.rbs +174 -0
  98. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  99. data/sig/generated/nukadoko/schema.rbs +137 -0
  100. data/sig/generated/nukadoko/secrets.rbs +157 -0
  101. data/sig/generated/nukadoko/selection.rbs +73 -0
  102. data/sig/generated/nukadoko/signature.rbs +17 -0
  103. data/sig/generated/nukadoko/skill.rbs +20 -0
  104. data/sig/generated/nukadoko/step.rbs +115 -0
  105. data/sig/generated/nukadoko/summary.rbs +204 -0
  106. data/sig/generated/nukadoko/table.rbs +43 -0
  107. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  108. data/sig/generated/nukadoko/trace.rbs +127 -0
  109. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  110. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  111. data/sig/generated/nukadoko/verdict.rbs +56 -0
  112. data/sig/generated/nukadoko/version.rbs +5 -0
  113. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  114. data/sig/generated/nukadoko/walk.rbs +139 -0
  115. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  116. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  117. data/sig/generated/nukadoko.rbs +15 -0
  118. data/sig/nukadoko.rbs +5 -48
  119. data/skills/nukadoko/SKILL.md +120 -0
  120. data/skills/nukadoko/references/checking-steps.md +200 -0
  121. data/skills/nukadoko/references/diagnosing.md +200 -0
  122. data/skills/nukadoko/references/done.md +99 -0
  123. data/skills/nukadoko/references/evidence.md +124 -0
  124. data/skills/nukadoko/references/examples/cli.md +230 -0
  125. data/skills/nukadoko/references/examples/http-api.md +339 -0
  126. data/skills/nukadoko/references/examples/workflow.md +173 -0
  127. data/skills/nukadoko/references/exploring.md +184 -0
  128. data/skills/nukadoko/references/fixtures.md +198 -0
  129. data/skills/nukadoko/references/from-prose.md +51 -0
  130. data/skills/nukadoko/references/judgments.md +95 -0
  131. data/skills/nukadoko/references/maintenance.md +97 -0
  132. data/skills/nukadoko/references/merge-risk.md +74 -0
  133. data/skills/nukadoko/references/parts.md +152 -0
  134. data/skills/nukadoko/references/perturbed-worlds.md +107 -0
  135. data/skills/nukadoko/references/program.md +200 -0
  136. data/skills/nukadoko/references/reviewing.md +200 -0
  137. data/skills/nukadoko/references/running.md +200 -0
  138. data/skills/nukadoko/references/scenario-rules.md +188 -0
  139. data/skills/nukadoko/references/states.md +66 -0
  140. data/skills/nukadoko/references/step-files.md +200 -0
  141. data/skills/nukadoko/references/verdicts.md +200 -0
  142. data/skills/nukadoko/references/writing-steps.md +200 -0
  143. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  144. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  145. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  146. data/skills/nukadoko-verification/SKILL.md +263 -0
  147. metadata +121 -1
@@ -1,4 +1,5 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  # What `check` can say without running anything: every finding follows from
4
5
  # the step classes, their patterns and schemas, `Method#parameters`, and the
@@ -6,30 +7,86 @@
6
7
  # conformance cases judges both engines.
7
8
  module Nukadoko
8
9
  module Engine
9
- Finding = Data.define(:severity, :code, :file, :line, :step, :message, :fix) do
10
+ Finding = Data.define(
11
+ :severity, #: String
12
+ :code, #: String
13
+ :file, #: String?
14
+ :line, #: Integer?
15
+ :step, #: String?
16
+ :message, #: String
17
+ :fix, #: String?
18
+ # The command that is the next step, printed as `do:`; most findings have none.
19
+ :run, #: String?
20
+ )
21
+
22
+ # A Data block's methods are its own, but rbs-inline reads only a class
23
+ # body, so they are written in one.
24
+ class Finding
25
+ #: (String, String, singleton(Step), String, String?) -> Finding
10
26
  def self.about_step(severity, code, step, message, fix)
11
- new(severity, code, step.file, step.line, step.step_name, message, fix)
27
+ new(severity, code, step.file, step.line, step.step_name, message, fix, nil)
12
28
  end
13
29
 
14
- def to_h = super.compact
30
+ #: () -> Hash[Symbol, untyped]
31
+ def to_h
32
+ hash = super.compact
33
+ hash[:do] = hash.delete(:run) if hash.key?(:run)
34
+ hash
35
+ end
15
36
  end
16
37
 
17
38
  FIXTURES = %w[baseURL call context env evidence page pageAs poll request requireEnv result scratch].freeze
18
39
 
19
40
  class Check
20
- attr_reader :findings, :usable
41
+ attr_reader :findings #: Array[Finding]
42
+ attr_reader :usable #: Array[singleton(Step)]
21
43
 
22
- def initialize(steps, scenarios)
44
+ # `environments` is the selection a run without --env starts, for
45
+ # condition-unmet; nil when --env named the selection. `problems` are
46
+ # what the feature loader found that runs nothing.
47
+ # `config` holds what was found in the config and the program file before
48
+ # any step loaded, such as an env file that is missing.
49
+ #: (Array[singleton(Step)], Array[Scenario], ?features: bool, ?full: bool, ?conditions: Array[String]?, ?environments: Array[Environment]?, ?problems: Array[FeatureProblem], ?config: Array[Finding]) -> void
50
+ def initialize(steps, scenarios, features: true, full: false, conditions: nil, environments: nil, problems: [], config: [])
23
51
  @steps = steps
24
52
  @scenarios = scenarios
53
+ @conditions = conditions
25
54
  @findings = []
55
+ # With no step file no line can ever match, so every line would read
56
+ # as undefined; one finding says why instead.
57
+ if !features
58
+ @findings << Finding.new("error", "features-dir-missing", "nukadoko.config.rb", nil, nil, %(featuresDir "features" does not exist),
59
+ "Create features/steps for the step files, or correct featuresDir in nukadoko.config.rb.", nil)
60
+ elsif steps.empty?
61
+ @findings << Finding.new("error", "no-step-files-found", "features", nil, nil,
62
+ %(no .rb step file was found while scanning "features"; no step can ever be registered), Codes.fix("no-step-files-found"), nil)
63
+ end
64
+ @findings.concat(config)
26
65
  @usable = steps.reject { definition_broken?(_1) }
27
66
  @usable.each { check_contract(_1) }
67
+ check_duplicate_patterns
28
68
  check_parts
29
69
  check_shapes
70
+ check_tags(conditions)
30
71
  check_lines
72
+ # One finding per cause: each undefined line already names the
73
+ # scaffold command for its file, so the missing step files would be
74
+ # said a second time.
75
+ @findings.reject! { _1.code == "no-step-files-found" } if steps.empty? && @findings.any? { _1.code == "undefined-step" }
76
+ check_fixtures(full)
77
+ check_conditions_met(environments) if environments
78
+ problems.each { |problem| findings << Finding.new("error", problem.code, problem.uri, problem.line, nil, problem.message, Codes.fix(problem.code), nil) }
79
+ if full
80
+ check_unbound
81
+ check_from_unused
82
+ end
83
+ # Errors, then warnings, then notes, each kind in the order found, as
84
+ # the TypeScript engine reports them.
85
+ rank = { "error" => 0, "warning" => 1, "note" => 2 }
86
+ @findings = @findings.uniq { [_1.code, _1.file, _1.line, _1.message] }.each_with_index.sort_by { |f, i| [rank.fetch(f.severity, 3), i] }.map(&:first)
31
87
  end
32
88
 
89
+ #: () -> bool
33
90
  def passed? = findings.none? { _1.severity == "error" }
34
91
 
35
92
  private
@@ -37,19 +94,83 @@ module Nukadoko
37
94
  # A step whose definition cannot stand (an unknown claim compare) is left
38
95
  # out of the vocabulary, as the TypeScript engine leaves out a step file
39
96
  # that fails to import, so it can never match a line.
97
+ #: (singleton(Step)) -> bool
40
98
  def definition_broken?(step)
41
- problems = Claims.unknown_compares(step.claims || []).map { "claims compare must be one of #{Claims::COMPARES.join(", ")}; got #{_1.inspect}." }
42
- problems += Definition.new(step).problems
99
+ if (pattern = pattern_problem(step))
100
+ findings << Finding.new("error", pattern[0], step.file, nil, step.step_name, pattern[1], Codes.fix(pattern[0]), nil)
101
+ return true
102
+ end
103
+ problems = Definition.new(step).problems
43
104
  problems.each do |problem|
44
105
  findings << Finding.about_step("error", "step-file-import-failed", step, problem,
45
- "Correct the error that the message names in the file, then run nuka check again.")
106
+ "Correct the import or the error that the message names in the file, then run nuka check again.")
46
107
  end
47
108
  problems.any?
48
109
  end
49
110
 
111
+ KEY = /\A[A-Za-z_][A-Za-z0-9_]*\z/
112
+
113
+ # Why the step's pattern cannot be read, as the TypeScript engine says
114
+ # it: the first broken capture, then what cucumber-expressions refuses.
115
+ #: (singleton(Step)) -> [String, String]?
116
+ def pattern_problem(step)
117
+ pattern = step.pattern or return nil
118
+ head = %(Step "#{step.step_name}" pattern "#{pattern}")
119
+ keys = []
120
+ rest = pattern.gsub(/\./, "")
121
+ open = rest.index("{")
122
+ while open
123
+ close = rest.index("}", open)
124
+ return ["unterminated-capture", %(#{head}: Pattern has an unterminated "{" starting at: #{rest[open..]})] unless close
125
+
126
+ token = rest[open + 1...close].to_s
127
+ key, type = token.split(":", 2)
128
+ return ["unnamed-capture", %(#{head}: Parameter "{#{token}}" has no name; every parameter in a pattern must be written {key:type} (docs/spec.md "Typed steps"))] unless type
129
+ return ["invalid-capture-key", %(#{head}: Parameter "{#{token}}" has an invalid name "#{key}": must match [a-zA-Z_][a-zA-Z0-9_]*)] unless key.to_s.match?(KEY)
130
+
131
+ keys << key
132
+ open = rest.index("{", close)
133
+ end
134
+ repeated = keys.tally.select { _2 > 1 }.keys.first
135
+ return ["duplicate-capture-key", %(#{head} binds key "#{repeated}" more than once)] if repeated
136
+
137
+ Pattern.new(pattern)
138
+ nil
139
+ rescue Cucumber::CucumberExpressions::UndefinedParameterTypeError => e
140
+ types = Pattern::REGISTRY.parameter_types.map(&:name).reject(&:empty?).sort
141
+ ["unknown-parameter-type", "#{head}: #{e.message} This project's registered parameter types are: #{types.join(", ")}."]
142
+ rescue StandardError => e
143
+ ["pattern-syntax-error", "#{head}: #{e.message}"]
144
+ end
145
+
146
+ NUMBER_TYPES = %w[int float bigdecimal biginteger byte short long double].freeze
147
+ STRING_TYPES = %w[string word].freeze
148
+
149
+ # A capture hands the step a number or a string, and an args field of
150
+ # the other kind can never hold it.
151
+ #: (singleton(Step)) -> Array[Array[untyped]]
152
+ def capture_mismatches(step)
153
+ fields = step.args.fields.to_h { [_1.name.to_s, _1.type] }
154
+ step.pattern.to_s.scan(Pattern::NAMED).filter_map do |key, type|
155
+ declared = fields[key]
156
+ captured = if NUMBER_TYPES.include?(type) then "number"
157
+ elsif STRING_TYPES.include?(type) then "string"
158
+ end
159
+ held = case declared
160
+ when :string, Array then declared == :string || declared.first == :enum ? "string" : nil
161
+ when :number, :integer then "number"
162
+ when :boolean then "boolean"
163
+ end
164
+ next unless captured && held && captured != held
165
+
166
+ [key, type, captured, held]
167
+ end
168
+ end
169
+
170
+ #: (singleton(Step)) -> void
50
171
  def check_contract(step)
51
172
  keys = step.args.fields.map { _1.name.to_s }
52
- (step.pattern ? Pattern.new(step.pattern).keys - keys : []).each do |key|
173
+ ((pattern = step.pattern) ? Pattern.new(pattern).keys - keys : []).each do |key|
53
174
  findings << Finding.about_step("error", "unknown-capture-key", step,
54
175
  %(Step "#{step.step_name}" pattern "#{step.pattern}" binds key "#{key}", which is not a key of its args schema),
55
176
  "Rename the capture to a key of the args schema, or add the key to the schema.")
@@ -60,6 +181,11 @@ module Nukadoko
60
181
  "Step \"#{step.step_name}\" has schema fields with no description: #{undescribed.map(&:name).join(", ")}",
61
182
  "Give each field a description, so nuka steps and an agent can say what it means.")
62
183
  end
184
+ capture_mismatches(step).each do |key, type, captured, held|
185
+ findings << Finding.new("error", "capture-type-mismatch", step.file, nil, step.step_name,
186
+ %(Step "#{step.step_name}" pattern "#{step.pattern}" binds key "#{key}" as {#{type}} (a #{captured}), but args declares "#{key}" as a #{held}),
187
+ "Make the capture type and the args field type agree: change the {key:type} in the pattern, or declare the field with the type the capture gives.", nil)
188
+ end
63
189
  known = FIXTURES + Nukadoko.project_fixtures.keys.map(&:to_s)
64
190
  (step.fixtures.map(&:to_s) - known).each do |name|
65
191
  findings << Finding.about_step("error", "fixture-structural-violation", step,
@@ -68,8 +194,297 @@ module Nukadoko
68
194
  end
69
195
  end
70
196
 
197
+ # Two patterns that read the same once their names go would match the
198
+ # same lines; the later file is named, with every step that shares it.
199
+ #: () -> void
200
+ def check_duplicate_patterns
201
+ @usable.select(&:pattern).group_by { _1.pattern.to_s.gsub(Pattern::NAMED) { "{#{Regexp.last_match(2)}}" } }.each do |text, group|
202
+ next if group.size < 2
203
+
204
+ sorted = group.sort_by(&:file)
205
+ findings << Finding.new("error", "duplicate-pattern", sorted.last.file, nil, nil,
206
+ %(Multiple patterns normalize to the same text "#{text}": #{sorted.map { %(#{_1.step_name} ("#{_1.pattern}")) }.join(", ")}),
207
+ Codes.fix("duplicate-pattern"), nil)
208
+ end
209
+ end
210
+
211
+ # A pattern no line binds alone has no place in a scenario; a placeholder
212
+ # description is what a person picking a step would read.
213
+ #: () -> void
214
+ def check_unbound
215
+ unbound_steps.each do |step|
216
+ findings << Finding.new("note", "pattern-unbound", step.file, nil, step.step_name,
217
+ %(Step "#{step.step_name}" declares a pattern, but no feature line under the scanned directories (features) binds it. It has no place in any scenario right now.),
218
+ Codes.fix("pattern-unbound"), nil)
219
+ end
220
+ @usable.select { _1.description.to_s == "TODO: describe #{_1.step_name}" }.sort_by(&:file).each do |step|
221
+ findings << Finding.new("note", "step-description-todo", step.file, nil, step.step_name,
222
+ %(Step "#{step.step_name}" still has the description nuka scaffold wrote ("#{step.description}"); nuka steps and nuka describe show it to whoever picks a step, so say what the step does.),
223
+ Codes.fix("step-description-todo"), nil)
224
+ end
225
+ end
226
+
227
+ # A from key every line fills with a capture never takes its value
228
+ # from the producer it names.
229
+ #: () -> void
230
+ def check_from_unused
231
+ bound = @scenarios.flat_map(&:steps).filter_map { |line| (m = Engine.matches(@usable, line.text)).size == 1 ? m.first : nil }
232
+ @usable.each do |step|
233
+ occurrences = bound.select { _1.first == step }.map(&:last)
234
+ next if occurrences.empty?
235
+
236
+ step.from.each_key do |key|
237
+ next unless occurrences.all? { _1.key?(key) }
238
+
239
+ findings << Finding.new("note", "from-unused", step.file, nil, step.step_name,
240
+ %(Step "#{step.step_name}"'s from.#{key} declares a producer, but every bound occurrence of this step already fills "#{key}" from a pattern capture. That producer has never supplied it. Still reachable through `nuka do --use`; this is a fact, not a verdict on whether to remove it.),
241
+ Codes.fix("from-unused"), nil)
242
+ end
243
+ end
244
+ end
245
+
246
+ # A from key whose producer has not run before the line fails args
247
+ # validation with certainty, and two producers that both ran leave
248
+ # the feature file unable to say which one counts. A line before it
249
+ # that matches no step may be the producer misspelled, so those
250
+ # findings wait behind one warning.
251
+ #: (Scenario) -> void
252
+ def check_from_order(scenario)
253
+ resolved = scenario.steps.map { |line| (m = Engine.matches(@usable, line.text)).size == 1 ? m.first : nil }
254
+ held = []
255
+ resolved.each_with_index do |(step, captures), index|
256
+ next unless step
257
+
258
+ step.from.each do |key, sources|
259
+ next if captures.key?(key) || step.args.fields.none? { _1.name.to_s == key }
260
+
261
+ names = sources.filter_map { |producer, _| producer.step_name if @usable.include?(producer) }.uniq
262
+ next if names.empty?
263
+
264
+ before = names.select { |name| resolved.first(index).any? { _1&.first&.step_name == name } }
265
+ next if before.size == 1
266
+
267
+ line = scenario.steps[index]
268
+ if before.size > 1
269
+ quoted = before.map { %("#{_1}") }.join(", ")
270
+ findings << Finding.new("error", "from-order-violation", scenario.uri, line.line, step.step_name,
271
+ %(Step "#{step.step_name}"'s from.#{key} has more than one of its candidate producers bound earlier in this scenario (#{quoted}): from's candidates are mutually exclusive by design (docs/spec.md "Chaining steps"), so the feature file, not the tool, must make exactly one of them win),
272
+ "Remove or move lines so that exactly one of steps #{quoted} runs before this line.", nil)
273
+ next
274
+ end
275
+ undefined = scenario.steps.first(index).each_index.select { Engine.matches(@usable, scenario.steps[_1].text).empty? }
276
+ issue = { index: index, step: step.step_name, key: key, candidates: names }
277
+ next held << issue.merge(undefined: undefined) if undefined.any?
278
+
279
+ findings << Finding.new("error", "from-order-violation", scenario.uri, line.line, step.step_name,
280
+ from_missing_message(step.step_name, key, names, resolved),
281
+ from_order_fix(issue), nil)
282
+ end
283
+ end
284
+ hold_from_order(scenario, held) if held.any?
285
+ end
286
+
287
+ # What a claim step's claims read, from the producers of its from
288
+ # values on the earlier lines of the scenario (ClaimCheck).
289
+ #: (Scenario) -> void
290
+ def check_claim_sources(scenario)
291
+ resolved = scenario.steps.map { |line| (m = Engine.matches(@usable, line.text)).size == 1 ? m.first : nil }
292
+ lines = scenario.steps.map(&:line)
293
+ resolved.each_index do |index|
294
+ ClaimCheck.issues(resolved, lines, index).each do |code, message|
295
+ findings << Finding.new("error", code, scenario.uri, lines[index], resolved[index]&.first&.step_name, message, Codes.fix(code), nil)
296
+ end
297
+ end
298
+ end
299
+
300
+ #: (String, String, Array[String], Array[untyped]) -> String
301
+ def from_missing_message(step_name, key, names, resolved)
302
+ anywhere = ->(name) { resolved.any? { _1&.first&.step_name == name } }
303
+ if names.size == 1
304
+ name = names.first
305
+ detail = anywhere.(name) ? %("#{name}" is bound in this scenario, but only at or after this line, never before it) : %("#{name}" is never bound anywhere in this scenario)
306
+ return %(Step "#{step_name}"'s from.#{key} needs step "#{name}" to have already run earlier in this scenario, but #{detail}. This line would fail args validation with certainty)
307
+ end
308
+ detail = names.map { anywhere.(_1) ? %("#{_1}" is bound only at or after this line, never before it) : %("#{_1}" is never bound anywhere in this scenario) }.join("; ")
309
+ %(Step "#{step_name}"'s from.#{key} needs exactly one of its candidate producers (#{names.map { %("#{_1}") }.join(", ")}) to have already run earlier in this scenario, but none has: #{detail}. This line would fail args validation with certainty)
310
+ end
311
+
312
+ #: (Hash[Symbol, untyped]) -> String
313
+ def from_order_fix(issue)
314
+ names = issue[:candidates]
315
+ put = names.size == 1 ? %(Put a line that runs step "#{names.first}" earlier in the scenario) : "Put a line that runs exactly one of steps #{names.map { %("#{_1}") }.join(", ")} earlier in the scenario"
316
+ return "#{put}." if issue[:index].zero?
317
+
318
+ %(#{put}. Or, if a step that an earlier line runs returns #{issue[:key]}, list that step as another [step, "#{issue[:key]}"] candidate in from.#{issue[:key]} of step "#{issue[:step]}".)
319
+ end
320
+
321
+ #: (Scenario, Array[Hash[Symbol, untyped]]) -> void
322
+ def hold_from_order(scenario, held)
323
+ steps_phrase = ->(names) { names.size == 1 ? %(step "#{names.first}") : "one of steps #{names.map { %("#{_1}") }.join(", ")}" }
324
+ undefined = held.flat_map { _1[:undefined] }.uniq.sort
325
+ consumers = held.group_by { [_1[:index], _1[:candidates]] }.map do |(index, candidates), issues|
326
+ "line #{scenario.steps[index].line} step \"#{issues.first[:step]}\" needs #{steps_phrase.(candidates)} for #{issues.map { _1[:key] }.join(", ")}"
327
+ end
328
+ lines = undefined.map { %(line #{scenario.steps[_1].line} "#{scenario.steps[_1].text}") }
329
+ which = lines.size == 1 ? lines.first : "one of #{lines.join(", ")}"
330
+ count = held.size == 1 ? "1 from-order-violation finding" : "#{held.size} from-order-violation findings"
331
+ findings << Finding.new("warning", "from-order-check-suppressed", scenario.uri, scenario.steps[undefined.first].line, nil,
332
+ "Held back #{count} while #{lines.join(", ")} #{lines.size == 1 ? "matches" : "match"} no step, because such a line may be meant to run the producer they need: #{consumers.join("; ")}",
333
+ "If #{which} is meant to run #{steps_phrase.(held.flat_map { _1[:candidates] }.uniq)}, reword that line to match that step's pattern. Otherwise fix the undefined-step finding first, then run nuka check again: a held-back finding that still applies is reported then.", nil)
334
+ end
335
+
336
+ SCENARIO_ONLY = FIXTURES - %w[env requireEnv baseURL]
337
+
338
+ # Fixture definitions that can never resolve, and (in a whole-project
339
+ # check) one no step reaches.
340
+ #: (bool) -> void
341
+ def check_fixtures(full)
342
+ fixtures = Nukadoko.project_fixtures
343
+ return if fixtures.empty?
344
+
345
+ config = "nukadoko.config.rb"
346
+ state = Hash.new(:white)
347
+ visit = lambda do |name, stack|
348
+ state[name] = :gray
349
+ stack.push(name)
350
+ fixtures[name].dependencies.each do |dep|
351
+ next unless fixtures.key?(dep) && dep != name
352
+
353
+ if state[dep] == :gray
354
+ cycle = [*stack.drop(stack.index(dep)), dep]
355
+ findings << Finding.new("error", "fixture-cycle", config, nil, nil, "fixture dependency cycle: #{cycle.join(" -> ")}", Codes.fix("fixture-cycle"), nil)
356
+ elsif state[dep] == :white
357
+ visit.(dep, stack)
358
+ end
359
+ end
360
+ stack.pop
361
+ state[name] = :black
362
+ end
363
+ fixtures.each_key { visit.(_1, []) if state[_1] == :white }
364
+
365
+ fixtures.each_value do |fixture|
366
+ next unless fixture.scope == :process
367
+
368
+ fixture.dependencies.each do |dep|
369
+ scenario = fixtures.key?(dep) && dep != fixture.name ? fixtures[dep].scope == :scenario : SCENARIO_ONLY.include?(dep.to_s)
370
+ next unless scenario
371
+
372
+ findings << Finding.new("error", "fixture-scope-violation", config, nil, nil,
373
+ %(fixture "#{fixture.name}" has scope "process" but depends on "#{dep}", which is scope "scenario": a "process"-scope fixture is built once for the whole run and can outlive any single scenario's own resources, so it cannot depend on something rebuilt per scenario),
374
+ Codes.fix("fixture-scope-violation"), nil)
375
+ end
376
+ end
377
+ return unless full
378
+
379
+ reachable = []
380
+ pending = @steps.flat_map(&:bag)
381
+ until pending.empty?
382
+ name = pending.shift
383
+ next if reachable.include?(name)
384
+
385
+ reachable << name
386
+ pending.concat(fixtures[name].dependencies) if fixtures.key?(name)
387
+ end
388
+ (fixtures.keys - reachable).each do |name|
389
+ findings << Finding.new("note", "fixture-unused", config, nil, nil,
390
+ %(Fixture "#{name}" is declared under nukadoko.config.rb's own `fixtures`, but no typed step requires it, directly or through another fixture. Still reachable through `nuka do`; this is a fact, not a verdict on whether to remove it.),
391
+ Codes.fix("fixture-unused"), nil)
392
+ end
393
+ end
394
+
395
+ # A scenario whose condition tags no environment of the selection meets
396
+ # has no required cell, so nothing in the run shows that it holds.
397
+ #: (Array[Environment]) -> void
398
+ def check_conditions_met(environments)
399
+ declared = @conditions || []
400
+ described = environments.map { |e| "#{e.name} (#{describe_conditions(e.conditions)})" }.join("; ")
401
+ @scenarios.uniq { [_1.uri, _1.line] }.each do |scenario|
402
+ tags = Table.condition_tags(scenario.tags)
403
+ next if tags.empty?
404
+
405
+ names = tags.map { Check.condition_of(_1) }
406
+ next if names.any?(&:nil?) || names.any? { !declared.include?(_1) }
407
+ next if environments.any? { Table.role(tags, _1.conditions) == "required" }
408
+
409
+ findings << Finding.new("error", "condition-unmet", scenario.uri, scenario.line, nil,
410
+ %(Scenario "#{scenario.name}" needs #{tags.join(" ")}, and no selected environment meets #{tags.size == 1 ? "it" : "all of them"}: #{described}. Its cells would all be controls, so nothing would show that it holds),
411
+ Codes.fix("condition-unmet"), nil)
412
+ end
413
+ end
414
+
415
+ #: (Hash[String, untyped]) -> String
416
+ def describe_conditions(conditions)
417
+ return "no conditions" if conditions.empty?
418
+
419
+ conditions.map { |name, value| "#{name}: #{value.is_a?(String) ? JSON.generate(value) : value}" }.join(", ")
420
+ end
421
+
422
+ CONDITION_NAME = /\A[A-Za-z0-9_.-]+\z/
423
+ CONDITION_VALUE = /\A[^\s@]+\z/
424
+
425
+ # The condition a tag names, nil for one that does not read.
426
+ #: (String) -> String?
427
+ def self.condition_of(tag)
428
+ if tag.start_with?("@without:")
429
+ name = tag.delete_prefix("@without:")
430
+ return name.match?(CONDITION_NAME) ? name : nil
431
+ end
432
+ name, value = tag.delete_prefix("@with:").split("=", 2)
433
+ return nil unless name&.match?(CONDITION_NAME)
434
+ return name if value.nil?
435
+
436
+ value.match?(CONDITION_VALUE) && !%w[true false].include?(value) ? name : nil
437
+ end
438
+
439
+ EXPECTED = { "status" => [/\A5[0-9]{2}\z/, "<500-599>", "a status from 500 to 599"],
440
+ "error" => [CONDITION_VALUE, "<class>", "the class of an error the program reports with handled: false"],
441
+ "page-error" => [CONDITION_VALUE, "<name>", "the name of an error the page threw, such as TypeError"] }.freeze
442
+ EXPECTS_FORMS = "@expects:status=<500-599>, @expects:error=<class>, or @expects:page-error=<name>"
443
+
444
+ # Why an @expects: tag accepts nothing, nil for one that reads.
445
+ #: (String) -> String?
446
+ def self.expects_problem(tag)
447
+ kind, value = tag.delete_prefix("@expects:").split("=", 2)
448
+ rule = EXPECTED[kind]
449
+ return "#{tag} does not read as #{EXPECTS_FORMS}, so it accepts nothing" unless rule
450
+ return "#{tag} names no value, and an @expects tag names what it accepts: #{rule[2]}" if value.nil? || value.empty?
451
+ return nil if value.match?(rule[0])
452
+
453
+ "#{tag} does not name #{rule[2]}, so it accepts nothing#{": a run judges no other status, and one tag names one status" if kind == "status"}"
454
+ end
455
+
456
+ #: (Array[String]?) -> void
457
+ def check_tags(conditions)
458
+ @scenarios.flat_map { |scenario| scenario.tag_lines.map { |tag, line| [scenario.uri, line, tag] } }.uniq.each do |uri, line, tag|
459
+ if tag.start_with?("@expects:")
460
+ problem = Check.expects_problem(tag)
461
+ findings << Finding.new("error", "expects-tag-malformed", uri, line, nil, problem, Codes.fix("expects-tag-malformed"), nil) if problem
462
+ next
463
+ end
464
+ next unless tag.start_with?("@with:", "@without:")
465
+
466
+ name = Check.condition_of(tag)
467
+ if name.nil?
468
+ boolean = tag.match(/\A@with:([A-Za-z0-9_.-]+)=(true|false)\z/)
469
+ message = if boolean
470
+ "#{tag} names a boolean as text, which reads two ways: write #{boolean[2] == "true" ? "@with:" : "@without:"}#{boolean[1]}, which reads the boolean the program file declares"
471
+ else
472
+ "#{tag} does not read as @with:<condition>, @with:<condition>=<value>, or @without:<condition>, so it names no condition"
473
+ end
474
+ findings << Finding.new("error", "condition-tag-malformed", uri, line, nil, message, Codes.fix("condition-tag-malformed"), nil)
475
+ elsif conditions && !conditions.include?(name)
476
+ on, off = tag.start_with?("@without:") ? %w[off on] : %w[on off]
477
+ findings << Finding.new("error", "condition-unknown", uri, line, nil,
478
+ %(#{tag} names the condition "#{name}", and no environment in nukadoko.program.rb declares it under conditions. ) +
479
+ "If #{name} was removed and its #{on} side kept, remove the tag, so the scenario holds everywhere; if its #{off} side was kept, delete the scenario.",
480
+ Codes.fix("condition-unknown"), nil)
481
+ end
482
+ end
483
+ end
484
+
71
485
  # A cycle never closes into a fixture bag, and a read-only step cannot
72
486
  # reach a part that writes: both can only end one way, so both are errors.
487
+ #: () -> void
73
488
  def check_parts
74
489
  @usable.each do |step|
75
490
  step.parts.reject { _1.is_a?(Class) && _1 < Step && @steps.include?(_1) }.each do |part|
@@ -91,6 +506,7 @@ module Nukadoko
91
506
  end
92
507
 
93
508
  # Each cycle once, named from the step whose walk first closed it.
509
+ #: () -> Array[Array[singleton(Step)]]
94
510
  def part_cycles
95
511
  done = []
96
512
  cycles = []
@@ -111,16 +527,28 @@ module Nukadoko
111
527
 
112
528
  # A scenario with steps of its own and no Then can never be judged on
113
529
  # an outcome. The Background's steps count toward the Then.
530
+ #: () -> void
114
531
  def check_shapes
115
- @scenarios.uniq { [_1.uri, _1.keyword_line] }.each do |scenario|
116
- next if scenario.steps.all?(&:background) || scenario.steps.any? { _1.kind == "Outcome" }
532
+ @scenarios.group_by { [_1.uri, _1.keyword_line] }.each_value do |rows|
533
+ scenario = rows.first
534
+ if rows.size > 1 && scenario.columns.none? { scenario.outline_name.include?("<#{_1}>") }
535
+ findings << Finding.new("warning", "outline-rows-share-name", scenario.uri, scenario.keyword_line, nil,
536
+ %(Scenario outline "#{scenario.name}" has #{rows.size} Examples rows, and its name uses none of the columns (#{scenario.columns.map { "<#{_1}>" }.join(", ")}), so every row is reported under the same name.),
537
+ "Add a column to the name, such as: #{scenario.name} <#{scenario.columns.first}>", nil)
538
+ end
539
+ own = scenario.steps.reject(&:background)
540
+ next if own.empty? || scenario.steps.any? { _1.kind.to_s == "Outcome" }
117
541
 
118
- findings << Finding.new("warning", "scenario-without-then", scenario.uri, scenario.keyword_line, nil,
119
- %(Scenario "#{scenario.name}" has no Then step, so nothing about its outcome is judged),
120
- "Add a Then step that states the outcome.")
542
+ message = if own.all? { _1.kind.to_s == "Unknown" }
543
+ %(Scenario "#{scenario.name}" has only * lines, so no line is in Then position and no claim is judged: it passes whenever its steps run without an error.)
544
+ else
545
+ %(Scenario "#{scenario.name}" has no Then step, so it passes whenever its steps run without an error, and no step checks an outcome.)
546
+ end
547
+ findings << Finding.new("warning", "scenario-without-then", scenario.uri, scenario.keyword_line, nil, message, Codes.fix("scenario-without-then"), nil)
121
548
  end
122
549
  end
123
550
 
551
+ #: () -> void
124
552
  def check_lines
125
553
  undefined = []
126
554
  @scenarios.each do |scenario|
@@ -128,46 +556,265 @@ module Nukadoko
128
556
  matches = Engine.matches(@usable, line.text)
129
557
  case matches.size
130
558
  when 0 then undefined << [scenario, line]
131
- when 1 then check_fill(scenario, line, *matches.first)
559
+ when 1
560
+ step, captures = matches.first
561
+ check_fill(scenario, line, step, captures)
562
+ check_position(scenario, line, step)
563
+ check_kinds(scenario, line, step, captures)
564
+ check_unfit_trees(scenario, line, step, captures)
565
+ check_poll(step)
132
566
  else
133
567
  findings << Finding.new("error", "ambiguous-step", scenario.uri, line.line, nil,
134
- "#{matches.size} steps match \"#{line.text}\"", "Make the patterns distinct.")
568
+ %("#{line.text}" matches more than one step: #{matches.map { _1.first.step_name }.join(", ")}), Codes.fix("ambiguous-step"), nil)
135
569
  end
136
570
  end
137
571
  end
572
+ @scenarios.each { check_from_order(_1) }
573
+ @scenarios.each { check_claim_sources(_1) }
138
574
  suppress_undefined(undefined)
575
+ @scenarios.each { judging_nothing(_1) }
576
+ end
577
+
578
+ # A scenario whose Then lines each bind one step, none of them a claim
579
+ # step, passes whenever its steps run.
580
+ #: (Scenario) -> void
581
+ def judging_nothing(scenario)
582
+ thens = scenario.steps.select { _1.kind.to_s == "Outcome" }
583
+ return if thens.empty?
584
+
585
+ steps = thens.map { Engine.matches(@usable, _1.text) }
586
+ return unless steps.all? { _1.size == 1 }
587
+ return if steps.any? { _1.first.first.claims }
588
+
589
+ findings << Finding.new("warning", "scenario-without-then", scenario.uri, thens.first.line, nil,
590
+ %(Scenario "#{scenario.name}" judges no claim: none of its Then lines binds a claim step, so it passes whenever its steps run without an error.),
591
+ Codes.fix("scenario-without-then"), nil)
592
+ end
593
+
594
+ # The steps with a pattern that no line binds alone. A step whose file
595
+ # failed to load is out of the vocabulary, so it is not unbound either.
596
+ #: () -> Array[singleton(Step)]
597
+ def unbound_steps
598
+ @unbound_steps ||= begin
599
+ bound = @scenarios.flat_map(&:steps).filter_map { |line| (m = Engine.matches(@usable, line.text)).size == 1 ? m.first.first : nil }
600
+ unread = findings.select { _1.code == "step-file-import-failed" }.map(&:step)
601
+ @steps.select(&:pattern).reject { bound.include?(_1) || unread.include?(_1.step_name) }.sort_by(&:file)
602
+ end
603
+ end
604
+
605
+ # A renamed sentence or pattern leaves one line undefined and one step
606
+ # unbound at once, so an undefined line names the unbound steps, at
607
+ # most three, beside the scaffold command that would write a duplicate.
608
+ #: () -> String
609
+ def unbound_suffix
610
+ steps = unbound_steps
611
+ return "" if steps.empty?
612
+
613
+ named = steps.first(3).map { %(#{_1.step_name} ("#{_1.pattern}", #{_1.file})) }
614
+ rest = steps.size - named.size
615
+ "; patterned steps no scanned feature line binds: #{rest.positive? ? "#{named.join(", ")}, and #{rest} more" : named.join(", ")}"
139
616
  end
140
617
 
141
618
  # While a step definition is broken, a line it would have matched looks
142
619
  # undefined. Saying so would send the reader after the wrong fix, so the
143
620
  # judgment waits for the broken definition, with one warning.
621
+ #: (Array[untyped]) -> void
144
622
  def suppress_undefined(undefined)
145
623
  broken = @steps - @usable
146
624
  if broken.any? && undefined.any?
147
625
  findings << Finding.about_step("warning", "undefined-step-check-suppressed", broken.first,
148
- "Suppressed #{undefined.size} undefined-step issues because #{broken.size} step file could not be read",
626
+ "Suppressed #{undefined.size} undefined-step #{undefined.size == 1 ? "issue" : "issues"} because #{broken.size} step #{broken.size == 1 ? "file" : "files"} could not be read. undefined-step judgment is on hold until the unreadable glue is fixed",
149
627
  "Correct the step-file-import-failed error, then run nuka check again.")
150
628
  return
151
629
  end
152
630
  undefined.each do |scenario, line|
153
631
  findings << Finding.new("error", "undefined-step", scenario.uri, line.line, nil,
154
- %(No step matches "#{line.text}"), "Add a step whose pattern matches the line.")
632
+ %(No step definition matches "#{line.text}"#{unbound_suffix}), nil, "nuka scaffold --feature #{Selection.shell_word(scenario.uri)}")
155
633
  end
156
634
  end
157
635
 
636
+ KEYWORD = { "Context" => "Given", "Action" => "When", "Outcome" => "Then" }.freeze
637
+
638
+ # Only a Then judges, so a claim step elsewhere and a step that runs in
639
+ # Then position are both mistakes.
640
+ #: (Scenario, PickleStep, singleton(Step)) -> void
641
+ def check_position(scenario, line, step)
642
+ then_line = line.kind.to_s == "Outcome"
643
+ if then_line && !step.claims
644
+ findings << Finding.new("error", "then-without-claims", scenario.uri, line.line, step.step_name,
645
+ %(Step "#{step.step_name}" is bound in Then position and runs instead of declaring claims. A Then judges through claims (docs/spec.md "Claims"); a step that only reads or records a value belongs in a Given or When),
646
+ Codes.fix("then-without-claims"), nil)
647
+ elsif !then_line && step.claims
648
+ findings << Finding.new("error", "claims-outside-then", scenario.uri, line.line, step.step_name,
649
+ %(Step "#{step.step_name}" declares claims and is bound in #{KEYWORD.fetch(line.kind.to_s, "*")} position. Only a Then judges, so a broken claim here would read as a setup that broke (docs/spec.md "Claims")),
650
+ Codes.fix("claims-outside-then"), nil)
651
+ end
652
+ end
653
+
654
+ # A page between two renders can show any state for one frame, so a
655
+ # claim step whose observe reaches a page, directly or through a
656
+ # project fixture, has to say whether it reads once or until its
657
+ # claims hold. Reported once for each step.
658
+ #: (singleton(Step)) -> void
659
+ def check_poll(step)
660
+ return unless step.claims && step.method_defined?(:observe) && step.poll.nil?
661
+ return if (@poll_reported ||= {}).key?(step)
662
+
663
+ @poll_reported[step] = true
664
+ return unless reaches_browser?(step.bag)
665
+
666
+ findings << Finding.about_step("error", "claim-poll-unstated", step,
667
+ %(Step "#{step.step_name}" observes a browser page and does not state poll. ) +
668
+ "Write poll: { timeout_ms } to read until every claim holds on two consecutive readings, or poll: false to read once",
669
+ Codes.fix("claim-poll-unstated"))
670
+ end
671
+
672
+ #: (Array[Symbol]) -> bool
673
+ def reaches_browser?(names)
674
+ fixtures = Nukadoko.project_fixtures
675
+ seen = [] #: Array[Symbol]
676
+ pending = names.dup
677
+ while (name = pending.shift)
678
+ next if seen.include?(name)
679
+
680
+ seen << name
681
+ return true if Vocabulary::BROWSER.include?(name)
682
+
683
+ pending.concat(fixtures[name].dependencies) if fixtures.key?(name)
684
+ end
685
+ false
686
+ end
687
+
688
+ # The key a table or docstring fills is what the line states; a claim
689
+ # step that neither compares a claim with it nor observes checks
690
+ # nothing the line said.
691
+ #: (untyped, untyped, singleton(Step), String) -> void
692
+ def check_unread(scenario, line, step, key)
693
+ claims = step.claims
694
+ return unless claims && !step.method_defined?(:observe) && !claim_keys_read(claims).include?(key)
695
+
696
+ attached = line.doc_string ? "docstring" : "table"
697
+ findings << Finding.new("error", "claim-sentence-unread", scenario.uri, line.line, step.step_name,
698
+ %(Step "#{step.step_name}": the #{attached} of the line fills args.#{key}, which no claim reads, and the step has no observe to receive it, so nothing checks the value the line states. Compare a claim with "#{key}", or take the #{attached} off the line),
699
+ Codes.fix("claim-sentence-unread"), nil)
700
+ end
701
+
702
+ # The args keys a step's claims read: the head of each actual path, a
703
+ # sentence key named as an expected value, and the head of a from
704
+ # expected path, in every claim and in each each's where and claims.
705
+ #: (Array[Hash[Symbol, untyped]]) -> Array[String]
706
+ def claim_keys_read(claims)
707
+ head = ->(path) { path.to_s.split(".").first.to_s }
708
+ expected = lambda do |value|
709
+ if value.is_a?(String) then value
710
+ elsif value.is_a?(Hash) && value[:from] then head.(value[:from])
711
+ end
712
+ end
713
+ claims.flat_map do |claim|
714
+ items = claim[:each] ? [*(claim[:each][:where] || []), *claim[:each][:claims]] : [claim]
715
+ [head.(claim[:actual]), *items.map { expected.(_1[:expected]) }]
716
+ end.compact.uniq
717
+ end
718
+
719
+ # The table or docstring fills the one required key no capture and no
720
+ # from speaks for, so zero or two such keys, or a key of a type the
721
+ # attachment can never be, fail binding with certainty.
722
+ #: (Scenario, PickleStep, singleton(Step), Hash[String, untyped]) -> void
158
723
  def check_fill(scenario, line, step, captures)
159
724
  missing = step.args.fields.map { _1.name.to_s } - captures.keys - step.from.keys
160
- missing = missing.drop(1) if (line.table || line.doc_string) && missing.any?
725
+ if line.table || line.doc_string
726
+ if missing.size != 1
727
+ detail = missing.empty? ? "every args key is already consumed by named captures or declared from" : "#{missing.size} args keys are left unconsumed (#{missing.join(", ")}); exactly one is required"
728
+ findings << Finding.new("error", "table-docstring-key-mismatch", scenario.uri, line.line, step.step_name,
729
+ %(Step "#{step.step_name}" has a table/docstring attached but #{detail}), Codes.fix("table-docstring-key-mismatch"), nil)
730
+ else
731
+ check_unread(scenario, line, step, missing.first.to_s)
732
+ if (message = attachment_mismatch(step, missing.first, line))
733
+ findings << Finding.new("error", "table-docstring-key-mismatch", scenario.uri, line.line, step.step_name, message, Codes.fix("table-docstring-key-mismatch"), nil)
734
+ end
735
+ end
736
+ return
737
+ end
161
738
  missing.each do |key|
162
739
  findings << Finding.new("error", "unfillable-required-key", scenario.uri, line.line, step.step_name,
163
- %(Step "#{step.step_name}"'s args key "#{key}" is required, but nothing on this line can fill it),
164
- "Capture the key in the pattern, attach a table, or make the key optional.")
740
+ %(Step "#{step.step_name}"'s args key "#{key}" is required, but nothing on this line can fill it: no named capture in the matched pattern binds it, there is no table/docstring attachment that resolves to filling it, and it has no declared from.#{key}. This line would fail args validation with certainty. Fix one of: add a named capture for "#{key}" to the step's pattern; attach a table/docstring that fills it; declare from.#{key}; or make "#{key}" optional in the step's args schema),
741
+ Codes.fix("unfillable-required-key"), nil)
742
+ end
743
+ end
744
+
745
+ # An is-a claim whose expected sentence key this line fills, through a
746
+ # capture, with a name that is no kind breaks on this line for certain.
747
+ # Only a plain string key read as it is or as text counts, so the value
748
+ # the claim reads is the captured text.
749
+ #: (Scenario, PickleStep, singleton(Step), Hash[String, untyped]) -> void
750
+ def check_kinds(scenario, line, step, captures)
751
+ (step.claims || []).each_with_index do |claim, index|
752
+ label = "claims[#{index}]"
753
+ entries = [[label, claim]] #: Array[[String, Hash[Symbol, untyped]]]
754
+ if (each = claim[:each])
755
+ entries = [*(each[:where] || []).each_with_index.map { ["#{label}.each.where[#{_2}]", _1] },
756
+ *each[:claims].each_with_index.map { ["#{label}.each.claims[#{_2}]", _1] }]
757
+ end
758
+ entries.each do |entry_label, entry|
759
+ key = entry[:expected]
760
+ next unless entry[:compare] == "is-a" && key.is_a?(String) && [nil, "text"].include?(entry[:expected_view])
761
+
762
+ named = captures[key]
763
+ next unless named.is_a?(String) && step.args[key]&.type == :string && Claims.value_kind(named).nil?
764
+
765
+ findings << Finding.new("error", "claim-kind-unknown", scenario.uri, line.line, step.step_name,
766
+ %(Step "#{step.step_name}"'s #{entry_label}.expected is args.#{key}, which this line fills with #{JSON.generate(named)}, and is-a names one of the kinds #{Claims::VALUE_KINDS.join(", ")}, so the claim would always break),
767
+ Codes.fix("claim-kind-unknown"), nil)
768
+ end
769
+ end
770
+ end
771
+
772
+ # A fits-aria-snapshot claim whose expected sentence key this line
773
+ # fills, through a capture or the docstring, with a tree the run breaks
774
+ # the claim on whatever the page shows: one that does not read, or one
775
+ # that names no node.
776
+ #: (Scenario, PickleStep, singleton(Step), Hash[String, untyped]) -> void
777
+ def check_unfit_trees(scenario, line, step, captures)
778
+ claims = step.claims or return
779
+ docstring_keys = line.doc_string ? step.args.fields.map { _1.name.to_s } - captures.keys - step.from.keys.map(&:to_s) : []
780
+ claims.each_with_index do |claim, index|
781
+ key = claim[:expected]
782
+ next if claim[:each] || claim[:compare] != "fits-aria-snapshot" || !key.is_a?(String)
783
+
784
+ captured = captures[key].is_a?(String) && step.args[key]&.type == :string ? captures[key] : nil
785
+ text = (captured || (docstring_keys == [key] ? line.doc_string : nil)) #: String?
786
+ next if text.nil?
787
+
788
+ problem = AriaSnapshot.expected_problem(text) or next
789
+ code = problem.first == :unreadable ? "claim-aria-snapshot-unreadable" : "claim-aria-snapshot-names-nothing"
790
+ findings << Finding.new("error", code, scenario.uri, line.line, step.step_name,
791
+ %(Step "#{step.step_name}"'s claims[#{index}].expected is args.#{key}, which this line's #{captured ? "capture" : "docstring"} fills, and #{AriaSnapshot.problem_reason(problem)}, so the claim would break whatever the page shows),
792
+ Codes.fix(code), nil)
793
+ end
794
+ end
795
+
796
+ #: (singleton(Step), String, PickleStep) -> String?
797
+ def attachment_mismatch(step, key, line)
798
+ field = step.args[key] or return nil
799
+ type = field.type
800
+ kind = case type
801
+ in Schema then "object"
802
+ in [:array, *] then "array"
803
+ in :number | :integer then "number"
804
+ in :boolean then "boolean"
805
+ else type.to_s
806
+ end
807
+ if line.table && type == :string
808
+ %(Step "#{step.step_name}" has a table attached, which fills args key "#{key}" as an array of rows (string[][]), but "#{key}" is a string. This line would fail args validation with certainty)
809
+ elsif line.doc_string && %w[array number boolean object].include?(kind)
810
+ %(Step "#{step.step_name}" has a docstring attached, which fills args key "#{key}" as a string, but "#{key}" is a #{kind}. This line would fail args validation with certainty)
165
811
  end
166
812
  end
167
813
  end
168
814
 
815
+ #: (Array[singleton(Step)], String) -> Array[[singleton(Step), Hash[String, untyped]]]
169
816
  def self.matches(steps, text)
170
- steps.filter_map { |step| step.pattern && (captures = Pattern.new(step.pattern).match(text)) && [step, captures] }
817
+ steps.filter_map { |step| (pattern = step.pattern) && (captures = Pattern.new(pattern).match(text)) && [step, captures] }
171
818
  end
172
819
  end
173
820
  end