yard-lint 1.13.1 → 1.14.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 (27) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +16 -0
  3. data/README.md +15 -8
  4. data/bin/yard-lint +24 -34
  5. data/lib/yard/lint/contracts/base.rb +20 -6
  6. data/lib/yard/lint/contracts/cli_options.rb +62 -0
  7. data/lib/yard/lint/contracts/config.rb +1 -1
  8. data/lib/yard/lint/executor/in_process_registry.rb +79 -9
  9. data/lib/yard/lint/formatters/relative_path.rb +32 -0
  10. data/lib/yard/lint/formatters/sarif.rb +2 -12
  11. data/lib/yard/lint/result_builder.rb +44 -15
  12. data/lib/yard/lint/results/aggregate.rb +4 -2
  13. data/lib/yard/lint/runner.rb +16 -14
  14. data/lib/yard/lint/stats_calculator.rb +59 -37
  15. data/lib/yard/lint/todo_generator.rb +33 -21
  16. data/lib/yard/lint/validators/documentation/undocumented_boolean_methods/messages_builder.rb +23 -0
  17. data/lib/yard/lint/validators/documentation/undocumented_boolean_methods/result.rb +1 -2
  18. data/lib/yard/lint/validators/documentation/undocumented_method_arguments/messages_builder.rb +10 -3
  19. data/lib/yard/lint/validators/documentation/undocumented_method_arguments/parser.rb +22 -3
  20. data/lib/yard/lint/validators/documentation/undocumented_method_arguments/validator.rb +46 -8
  21. data/lib/yard/lint/validators/documentation/undocumented_objects/parser.rb +15 -13
  22. data/lib/yard/lint/validators/documentation/undocumented_objects/result.rb +6 -1
  23. data/lib/yard/lint/validators/documentation/undocumented_objects/validator.rb +25 -2
  24. data/lib/yard/lint/validators/tags/example_style/validator.rb +7 -2
  25. data/lib/yard/lint/version.rb +1 -1
  26. data/lib/yard/lint.rb +15 -14
  27. metadata +4 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c16ecb156acd4118a7f6b11de2426ea4194789350e794b300a17a5608ed88c6f
4
- data.tar.gz: 1700cd0522e3fd7ba3041e170f7a6c6c2d407cac819808571e77907355bbb5ed
3
+ metadata.gz: f11bcba208f76430aa0d5d1693bae22825ef1cd6c4e6834e6dfd2e3ee0d2643e
4
+ data.tar.gz: 39e206a7e2599915d2ba5272074424e7db2905784ec44ebe245ee99f039a36a6
5
5
  SHA512:
6
- metadata.gz: 69ef7bafbb9c41c27857d0247c30fbcc5dc880663a16f4d90088afa594c4ea3fac8a447e66f041aae501786f91fa5b75a21d83f25679dbbfb8d1ff287709902b
7
- data.tar.gz: 7089ac1747b1473388efaafdb1e899ac3888fa71f31d696b408b5dcdc924ccd69ebaaa466efba90631e59d42cd9c87522d2ca482d5137e68f6dd089149da2474
6
+ metadata.gz: 75851ea554cecab09f9421fd6e28e7434a4eb8f22774d38830592e7f603270eaef02edcf4e12516f54a701d5781e97dd311cddc8e12441002188ab3d568eeae1
7
+ data.tar.gz: 7c1761efa56dc2fcb87088f42a0710ed073f54695948cdb919813c87e00b07bf54c45723db21aad2ede521601ce12f148e0d6bad8c528af37307ab88328b3000
data/CHANGELOG.md CHANGED
@@ -1,3 +1,19 @@
1
+ ## 1.14.0 (2026-11-24)
2
+ - **[Enhancement]** Files are now parsed with YARD once instead of twice when nothing in them depends on parse order (simplecov 1.3.2 `lib/`: about 5.9 s to 4.5 s). The second pass still runs, and the offenses stay the same, when the files define a `@!macro`, have an `alias`/`alias_method` or `module_function :name` written before its method, or a `module_function` copy that differs from its instance method (e.g. an undocumented `?` method).
3
+ - **[Enhancement]** Text and quickfix output now print offense paths relative to the current directory (`lib/foo.rb:10` instead of `/home/me/myproj/lib/foo.rb:10`), like RuboCop. Files outside the current directory keep their absolute path. JSON output and `Yard::Lint.run` results keep absolute paths.
4
+ - **[Enhancement]** `Documentation/UndocumentedMethodArguments` now names the arguments that have no `@param` tag (e.g. ``The `undocumented` method has no @param for: a, b``) instead of saying that some arguments are missing. Count-only mode (`CheckParameterNames: false`) keeps the old message. Its offenses now carry the method as their object, so SARIF fingerprints no longer change with the message.
5
+ - **[Bugfix]** Documentation coverage no longer counts methods that match `Documentation/UndocumentedObjects` `ExcludedMethods` (`initialize/0` by default; a config generated by `--init` also has `/^_/`). The setting was read but not applied, so excluded methods still lowered the coverage.
6
+ - **[Bugfix]** Documentation coverage under `--stdin` now counts the source read from stdin. Before, it read the file on disk, and a file that did not exist gave 100%.
7
+ - **[Bugfix]** Documentation coverage is now 0% instead of 100% when there are no documentable objects (e.g. every object is excluded, or the files define none). Behaviour change: `--min-coverage` / `MinCoverage` above 0 now fails such a run.
8
+ - **[Bugfix]** A documented `?` method without `@return` (found by `Documentation/UndocumentedBooleanMethods`) is now reported as ``The `Foo#bar?` method has no @return tag`` instead of ``Documentation required for `Foo#bar?` ``. It is still reported under `Documentation/UndocumentedObjects` with its severity.
9
+ - **[Bugfix]** Two diff mode flags together (e.g. `--diff main --staged`) now stop the run with `Error: Diff mode options are mutually exclusive: --diff, --staged` and exit 1. Before, the last flag silently won. `MinCoverage: .nan` in `.yard-lint.yml` is now rejected like other values outside 0-100.
10
+ - **[Bugfix]** `Documentation/UndocumentedObjects` no longer reports a constant hidden with `private_constant` in a file parsed before the file that defines it, when the files are parsed twice (e.g. they define a `@!macro`). The second pass made such a constant public again.
11
+ - **[Bugfix]** `--auto-gen-config` now writes `Documentation/UndocumentedBooleanMethods` offenses under `Documentation/UndocumentedBooleanMethods` instead of `Documentation/UndocumentedObjects`, and `--check-todo` no longer reports a `Documentation/UndocumentedBooleanMethods` entry as unused when it silences an offense.
12
+ - **[Bugfix]** `Documentation/UndocumentedObjects` now reports an undocumented `module_function` method once, on its public module method. Before, with `--private` it was also reported on its private instance copy (two offenses for one method), and a `?` method declared with `module_function :name` or `module_function def name` was reported only on the private copy, or not at all without `--private`.
13
+ - **[Bugfix]** `--min-coverage` outside 0-100 now stops the run with `Error: Invalid --min-coverage` and exit 1, like `MinCoverage` in `.yard-lint.yml`. Before, a value above 100 always failed and a negative value always passed.
14
+ - **[Bugfix]** SARIF output now gives a repository-relative URI for a file under a directory whose name starts with `..` (e.g. `..cache/foo.rb`) instead of keeping its absolute path.
15
+ - **[Bugfix]** A per-validator `Exclude` that matches every linted file is no longer ignored. The empty file selection was read as "all files", so `Documentation/UndocumentedBooleanMethods` reported excluded files on single-file and `--stdin` runs (editors, `--staged`, `--diff` with one changed file), and on any run whose files its `Exclude` covers fully.
16
+
1
17
  ## 1.13.1 (2026-11-02)
2
18
  - **[Bugfix]** `Documentation/UndocumentedBooleanMethods` no longer slows down with the square of the number of methods in a class or module (a module with 4200 methods: about 3 s to 40 ms). The `module_function` twin lookup it shares with the separator, `Tags/OverloadConsistency` and `Documentation/ReferenceTypo` validators now reads the registry by path instead of scanning the namespace's children.
3
19
 
data/README.md CHANGED
@@ -31,7 +31,7 @@ YARD-Lint validates your YARD documentation for:
31
31
  - **Performance** - In-process YARD execution with shared registry (~10x faster than shell-based execution)
32
32
  - **Incremental Adoption** - `--auto-gen-config` generates a baseline todo file to adopt on legacy codebases without fixing everything first
33
33
 
34
- **See the complete list:** [All Features](https://github.com/mensfeld/yard-lint/wiki/Features) | [37 Validators](https://github.com/mensfeld/yard-lint/wiki/Validators)
34
+ **See the complete list:** [All Features](https://github.com/mensfeld/yard-lint/wiki/Features) | [40 Validators](https://github.com/mensfeld/yard-lint/wiki/Validators)
35
35
 
36
36
  ## Installation
37
37
 
@@ -192,9 +192,9 @@ yard-lint --format quickfix lib/
192
192
  Example output:
193
193
 
194
194
  ```
195
- lib/foo.rb:42: E: Documentation/UndocumentedObjects: Class Foo is not documented
196
- lib/foo.rb:57: W: Tags/InvalidTypes: has invalid type(s): @return: `Sting`
197
- lib/bar.rb:12: C: Tags/Order: Tags are not in the correct order
195
+ lib/foo.rb:42: E: Documentation/UndocumentedObjects: Documentation required for `Foo`
196
+ lib/foo.rb:57: W: Tags/InvalidTypes: The `bar` has invalid type(s): @return: `string`
197
+ lib/bar.rb:12: C: Tags/Order: The `baz` has yard tags in an invalid order. Following tags need to be in the presented order: `param`, `return`.
198
198
  ```
199
199
 
200
200
  **Vim** — set `makeprg` and use `:make` to populate the quickfix list:
@@ -584,7 +584,7 @@ jobs:
584
584
  - name: Set up Ruby
585
585
  uses: ruby/setup-ruby@v1
586
586
  with:
587
- ruby-version: '3.2'
587
+ ruby-version: '3.4'
588
588
  bundler-cache: true
589
589
 
590
590
  - name: Run YARD-Lint on changed files
@@ -667,12 +667,19 @@ Every offense (in text, JSON, and quickfix output) includes a `validator` field
667
667
  "validator": "Documentation/OrphanedDocComment",
668
668
  "severity": "warning",
669
669
  "message": "Documentation comment with @param, @return is orphaned - YARD will ignore it",
670
- "location": "lib/my_class.rb",
670
+ "location": "/home/me/myproj/lib/my_class.rb",
671
671
  "location_line": 42
672
672
  }
673
673
  ```
674
674
 
675
- The text formatter also shows the validator path (e.g., `[Documentation/OrphanedDocComment]`) instead of just the short offense name.
675
+ The text formatter also shows the validator path instead of just the short offense name:
676
+
677
+ ```
678
+ [W] lib/my_class.rb:42
679
+ Documentation/OrphanedDocComment: Documentation comment with @param, @return is orphaned - YARD will ignore it
680
+ ```
681
+
682
+ JSON output keeps the absolute `location`. Text and quickfix output print the path relative to the current directory when the file is inside it, and the absolute path otherwise.
676
683
 
677
684
  ## Documentation
678
685
 
@@ -681,7 +688,7 @@ The text formatter also shows the validator path (e.g., `[Documentation/Orphaned
681
688
  - **[Wiki Home](https://github.com/mensfeld/yard-lint/wiki)** - Full documentation
682
689
  - **[Installation](https://github.com/mensfeld/yard-lint/wiki/Installation)** - Installation guide
683
690
  - **[Configuration](https://github.com/mensfeld/yard-lint/wiki/Configuration)** - Complete configuration reference
684
- - **[Validators](https://github.com/mensfeld/yard-lint/wiki/Validators)** - All 37 validators documented
691
+ - **[Validators](https://github.com/mensfeld/yard-lint/wiki/Validators)** - All 40 validators documented
685
692
  - **[Features](https://github.com/mensfeld/yard-lint/wiki/Features)** - All features explained
686
693
 
687
694
  ### Workflows
data/bin/yard-lint CHANGED
@@ -47,14 +47,17 @@ begin
47
47
 
48
48
  opts.on('--diff [REF]', 'Lint only files changed since REF (default: main/master auto-detected)') do |ref|
49
49
  diff_mode = { mode: :ref, base_ref: ref }
50
+ (options[:diff_flags] ||= []) << '--diff'
50
51
  end
51
52
 
52
53
  opts.on('--staged', 'Lint only staged files (git index)') do
53
54
  diff_mode = { mode: :staged }
55
+ (options[:diff_flags] ||= []) << '--staged'
54
56
  end
55
57
 
56
58
  opts.on('--changed', 'Lint only uncommitted files') do
57
59
  diff_mode = { mode: :changed }
60
+ (options[:diff_flags] ||= []) << '--changed'
58
61
  end
59
62
 
60
63
  opts.separator ''
@@ -144,31 +147,21 @@ rescue OptionParser::ParseError => e
144
147
  exit 1
145
148
  end
146
149
 
147
- # Report one or more unknown validator names with "did you mean" suggestions,
148
- # the full list of available validators, and a pointer to --explain. Shared by
149
- # --only and --explain so the two stay consistent.
150
- report_unknown_validators = lambda do |names|
151
- checker = DidYouMean::SpellChecker.new(dictionary: Yard::Lint::ConfigLoader::ALL_VALIDATORS)
152
- messages = names.map do |name|
153
- suggestions = checker.correct(name)
154
- suggestions.any? ? " #{name} (did you mean: #{suggestions.first}?)" : " #{name}"
155
- end
156
- puts 'Error: Unknown validator(s):'
157
- puts messages.join("\n")
158
- puts "\nAvailable validators:"
159
- Yard::Lint::ConfigLoader::ALL_VALIDATORS.each { |v| puts " #{v}" }
160
- puts "\nRun `yard-lint --explain VALIDATOR` to see what a validator checks."
150
+ # Validate the given options with the CLI options contract, exiting on errors.
151
+ # Each option is checked where it is used, so earlier errors keep precedence.
152
+ validate_options = lambda do |*keys|
153
+ result = Yard::Lint::Contracts::CliOptions.new.call(options.slice(*keys))
154
+ next if result.success?
155
+
156
+ result.errors.each_value { |message| puts "Error: #{message}" }
157
+ exit 1
161
158
  end
162
159
 
163
160
  # Apply --only filter if provided, exiting on unknown validator names
164
161
  apply_only = lambda do |config|
165
162
  next unless options[:only]
166
163
 
167
- unknown = options[:only] - Yard::Lint::ConfigLoader::ALL_VALIDATORS
168
- if unknown.any?
169
- report_unknown_validators.call(unknown)
170
- exit 1
171
- end
164
+ validate_options.call(:only)
172
165
  config.only_validators = options[:only]
173
166
  end
174
167
 
@@ -191,15 +184,14 @@ end
191
184
 
192
185
  # Handle --explain flag (early exit; needs no config or path)
193
186
  if options[:explain]
194
- name = options[:explain]
195
- unless Yard::Lint::ConfigLoader::ALL_VALIDATORS.include?(name)
196
- report_unknown_validators.call([name])
197
- exit 1
198
- end
199
- puts Yard::Lint::Explainer.call(name)
187
+ validate_options.call(:explain)
188
+ puts Yard::Lint::Explainer.call(options[:explain])
200
189
  exit 0
201
190
  end
202
191
 
192
+ # Reject two diff mode flags instead of silently running the last one
193
+ validate_options.call(:diff_flags)
194
+
203
195
  # Disambiguate `--diff PATH`. `--diff [REF]` takes an optional argument, so
204
196
  # `yard-lint --diff lib/` makes OptionParser consume `lib/` as the REF, leaving
205
197
  # no PATH (the run then tries `git diff lib/...HEAD` and fails). When the --diff
@@ -328,13 +320,9 @@ config.min_coverage = options[:min_coverage] if options[:min_coverage]
328
320
 
329
321
  apply_only.call(config)
330
322
 
331
- # Validate the output format before doing any (potentially long) work, rather
332
- # than running the whole lint and only then rejecting an unknown format.
333
- valid_formats = %w[text json quickfix sarif]
334
- if options[:format] && !valid_formats.include?(options[:format])
335
- puts "Error: Unknown format '#{options[:format]}'. Valid formats: #{valid_formats.join(', ')}"
336
- exit 1
337
- end
323
+ # Validate the output format and coverage before doing any (potentially long)
324
+ # work, rather than running the whole lint and only then rejecting them.
325
+ validate_options.call(:format, :min_coverage)
338
326
 
339
327
  # Suppress progress for machine-readable formats to avoid contaminating output
340
328
  options[:progress] = false if %w[quickfix sarif].include?(options[:format]) && options[:progress].nil?
@@ -383,7 +371,8 @@ when 'quickfix'
383
371
  result.offenses.each do |offense|
384
372
  char = severity_char.call(offense[:severity])
385
373
  message = offense[:message].to_s.gsub(/\n/, ' ')
386
- puts "#{offense[:location]}:#{offense[:location_line]}: #{char}: #{offense[:validator]}: #{message}"
374
+ location = Yard::Lint::Formatters::RelativePath.call(offense[:location])
375
+ puts "#{location}:#{offense[:location_line]}: #{char}: #{offense[:validator]}: #{message}"
387
376
  end
388
377
  exit result.exit_code
389
378
  when 'sarif'
@@ -438,7 +427,8 @@ when 'text', nil
438
427
  puts "Found #{result.count} offense(s):\n\n"
439
428
 
440
429
  result.offenses.each do |offense|
441
- puts "[#{severity_char.call(offense[:severity])}] #{offense[:location]}:#{offense[:location_line]}"
430
+ location = Yard::Lint::Formatters::RelativePath.call(offense[:location])
431
+ puts "[#{severity_char.call(offense[:severity])}] #{location}:#{offense[:location_line]}"
442
432
  puts " #{offense[:validator]}: #{offense[:message]}"
443
433
  puts
444
434
  end
@@ -2,9 +2,10 @@
2
2
 
3
3
  module Yard
4
4
  module Lint
5
- # Contracts that validate the configuration structure and values
5
+ # Contracts that validate the configuration and the command line options
6
6
  module Contracts
7
- # Base for the configuration contracts with the helpers that build their error messages
7
+ # Base for the configuration and command line options contracts with the helpers that
8
+ # build their error messages
8
9
  class Base < Contractable::Contract
9
10
  # Valid boolean values
10
11
  BOOLEAN_VALUES = [true, false].freeze
@@ -19,6 +20,13 @@ module Yard
19
20
  lines.compact.join("\n")
20
21
  end
21
22
 
23
+ # Checks a minimum documentation coverage, shared by MinCoverage and --min-coverage
24
+ # @param value [Object] coverage value to check
25
+ # @return [Boolean] true when the value is a number between 0 and 100
26
+ def valid_coverage?(value)
27
+ value.is_a?(Numeric) && value >= 0 && value <= 100
28
+ end
29
+
22
30
  # Converts errors of a nested contract into virtual rule errors of the parent contract
23
31
  # @param result [Contractable::Result] nested contract validation result
24
32
  # @return [Array<Array>] error pairs with the nested error scope as their path
@@ -26,15 +34,21 @@ module Yard
26
34
  result.errors.map { |scope, error| [[scope], error] }
27
35
  end
28
36
 
37
+ # Finds the validator name closest to an invalid one using did_you_mean
38
+ # @param invalid_name [String] invalid validator name
39
+ # @return [String, nil] closest validator name or nil when there is no similar one
40
+ def closest_validator_name(invalid_name)
41
+ DidYouMean::SpellChecker.new(dictionary: ConfigLoader::ALL_VALIDATORS).correct(invalid_name).first
42
+ end
43
+
29
44
  # Suggest similar validator names using did_you_mean
30
45
  # @param invalid_name [String] invalid validator name
31
46
  # @return [String] suggestion line
32
47
  def suggest_validator_name(invalid_name)
33
- checker = DidYouMean::SpellChecker.new(dictionary: ConfigLoader::ALL_VALIDATORS)
34
- suggestions = checker.correct(invalid_name)
48
+ suggestion = closest_validator_name(invalid_name)
35
49
 
36
- if suggestions.any?
37
- " Did you mean: #{suggestions.first}?"
50
+ if suggestion
51
+ " Did you mean: #{suggestion}?"
38
52
  else
39
53
  ' See https://github.com/mensfeld/yard-lint/wiki/Validators ' \
40
54
  'for all available validators'
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yard
4
+ module Lint
5
+ module Contracts
6
+ # Validates the command line options parsed by `bin/yard-lint`
7
+ class CliOptions < Base
8
+ # Valid output formats
9
+ VALID_FORMATS = %w[text json quickfix sarif].freeze
10
+
11
+ class << self
12
+ private
13
+
14
+ # Builds the unknown validators message with "did you mean" suggestions, the full list
15
+ # of available validators and a pointer to --explain
16
+ # @param names [Array<String>] unknown validator names
17
+ # @return [String] multi-line error message
18
+ def unknown_validators(names)
19
+ names_lines = names.map do |name|
20
+ suggestion = closest_validator_name(name)
21
+ suggestion ? " #{name} (did you mean: #{suggestion}?)" : " #{name}"
22
+ end
23
+
24
+ message(
25
+ 'Unknown validator(s):',
26
+ *names_lines,
27
+ '',
28
+ 'Available validators:',
29
+ *ConfigLoader::ALL_VALIDATORS.map { |validator| " #{validator}" },
30
+ '',
31
+ 'Run `yard-lint --explain VALIDATOR` to see what a validator checks.'
32
+ )
33
+ end
34
+ end
35
+
36
+ optional(:format) do |format|
37
+ VALID_FORMATS.include?(format) ||
38
+ "Unknown format '#{format}'. Valid formats: #{VALID_FORMATS.join(', ')}"
39
+ end
40
+
41
+ optional(:min_coverage) do |min_cov|
42
+ valid_coverage?(min_cov) ||
43
+ message("Invalid --min-coverage: '#{min_cov}'", ' Must be a number between 0 and 100')
44
+ end
45
+
46
+ optional(:diff_flags) do |flags|
47
+ flags.uniq.size < 2 ||
48
+ "Diff mode options are mutually exclusive: #{flags.uniq.join(', ')}"
49
+ end
50
+
51
+ optional(:only) do |names|
52
+ unknown = names - ConfigLoader::ALL_VALIDATORS
53
+ unknown.empty? || unknown_validators(unknown)
54
+ end
55
+
56
+ optional(:explain) do |name|
57
+ ConfigLoader::ALL_VALIDATORS.include?(name) || unknown_validators([name])
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -40,7 +40,7 @@ module Yard
40
40
  end
41
41
 
42
42
  optional('MinCoverage') do |min_cov|
43
- !min_cov || (min_cov.is_a?(Numeric) && !(min_cov < 0 || min_cov > 100)) ||
43
+ !min_cov || valid_coverage?(min_cov) ||
44
44
  message("Invalid MinCoverage: '#{min_cov}'", ' Must be a number between 0 and 100')
45
45
  end
46
46
 
@@ -9,6 +9,14 @@ module Yard
9
9
  # Manages shared YARD::Registry for in-process execution.
10
10
  # Ensures files are parsed once and shared across all validators.
11
11
  class InProcessRegistry
12
+ # Statements YARD registers an alias for
13
+ ALIAS_KEYWORDS = %w[alias alias_method].freeze
14
+
15
+ # A keyword or method name in an alias statement
16
+ ALIAS_TOKEN = /[^\s,():"']+/
17
+
18
+ private_constant :ALIAS_KEYWORDS, :ALIAS_TOKEN
19
+
12
20
  # @return [Array<String>] warnings captured during parsing
13
21
  attr_reader :warnings
14
22
 
@@ -51,15 +59,26 @@ module Yard
51
59
  @warnings = capture_warnings { parse_source_string(source, virtual_path) }
52
60
  else
53
61
  # First pass: parse all files to process directive definitions
54
- YARD.parse(files)
62
+ @warnings = capture_warnings { YARD.parse(files) }
55
63
 
56
- # Clear checksums to force reparsing without clearing the registry.
57
- # This allows macro definitions from the first pass to be available
58
- # during the second pass, enabling proper directive expansion regardless of parse order.
59
- YARD::Registry.checksums.clear
64
+ if second_pass_needed?
65
+ # The first pass parses a constant defined in a later file before
66
+ # applying `private_constant`. The second pass applies it first and
67
+ # then the constant definition makes it public again.
68
+ private_constants = YARD::Registry.all(:constant).select do |constant|
69
+ constant.visibility == :private
70
+ end
60
71
 
61
- # Second pass: reparse files now that all directive definitions are available
62
- @warnings = capture_warnings { YARD.parse(files) }
72
+ # Clear checksums to force reparsing without clearing the registry.
73
+ # This keeps the objects of the first pass available to the second,
74
+ # so macros and copied methods resolve regardless of parse order.
75
+ YARD::Registry.checksums.clear
76
+
77
+ # Second pass: reparse files now that all definitions are available
78
+ @warnings = capture_warnings { YARD.parse(files) }
79
+
80
+ private_constants.each { |constant| constant.visibility = :private }
81
+ end
63
82
  end
64
83
 
65
84
  @parsed = true
@@ -86,7 +105,8 @@ module Yard
86
105
  # Get objects filtered for a specific validator
87
106
  # @param visibility [Symbol] visibility filter, either :all or :public
88
107
  # @param file_excludes [Array<String>] glob patterns for files to exclude
89
- # @param file_selection [Array<String>, nil] specific files to include (nil = all files)
108
+ # @param file_selection [Array<String>, nil] specific files to include (nil = all files,
109
+ # empty = no files)
90
110
  # @return [Array<YARD::CodeObjects::Base>]
91
111
  def objects_for_validator(visibility:, file_excludes: [], file_selection: nil)
92
112
  objects = all_objects
@@ -99,7 +119,7 @@ module Yard
99
119
  end
100
120
 
101
121
  # Filter by file selection (if provided)
102
- if file_selection && !file_selection.empty?
122
+ if file_selection
103
123
  expanded_selection = file_selection.to_set { |f| File.expand_path(f) }
104
124
  objects = objects.select do |obj|
105
125
  obj.file && expanded_selection.include?(File.expand_path(obj.file))
@@ -159,6 +179,56 @@ module Yard
159
179
  warn "[YARD::Lint] Failed to load .yardopts tags: #{e.message}" if ENV['DEBUG']
160
180
  end
161
181
 
182
+ # Tells whether the first pass left objects that depend on parse order.
183
+ # A macro may be used before its definition; an alias or `module_function :name`
184
+ # copies a method that may be defined later, and YARD gives a module function
185
+ # copy of a `?` method an inferred `@return` that its instance twin gets only on
186
+ # a reparse. Skipping the second pass in these cases would change the offenses.
187
+ # @return [Boolean]
188
+ def second_pass_needed?
189
+ return true unless YARD::Registry.all(:macro).empty?
190
+
191
+ YARD::Registry.all(:method).any? do |method|
192
+ stale_alias?(method) || stale_module_function_copy?(method)
193
+ end
194
+ end
195
+
196
+ # YARD drops the alias entry once the aliased method is defined, so an alias
197
+ # registered before its method is known only by what the alias handler leaves:
198
+ # the alias statement as source (a resolved alias copies the method's source)
199
+ # and a bare `def <alias>` signature. YARD never resolves a module scope alias,
200
+ # so a reparse would not change it.
201
+ # @param method [YARD::CodeObjects::MethodObject]
202
+ # @return [Boolean] true when the method is an alias of a method parsed later
203
+ def stale_alias?(method)
204
+ return false if method.module_function?
205
+ return false unless method.signature == "def #{method.name}"
206
+
207
+ source = method.source.to_s
208
+ return false unless source.start_with?('alias')
209
+
210
+ # `alias new old`, `alias_method :new, :old`
211
+ keyword, _new_name, old_name = source.scan(ALIAS_TOKEN)
212
+ return false unless ALIAS_KEYWORDS.include?(keyword) && old_name
213
+
214
+ # Looked up by path: a children scan per alias is quadratic in the
215
+ # number of methods of a namespace
216
+ target = YARD::Registry.at(method.path.delete_suffix(method.name.to_s) + old_name)
217
+ target.is_a?(YARD::CodeObjects::MethodObject)
218
+ end
219
+
220
+ # @param method [YARD::CodeObjects::MethodObject]
221
+ # @return [Boolean] true when a module function copy differs from its instance method
222
+ def stale_module_function_copy?(method)
223
+ return false unless method.module_function?
224
+
225
+ twin = YARD::Registry.at("#{method.namespace.path}#{YARD::CodeObjects::ISEP}#{method.name}")
226
+ return false unless twin.is_a?(YARD::CodeObjects::MethodObject)
227
+
228
+ twin.docstring.all != method.docstring.all ||
229
+ twin.tags.map(&:tag_name) != method.tags.map(&:tag_name)
230
+ end
231
+
162
232
  # Parse Ruby source from a string and register objects under a virtual path.
163
233
  # YARD::Parser::SourceParser#parse accepts a StringIO but keeps @file as '(stdin)'
164
234
  # unless we set it explicitly before parsing.
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yard
4
+ module Lint
5
+ module Formatters
6
+ # Shortens offense locations for display
7
+ module RelativePath
8
+ class << self
9
+ # Path relative to base_dir when the file is inside it. A path outside
10
+ # base_dir keeps its original value rather than becoming a `../` path.
11
+ # @param location [String, nil] the offense location path
12
+ # @param base_dir [String] directory the path is made relative to
13
+ # @return [String] a relative path where possible
14
+ def call(location, base_dir = Dir.pwd)
15
+ path = location.to_s
16
+ return path if path.empty?
17
+
18
+ base = File.absolute_path(base_dir)
19
+ absolute = File.absolute_path(path, base)
20
+ return absolute.delete_prefix("#{base}/") if absolute.start_with?("#{base}/")
21
+
22
+ relative = Pathname.new(absolute).relative_path_from(Pathname.new(base)).to_s
23
+ relative.start_with?('..') ? path : relative
24
+ rescue ArgumentError
25
+ # relative_path_from raises across platforms/mixed roots; fall back.
26
+ path
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
@@ -187,21 +187,11 @@ module Yard
187
187
  line.positive? ? line : 1
188
188
  end
189
189
 
190
- # Make a path repository-relative so GitHub maps it onto a file. Paths
191
- # already relative are kept; a path outside base_dir keeps its original
192
- # value rather than emitting a `../` or absolute URI.
190
+ # Make a path repository-relative so GitHub maps it onto a file.
193
191
  # @param location [String, nil] the offense location path
194
192
  # @return [String] a relative URI where possible
195
193
  def relative_uri(location)
196
- path = location.to_s
197
- return path if path.empty?
198
-
199
- absolute = File.absolute_path(path, @base_dir)
200
- relative = Pathname.new(absolute).relative_path_from(Pathname.new(@base_dir)).to_s
201
- relative.start_with?('..') ? path : relative
202
- rescue ArgumentError
203
- # relative_path_from raises across platforms/mixed roots; fall back.
204
- path
194
+ RelativePath.call(location, @base_dir)
205
195
  end
206
196
 
207
197
  # The validator's default severity, from a defaults-only config, for the
@@ -26,13 +26,38 @@ module Yard
26
26
 
27
27
  # Handle composite validators (those that combine multiple validators)
28
28
  unless validator_cfg.combines_with.empty?
29
- return build_composite_result(validator_module, validator_cfg, raw)
29
+ return build_composite_result(validator_name, validator_module, validator_cfg, raw)
30
30
  end
31
31
 
32
32
  # Handle standard validators (single or multi-parser)
33
33
  build_standard_result(validator_module, validator_cfg, raw)
34
34
  end
35
35
 
36
+ # Build results keyed by the validator that found the offenses
37
+ # A composite result is split into one result per member (the parent and each child),
38
+ # so a child's offenses are keyed by the child's name.
39
+ # @api private
40
+ # @param validator_name [String] validator name (e.g., 'Tags/Order')
41
+ # @param raw [Hash] raw results from all validators
42
+ # @return [Hash{String => Results::Base}] validator names to their results
43
+ def build_by_validator(validator_name, raw)
44
+ validator_cfg = ConfigLoader.validator_config(validator_name)
45
+ if validator_cfg.nil? || validator_cfg.combines_with.empty?
46
+ result = build(validator_name, raw)
47
+ return result ? { validator_name => result } : {}
48
+ end
49
+
50
+ validator_module = ConfigLoader.validator_module(validator_name)
51
+ return {} unless validator_module
52
+ return {} if reported_by_composite?(validator_name)
53
+
54
+ composite_members(validator_name, validator_module, validator_cfg)
55
+ .each_with_object({}) do |(name, mod, cfg), results|
56
+ parsed = parse_validator_output(mod, cfg, raw)
57
+ results[name] = validator_module::Result.new(parsed, config) unless parsed.empty?
58
+ end
59
+ end
60
+
36
61
  private
37
62
 
38
63
  # Check if a composite parent reports this validator's offenses
@@ -50,29 +75,33 @@ module Yard
50
75
  end
51
76
 
52
77
  # Build result for a composite validator (combines multiple validators)
78
+ # @param validator_name [String] composite validator name
53
79
  # @param validator_module [Module] validator namespace module
54
80
  # @param validator_cfg [Class] validator config class
55
81
  # @param raw [Hash] raw results
56
82
  # @return [Results::Base, nil] composite result or nil
57
- def build_composite_result(validator_module, validator_cfg, raw)
58
- # Collect all child validators (modules + configs)
83
+ def build_composite_result(validator_name, validator_module, validator_cfg, raw)
84
+ combined = composite_members(validator_name, validator_module, validator_cfg)
85
+ .flat_map { |_name, mod, cfg| parse_validator_output(mod, cfg, raw) }
86
+
87
+ return nil if combined.empty?
88
+
89
+ validator_module::Result.new(combined, config)
90
+ end
91
+
92
+ # Collect the members of a composite validator: the parent and each known child
93
+ # @param validator_name [String] composite validator name
94
+ # @param validator_module [Module] validator namespace module
95
+ # @param validator_cfg [Class] validator config class
96
+ # @return [Array<Array(String, Module, Class)>] name, module and config of each member
97
+ def composite_members(validator_name, validator_module, validator_cfg)
59
98
  children = validator_cfg.combines_with.filter_map do |child_name|
60
99
  child_mod = ConfigLoader.validator_module(child_name)
61
100
  child_cfg = ConfigLoader.validator_config(child_name)
62
- [child_mod, child_cfg] if child_mod && child_cfg
101
+ [child_name, child_mod, child_cfg] if child_mod && child_cfg
63
102
  end
64
103
 
65
- # All validators (parent + children)
66
- all_validators = [[validator_module, validator_cfg]] + children
67
-
68
- # Parse output from all validators
69
- combined = all_validators.flat_map do |mod, cfg|
70
- parse_validator_output(mod, cfg, raw)
71
- end
72
-
73
- return nil if combined.empty?
74
-
75
- validator_module::Result.new(combined, config)
104
+ [[validator_name, validator_module, validator_cfg]] + children
76
105
  end
77
106
 
78
107
  # Build result for a standard validator (single or multi-parser)
@@ -19,10 +19,12 @@ module Yard
19
19
  # @param results [Array<Results::Base>] array of validator result objects
20
20
  # @param config [Config, nil] configuration object
21
21
  # @param files [Array<String>, nil] array of files that were analyzed
22
- def initialize(results, config = nil, files = nil)
22
+ # @param source [String, nil] in-memory source of the single file (--stdin)
23
+ def initialize(results, config = nil, files = nil, source: nil)
23
24
  @results = Array(results)
24
25
  @config = config
25
26
  @files = Array(files)
27
+ @source = source
26
28
  end
27
29
 
28
30
  # Get all offenses from all validators
@@ -74,7 +76,7 @@ module Yard
74
76
 
75
77
  return nil unless @config && !@files.empty?
76
78
 
77
- calculator = StatsCalculator.new(@config, @files)
79
+ calculator = StatsCalculator.new(@config, @files, source: @source)
78
80
  @documentation_coverage = calculator.calculate
79
81
  end
80
82