Class: Rubycli::Documentation::MetadataParser

Inherits:
Object
  • Object
show all
Includes:
TypeUtils
Defined in:
lib/rubycli/documentation/metadata_parser.rb

Constant Summary collapse

INLINE_TYPE_HINTS =
%w[
  String
  Integer
  Float
  Numeric
  Boolean
  TrueClass
  FalseClass
  Symbol
  Array
  Hash
  JSON
  Time
  Date
  DateTime
  BigDecimal
  File
  Pathname
  nil
].freeze

Instance Method Summary collapse

Methods included from TypeUtils

analyze_placeholder, boolean_string?, boolean_type?, convert_boolean, default_placeholder_for, determine_requires_value, infer_types_from_placeholder, nil_type?, normalize_long_option, normalize_short_option, normalize_type_list, normalize_type_token, parse_list

Constructor Details

#initialize(environment:) ⇒ MetadataParser

Returns a new instance of MetadataParser.



11
12
13
# File 'lib/rubycli/documentation/metadata_parser.rb', line 11

def initialize(environment:)
  @environment = environment
end

Instance Method Details

#align_and_validate_parameter_docs(method_obj, metadata, defaults) ⇒ Object



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'lib/rubycli/documentation/metadata_parser.rb', line 587

def align_and_validate_parameter_docs(method_obj, , defaults)
  positional_defs = [:positionals].dup
  positional_map = {}
  existing_options = [:options].dup
  options_by_keyword = existing_options.each_with_object({}) { |opt, memo| memo[opt.keyword] = opt }
  ordered_options = []

  source_file = nil
  source_line = nil
  source_file, source_line = method_obj.source_location if method_obj.respond_to?(:source_location)
  line_for_comment = source_line ? [source_line - 1, 1].max : nil

  method_obj.parameters.each do |type, name|
    case type
    when :req, :opt, :rest
      doc = take_positional_definition(positional_defs, name)
      if doc
        doc.param_name = name
        doc.default_value = type == :rest ? [] : defaults[name]
        positional_map[name] = doc
      else
        @environment.handle_documentation_issue(
          "Documentation is missing for positional argument '#{name}'",
          file: source_file,
          line: line_for_comment
        )
        unless @environment.doc_check_mode?
          fallback = PositionalDefinition.new(
            placeholder: name.to_s,
            label: name.to_s.upcase,
            types: [type == :rest ? 'String[]' : 'String'],
            description: nil,
            param_name: name,
            default_value: type == :rest ? [] : defaults[name],
            inline_type_annotation: false,
            inline_type_text: nil,
            doc_format: :auto_generated,
            allowed_values: []
          )
          [:positionals] << fallback
          positional_map[name] = fallback
        end
      end
    when :keyreq, :key
      if (option = options_by_keyword[name])
        ordered_options << option unless ordered_options.include?(option)
      else
        @environment.handle_documentation_issue(
          "Documentation is missing for keyword argument ':#{name}'",
          file: source_file,
          line: line_for_comment
        )
        unless @environment.doc_check_mode?
          fallback_option = build_auto_option_definition(name)
          ordered_options << fallback_option if fallback_option
        end
      end
    end
  end

  [:options] = ordered_options + (existing_options - ordered_options)

  unless positional_defs.empty?
    extra = positional_defs.map(&:placeholder).join(', ')
    @environment.handle_documentation_issue(
      "Extra positional argument comments were found: #{extra}",
      file: source_file,
      line: line_for_comment
    )

    [:positionals] -= positional_defs

    positional_defs.each do |doc|
      detail_line = detail_line_for_extra_positional(doc)
      next unless detail_line

      [:detail_lines] ||= []
      [:detail_lines] << detail_line
    end
  end

  [:positionals_map] = positional_map

  [:options].each do |opt|
    next unless defaults.key?(opt.keyword)

    opt.default_value = defaults[opt.keyword]
    if boolean_default?(opt.default_value)
      opt.boolean_flag = true
      opt.requires_value = false
      if opt.doc_format == :auto_generated
        opt.value_name = nil
        opt.types = ['Boolean']
      end
    elsif opt.boolean_flag && !TypeUtils.boolean_string?(opt.default_value)
      opt.boolean_flag = false
      opt.requires_value = true
      opt.value_name ||= default_placeholder_for(opt.keyword)
      opt.types = ['String'] if opt.types.nil? || opt.types.empty?
    end
  end
end

#allowed_value_suggestions(token) ⇒ Object



896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
# File 'lib/rubycli/documentation/metadata_parser.rb', line 896

def allowed_value_suggestions(token)
  stripped = token.to_s.strip
  return [] if stripped.empty?

  candidates = []
  if stripped.match?(/\A[a-z0-9._-]+\z/i)
    candidates << ":#{stripped.downcase}"
    candidates << stripped.downcase.inspect
  end
  return [] if candidates.empty?

  require 'did_you_mean'
  checker = DidYouMean::SpellChecker.new(dictionary: candidates)
  checker.correct(stripped).take(2)
rescue LoadError, NameError
  candidates.first(1)
end

#array_inner_type_token(token) ⇒ Object



1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1023

def array_inner_type_token(token)
  return nil unless token

  stripped = token.to_s.strip
  if stripped.end_with?('[]')
    stripped[0..-3]
  elsif stripped.start_with?('Array<') && stripped.end_with?('>')
    stripped[6..-2].strip
  end
end

#audit_literal_entry(token, source_file, line_number) ⇒ Object



487
488
489
490
491
492
# File 'lib/rubycli/documentation/metadata_parser.rb', line 487

def audit_literal_entry(token, source_file, line_number)
  literal_entry = literal_entry_from_token(token)
  return if literal_entry

  warn_unknown_allowed_value(token, source_file, line_number)
end

#audit_single_token(token, source_file, line_number, literal_context) ⇒ Object



456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/rubycli/documentation/metadata_parser.rb', line 456

def audit_single_token(token, source_file, line_number, literal_context)
  normalized = token.to_s.strip
  return if normalized.empty?

  if literal_hint_token?(normalized)
    expand_annotation_token(normalized).each do |entry|
      audit_literal_entry(entry, source_file, line_number)
    end
    return
  end

  literal_entry = literal_entry_from_token(normalized)
  return if literal_entry

  if literal_context && literal_token_candidate?(normalized,
                                                 include_uppercase: true) && !known_type_token?(normalized)
    warn_unknown_allowed_value(normalized, source_file, line_number)
    return
  end

  if literal_token_candidate?(normalized, include_uppercase: false)
    warn_unknown_allowed_value(normalized, source_file, line_number)
    return
  end

  return if inline_type_hint?(normalized)
  return if known_type_token?(normalized)

  warn_unknown_type_token(normalized, source_file, line_number)
end

#audit_type_annotation_tokens(tokens, method_obj) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/rubycli/documentation/metadata_parser.rb', line 441

def audit_type_annotation_tokens(tokens, method_obj)
  return if tokens.nil? || tokens.empty?
  return unless @environment.doc_check_mode?

  source_file, line_number = doc_issue_location(method_obj)
  literal_tokens_present = Array(tokens).any? do |token|
    literal_entry = literal_entry_from_token(token)
    literal_entry || literal_hint_token?(token)
  end

  Array(tokens).each do |token|
    audit_single_token(token, source_file, line_number, literal_tokens_present)
  end
end

#balanced_signature?(signature) ⇒ Boolean

Returns:

  • (Boolean)


535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'lib/rubycli/documentation/metadata_parser.rb', line 535

def balanced_signature?(signature)
  def_index = signature.index(/\bdef\b/)
  return false unless def_index

  open_parens = signature.count('(')
  close_parens = signature.count(')')

  if open_parens.zero?
    !signature.strip.end_with?(',')
  else
    open_parens == close_parens && signature.rindex(')') > signature.index('(')
  end
end

#boolean_default?(default_value) ⇒ Boolean

Only a literal true/false default turns an option into a boolean flag. Values such as 0/1 are truthy for TypeUtils.boolean_string?, but they are ordinary defaults for numeric options, so they must keep accepting a value.

Returns:

  • (Boolean)


693
694
695
696
697
# File 'lib/rubycli/documentation/metadata_parser.rb', line 693

def boolean_default?(default_value)
  return true if [true, false].include?(default_value)

  %w[true false].include?(default_value.to_s.strip.downcase)
end

#build_auto_option_definition(keyword) ⇒ Object



1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1191

def build_auto_option_definition(keyword)
  long_option = "--#{keyword.to_s.tr('_', '-')}"
  placeholder = default_placeholder_for(keyword)
  build_option_definition(
    keyword,
    long_option,
    nil,
    placeholder,
    [],
    nil,
    inline_type_annotation: false,
    doc_format: :auto_generated,
    allowed_values: []
  )
end

#build_option_definition(keyword, long_option, short_option, value_name, types, description, inline_type_annotation: false, doc_format: nil, allowed_values: nil) ⇒ Object



1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1130

def build_option_definition(
  keyword,
  long_option,
  short_option,
  value_name,
  types,
  description,
  inline_type_annotation: false,
  doc_format: nil,
  allowed_values: nil
)
  normalized_long = normalize_long_option(long_option)
  normalized_short = normalize_short_option(short_option)
  value_placeholder = value_name&.strip
  value_placeholder = nil if value_placeholder && value_placeholder.empty?
  description_text = description&.strip
  description_text = nil if description_text && description_text.empty?

  placeholder_info = analyze_placeholder(value_placeholder)
  normalized_types = normalize_type_list(types)
  inferred_types = infer_types_from_placeholder(normalized_types, placeholder_info)
  inferred_types = ['Boolean'] if inferred_types.empty? && value_placeholder.nil?

  optional_value = placeholder_info[:optional]
  boolean_flag = !optional_value && inferred_types.any? { |type| boolean_type?(type) }
  requires_value = determine_requires_value(
    value_placeholder: value_placeholder,
    types: inferred_types,
    boolean_flag: boolean_flag,
    optional_value: optional_value
  )

  if value_placeholder.nil? && !boolean_flag && requires_value
    value_placeholder = default_placeholder_for(keyword)
    placeholder_info = analyze_placeholder(value_placeholder)
    optional_value = placeholder_info[:optional]
  end

  inline_type_text = inline_type_annotation ? format_inline_type_label(inferred_types) : nil

  OptionDefinition.new(
    keyword: keyword,
    long: normalized_long,
    short: normalized_short,
    value_name: value_placeholder,
    types: inferred_types,
    description: description_text,
    requires_value: requires_value,
    boolean_flag: boolean_flag,
    optional_value: optional_value,
    inline_type_annotation: inline_type_annotation,
    inline_type_text: inline_type_text,
    doc_format: doc_format,
    allowed_values: normalize_allowed_values(allowed_values)
  )
end

#combine_bracketed_tokens(tokens) ⇒ Object



1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1081

def combine_bracketed_tokens(tokens)
  combined = []
  buffer = nil
  closing = nil

  tokens.each do |token|
    next if token.nil?

    if buffer
      buffer << ' ' unless token.empty?
      buffer << token
      if closing && token.include?(closing)
        combined << buffer
        buffer = nil
        closing = nil
      end
    elsif token.start_with?('[') && !token.include?(']')
      buffer = token.dup
      closing = ']'
    elsif token.start_with?('(') && !token.include?(')')
      buffer = token.dup
      closing = ')'
    elsif token.start_with?('%') && token.include?('[') && !token.include?(']')
      buffer = token.dup
      closing = ']'
    else
      combined << token
    end
  end

  combined << buffer if buffer
  combined
end

#detail_line_for_extra_positional(doc) ⇒ Object



711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
# File 'lib/rubycli/documentation/metadata_parser.rb', line 711

def detail_line_for_extra_positional(doc)
  return nil unless doc

  parts = []
  placeholder = doc.placeholder || doc.label
  placeholder = placeholder.to_s.strip
  parts << placeholder unless placeholder.empty?

  type_text = doc.inline_type_text
  type_text = "[#{doc.types.join(', ')}]" if (!type_text || type_text.empty?) && doc.types && !doc.types.empty?
  parts << type_text if type_text && !type_text.empty?

  description = doc.description.to_s.strip
  parts << description unless description.empty?

  text = parts.join(' ').strip
  text.empty? ? nil : text
end

#doc_issue_location(method_obj) ⇒ Object



433
434
435
436
437
438
439
# File 'lib/rubycli/documentation/metadata_parser.rb', line 433

def doc_issue_location(method_obj)
  return [nil, nil] unless method_obj.respond_to?(:source_location)

  source_file, source_line = method_obj.source_location
  line_number = source_line ? [source_line - 1, 1].max : nil
  [source_file, line_number]
end

#empty_metadataObject



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rubycli/documentation/metadata_parser.rb', line 15

def 
  {
    options: [],
    returns: [],
    summary: nil,
    summary_lines: [],
    detail_lines: [],
    positionals: [],
    positionals_map: {}
  }
end

#expand_annotation_token(token) ⇒ Object



783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'lib/rubycli/documentation/metadata_parser.rb', line 783

def expand_annotation_token(token)
  return [] unless token

  stripped = token.strip
  return [] if stripped.empty?

  if stripped.start_with?('%i[') && stripped.end_with?(']')
    inner = stripped[3..-2]
    inner.split(/\s+/).map { |entry| ":#{entry}" }
  elsif stripped.start_with?('%I[') && stripped.end_with?(']')
    inner = stripped[3..-2]
    inner.split(/\s+/).map { |entry| ":#{entry}" }
  elsif stripped.start_with?('%w[') && stripped.end_with?(']')
    inner = stripped[3..-2]
    inner.split(/\s+/)
  elsif stripped.start_with?('%W[') && stripped.end_with?(']')
    inner = stripped[3..-2]
    inner.split(/\s+/)
  else
    [stripped]
  end
end

#extract_parameter_defaults(method_obj) ⇒ Object



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/rubycli/documentation/metadata_parser.rb', line 494

def extract_parameter_defaults(method_obj)
  location = method_obj.source_location
  return {} unless location

  file, line_no = location
  return {} unless file && line_no

  lines = File.readlines(file)
  signature = String.new
  index = line_no - 1
  while index < lines.length
    line = lines[index]
    signature << line
    break if balanced_signature?(signature)

    index += 1
  end

  params_source = extract_params_from_signature(signature)
  return {} unless params_source

  split_parameters(params_source).each_with_object({}) do |param_token, memo|
    case param_token
    when /^\*\*/
      next
    when /^\*/
      next
    when /^&/
      next
    else
      if (match = param_token.match(/\A([a-zA-Z0-9_]+)\s*=\s*(.+)\z/))
        memo[match[1].to_sym] = match[2].strip
      elsif (match = param_token.match(/\A([a-zA-Z0-9_]+):\s*(.+)\z/))
        memo[match[1].to_sym] = match[2].strip
      end
    end
  end
rescue Errno::ENOENT
  {}
end

#extract_params_from_signature(signature) ⇒ Object



549
550
551
552
553
554
555
556
557
558
559
# File 'lib/rubycli/documentation/metadata_parser.rb', line 549

def extract_params_from_signature(signature)
  return nil unless (def_match = signature.match(/\bdef\b\s+[^(\s]+\s*(\((.*)\))?/m))

  if def_match[1]
    def_match[1][1..-2]

  else
    signature_after_def = signature.sub(/.*\bdef\b\s+[^(\s]+\s*/m, '')
    signature_after_def.split("\n").first&.strip
  end
end

#format_inline_type_label(types) ⇒ Object



1115
1116
1117
1118
1119
1120
1121
1122
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1115

def format_inline_type_label(types)
  return nil if types.nil? || types.empty?

  unique_types = types.reject(&:empty?).uniq
  return nil if unique_types.empty?

  "[#{unique_types.join(', ')}]"
end

#inline_type_hint?(token) ⇒ Boolean

Returns:

  • (Boolean)


1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1001

def inline_type_hint?(token)
  normalized = normalize_type_token(token)
  return false if normalized.empty?

  base = if normalized.include?('<') && normalized.end_with?('>')
           normalized.split('<').first
         elsif normalized.end_with?('[]')
           normalized[0..-3]
         else
           normalized
         end

  INLINE_TYPE_HINTS.include?(base)
end

#known_type_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


986
987
988
989
990
991
992
993
994
995
996
997
998
999
# File 'lib/rubycli/documentation/metadata_parser.rb', line 986

def known_type_token?(token)
  return false unless token

  normalized = normalize_type_token(token)
  return false if normalized.empty?

  return true if primitive_type_token?(normalized)

  if (inner = array_inner_type_token(normalized))
    return known_type_token?(inner)
  end

  !safe_constant_lookup(normalized).nil?
end

#literal_entry_from_token(token) ⇒ Object



806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# File 'lib/rubycli/documentation/metadata_parser.rb', line 806

def literal_entry_from_token(token)
  return nil unless token

  stripped = token.strip
  return nil if stripped.empty?

  stripped = stripped[1..] if stripped.start_with?('[') && !stripped.end_with?(']')
  stripped = stripped[0...-1] if stripped.end_with?(']') && !stripped.include?('[')

  lowered = stripped.downcase
  return { kind: :literal, value: nil } if %w[nil null ~].include?(lowered)
  return { kind: :literal, value: true } if lowered == 'true'
  return { kind: :literal, value: false } if lowered == 'false'

  if stripped.start_with?(':')
    sym_name = stripped[1..]
    return nil if sym_name.nil? || sym_name.empty?

    return { kind: :literal, value: sym_name.to_sym }
  end

  if stripped.start_with?('"') && stripped.end_with?('"') && stripped.length >= 2
    return { kind: :literal, value: stripped[1..-2] }
  end

  if stripped.start_with?("'") && stripped.end_with?("'") && stripped.length >= 2
    return { kind: :literal, value: stripped[1..-2] }
  end

  return { kind: :literal, value: Integer(stripped) } if stripped.match?(/\A-?\d+\z/)

  return { kind: :literal, value: Float(stripped) } if stripped.match?(/\A-?\d+\.\d+\z/)

  return { kind: :literal, value: stripped } if stripped.match?(/\A[a-z0-9._-]+\z/)

  nil
rescue ArgumentError
  nil
end

#literal_hint_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1049

def literal_hint_token?(token)
  return false unless token

  stripped = token.to_s.strip
  return false if stripped.empty?

  stripped.start_with?('%i[') ||
    stripped.start_with?('%I[') ||
    stripped.start_with?('%w[') ||
    stripped.start_with?('%W[')
end

#literal_token_candidate?(token, include_uppercase: false) ⇒ Boolean

Returns:

  • (Boolean)


846
847
848
849
850
851
852
853
854
855
856
857
858
859
# File 'lib/rubycli/documentation/metadata_parser.rb', line 846

def literal_token_candidate?(token, include_uppercase: false)
  return false unless token

  stripped = token.strip
  return false if stripped.empty?

  lowered = stripped.downcase
  return true if %w[true false nil null ~].include?(lowered)
  return true if stripped.start_with?(':', '"', "'")
  return true if stripped.match?(/\A-?\d/)

  pattern = include_uppercase ? /\A[a-z0-9._-]+\z/i : /\A[a-z0-9._-]+\z/
  stripped.match?(pattern)
end

#merge_allowed_values(primary, additional) ⇒ Object



776
777
778
779
780
781
# File 'lib/rubycli/documentation/metadata_parser.rb', line 776

def merge_allowed_values(primary, additional)
  return Array(additional) if primary.nil? || primary.empty?
  return Array(primary) if additional.nil? || additional.empty?

  (primary + additional).uniq
end

#method_accepts_keyword?(method_obj, keyword) ⇒ Boolean

Returns:

  • (Boolean)


1124
1125
1126
1127
1128
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1124

def method_accepts_keyword?(method_obj, keyword)
  params = method_obj.parameters
  keyword_names = params.select { |type, _| %i[key keyreq keyrest].include?(type) }.map { |_, name| name }
  keyword_names.include?(keyword) || params.any? { |type, _| type == :keyrest }
end

#normalize_allowed_values(values) ⇒ Object



1187
1188
1189
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1187

def normalize_allowed_values(values)
  Array(values).compact.uniq
end

#option_to_positional_definition(option) ⇒ Object



1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1207

def option_to_positional_definition(option)
  placeholder = option.value_name || default_placeholder_for(option.keyword)
  PositionalDefinition.new(
    placeholder: placeholder,
    label: placeholder,
    types: option.types,
    description: option.description,
    param_name: option.keyword,
    default_value: option.default_value,
    inline_type_annotation: option.inline_type_annotation,
    inline_type_text: option.inline_type_text,
    doc_format: option.doc_format,
    allowed_values: option.allowed_values
  )
end

#parameter_role(method_obj, keyword) ⇒ Object



1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1061

def parameter_role(method_obj, keyword)
  return nil unless method_obj.respond_to?(:parameters)

  symbol = keyword.to_sym
  method_obj.parameters.each do |type, name|
    next unless name == symbol

    case type
    when :req, :opt, :rest
      return :positional
    when :keyreq, :key
      return :keyword
    else
      return nil
    end
  end

  nil
end

#parse(comment_lines, method_obj) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/rubycli/documentation/metadata_parser.rb', line 27

def parse(comment_lines, method_obj)
   = 
  return  if comment_lines.empty?

  summary_compact_lines = []
  summary_display_lines = []
  detail_lines = []
  summary_phase = true
  deferred_positional = nil

  comment_lines.each do |content|
    stripped = content.strip
    if summary_phase && stripped.empty?
      summary_display_lines << ''
      next
    end

    if (option = parse_tagged_param_line(stripped, method_obj))
      if option.is_a?(OptionDefinition)
        if method_accepts_keyword?(method_obj, option.keyword)
          [:options].reject! { |existing| existing.keyword == option.keyword }
          [:options] << option
        else
          [:positionals] << option_to_positional_definition(option)
        end
      elsif option.is_a?(PositionalDefinition)
        [:positionals] << option
      end
      summary_phase = false
      next
    end

    if (return_meta = (stripped, method_obj))
      [:returns] << return_meta
      summary_phase = false
      next
    end

    if (option = parse_tagless_option_line(stripped, method_obj))
      [:options].reject! { |existing| existing.keyword == option.keyword }
      [:options] << option
      summary_phase = false
      next
    end

    if (positional = parse_positional_line(stripped, method_obj))
      # An untyped uppercase line opening a doc block ("JSON output
      # formatter for reports.") reads exactly like a placeholder. Hold on
      # to it and decide once the whole block is known.
      if summary_phase && deferred_positional.nil? && !positional.inline_type_annotation
        deferred_positional = { content: content, stripped: stripped, definition: positional }
      else
        [:positionals] << positional
      end
      summary_phase = false
      next
    end
    if summary_phase
      summary_display_lines << content.rstrip
      summary_compact_lines << stripped unless stripped.empty?
    else
      detail_lines << content.rstrip
    end
  end

  if deferred_positional
    if positional_documentation_needed?(method_obj, [:positionals].size)
      [:positionals].unshift(deferred_positional[:definition])
    else
      summary_display_lines << deferred_positional[:content].rstrip
      summary_compact_lines << deferred_positional[:stripped]
    end
  end

  summary_text = summary_compact_lines.join(' ')
  summary_text = nil if summary_text.empty?
  [:summary] = summary_text
  [:summary_lines] = trim_blank_edges(summary_display_lines)
  [:detail_lines] = trim_blank_edges(detail_lines)

  defaults = extract_parameter_defaults(method_obj)
  align_and_validate_parameter_docs(method_obj, , defaults)

  
end

#parse_positional_line(line, method_obj) ⇒ Object



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/rubycli/documentation/metadata_parser.rb', line 357

def parse_positional_line(line, method_obj)
  return nil if line.start_with?('--') || line.start_with?('-')

  tokens = combine_bracketed_tokens(line.split(/\s+/))
  placeholder = tokens.shift
  return nil unless placeholder

  clean_placeholder = placeholder.delete('[]')
  return nil unless placeholder_token?(clean_placeholder)

  type_token = nil
  type_token = tokens.shift if tokens.first && type_token_candidate?(tokens.first)

  # Summaries such as "A command that ..." or "I keep ..." start with an
  # all-uppercase single letter and would otherwise take over the first
  # positional argument. Require a type annotation to use one as a
  # placeholder; "A [String] ..." keeps working.
  return nil if type_token.nil? && clean_placeholder.match?(/\A[A-Z]\z/)

  description = tokens.join(' ').strip
  description = nil if description.empty?

  raw_types = parse_type_annotation(type_token)
  audit_type_annotation_tokens(raw_types, method_obj)
  types, allowed_values = partition_type_tokens(raw_types)
  placeholder_info = analyze_placeholder(placeholder)
  inferred_types = infer_types_from_placeholder(
    normalize_type_list(types),
    placeholder_info,
    include_optional_boolean: false
  )

  label = clean_placeholder

  inline_annotation = !type_token.nil?
  inline_text = inline_annotation ? format_inline_type_label(inferred_types) : nil

  PositionalDefinition.new(
    placeholder: placeholder,
    label: label.empty? ? placeholder : label,
    types: inferred_types,
    description: description,
    inline_type_annotation: inline_annotation,
    inline_type_text: inline_text,
    doc_format: :rubycli,
    allowed_values: allowed_values
  )
end

#parse_return_metadata(line, method_obj) ⇒ Object



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/rubycli/documentation/metadata_parser.rb', line 406

def (line, method_obj)
  yard_match = /\A@return\s+\[([^\]]+)\](?:\s+(.*))?\z/.match(line)
  if yard_match
    types = parse_type_annotation(yard_match[1])
    audit_type_annotation_tokens(types, method_obj)
    description = yard_match[2]&.strip
    return ReturnDefinition.new(types: types, description: description)
  end

  shorthand_match = /\A=>\s+(\[[^\]]+\]|[^\s]+)(?:\s+(.*))?\z/.match(line)
  if shorthand_match
    types = parse_type_annotation(shorthand_match[1])
    audit_type_annotation_tokens(types, method_obj)
    description = shorthand_match[2]&.strip
    return ReturnDefinition.new(types: types, description: description)
  end

  return unless line.start_with?('return ')

  stripped = line.sub(/\Areturn\s+/, '')
  type_token, description = stripped.split(/\s+/, 2)
  types = parse_type_annotation(type_token)
  audit_type_annotation_tokens(types, method_obj)
  description = description&.strip
  ReturnDefinition.new(types: types, description: description)
end

#parse_tagged_param_line(line, method_obj) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/rubycli/documentation/metadata_parser.rb', line 134

def parse_tagged_param_line(line, method_obj)
  return nil unless line.start_with?('@param')

  nil
  source_line = nil
  _, source_line = method_obj.source_location if method_obj.respond_to?(:source_location)
  line_number = source_line ? [source_line - 1, 1].max : nil

  unless @environment.allow_param_comments?
    source_file, = method_obj.source_location
    @environment.handle_documentation_issue(
      '@param notation is disabled. Enable it via ENV RUBYCLI_ALLOW_PARAM_COMMENT=ON.',
      file: source_file,
      line: line_number
    )
    return nil if @environment.doc_check_mode?
  end

  pattern = /\A@param\s+([a-zA-Z0-9_]+)(?:\s+\[([^\]]+)\])?(?:\s+\(([^)]+)\))?(?:\s+(.*))?\z/
  match = pattern.match(line)
  return nil unless match

  param_name = match[1]
  param_symbol = param_name.to_sym
  type_str = match[2]
  option_tokens = combine_bracketed_tokens(match[3]&.split(/\s+/) || [])
  description = match[4]&.strip
  description = nil if description && description.empty?

  raw_types = parse_type_annotation(type_str)
  audit_type_annotation_tokens(raw_types, method_obj)
  types, allowed_values = partition_type_tokens(raw_types)

  long_option = nil
  short_option = nil
  value_name = nil
  type_token = nil

  unless option_tokens.empty?
    normalized = option_tokens.flat_map { |token| token.split('/') }
    normalized.each do |token|
      token_without_at = token.start_with?('@') ? token[1..] : token
      if token.start_with?('--')
        if (eq_index = token.index('='))
          long_option = token[0...eq_index]
          inline_value = token[(eq_index + 1)..]
          if value_name.nil? && inline_value && !inline_value.strip.empty?
            value_name = inline_value.strip
            next
          end
        else
          long_option = token
        end
      elsif token.start_with?('-')
        if (eq_index = token.index('='))
          short_option = token[0...eq_index]
          inline_value = token[(eq_index + 1)..]
          if value_name.nil? && inline_value && !inline_value.strip.empty?
            value_name = inline_value.strip
            next
          end
        else
          short_option = token
        end
      elsif value_name.nil? && placeholder_token?(token_without_at)
        value_name = token_without_at
      elsif type_token.nil? && type_token_candidate?(token)
        type_token = token
      elsif value_name.nil?
        value_name = token_without_at
      end
    end
  end

  long_option ||= "--#{param_name.tr('_', '-')}"
  role = parameter_role(method_obj, param_symbol)
  if value_name.nil?
    if role == :positional
      value_name = default_placeholder_for(param_symbol)
    elsif !types&.any? { |entry| boolean_type?(entry) }
      # Most keywords expect a value; boolean flags should be documented with [Boolean].
      value_name = default_placeholder_for(param_symbol)
    end
  end

  if (types.nil? || types.empty?) && type_token
    inline_raw_types = parse_type_annotation(type_token)
    audit_type_annotation_tokens(inline_raw_types, method_obj)
    inline_types, inline_allowed = partition_type_tokens(inline_raw_types)
    types = inline_types
    allowed_values = merge_allowed_values(allowed_values, inline_allowed)
  end

  # TODO: Derive primitive types from Ruby default values when explicit hints are absent.
  option_def = build_option_definition(
    param_symbol,
    long_option,
    short_option,
    value_name,
    types,
    description,
    inline_type_annotation: !type_token.nil?,
    doc_format: :tagged_param,
    allowed_values: allowed_values
  )

  if role == :positional
    placeholder = option_def.value_name || default_placeholder_for(option_def.keyword)
    return PositionalDefinition.new(
      placeholder: placeholder,
      label: placeholder,
      types: option_def.types,
      description: option_def.description,
      param_name: param_symbol,
      doc_format: option_def.doc_format,
      allowed_values: option_def.allowed_values
    )
  elsif role == :keyword
    return option_def
  end

  unless method_accepts_keyword?(method_obj, param_symbol)
    placeholder = option_def.value_name || default_placeholder_for(option_def.keyword)
    return PositionalDefinition.new(
      placeholder: placeholder,
      label: placeholder,
      types: option_def.types,
      description: option_def.description,
      param_name: param_symbol,
      doc_format: option_def.doc_format,
      allowed_values: option_def.allowed_values
    )
  end

  option_def
end

#parse_tagless_option_line(line, method_obj) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/rubycli/documentation/metadata_parser.rb', line 271

def parse_tagless_option_line(line, method_obj)
  return nil unless line.start_with?('--') || line.start_with?('-')

  raw_tokens = combine_bracketed_tokens(line.split(/\s+/))
  tokens = raw_tokens.flat_map do |token|
    if token.include?('/') && !token.start_with?('[')
      token.split('/')
    else
      [token]
    end
  end

  long_option = nil
  short_option = nil
  inline_value_from_long = nil
  inline_value_from_short = nil
  remaining = []

  tokens.each do |token|
    if long_option.nil? && token.start_with?('--')
      if (eq_index = token.index('='))
        long_option = token[0...eq_index]
        inline_value_from_long = token[(eq_index + 1)..]
      else
        long_option = token
      end
      next
    end

    if short_option.nil? && token.start_with?('-') && !token.start_with?('--')
      if (eq_index = token.index('='))
        short_option = token[0...eq_index]
        inline_value_from_short = token[(eq_index + 1)..]
      else
        short_option = token
      end
      next
    end

    remaining << token
  end

  return nil unless long_option

  type_token = nil
  value_name = [inline_value_from_long, inline_value_from_short].compact.map(&:strip).find { |val| !val.empty? }
  description_tokens = []

  remaining.each do |token|
    token_without_at = token.start_with?('@') ? token[1..] : token

    if value_name.nil? && placeholder_token?(token_without_at)
      value_name = token_without_at
      next
    end

    if type_token.nil? && type_token_candidate?(token)
      type_token = token
      next
    end

    description_tokens << token
  end

  description = description_tokens.join(' ').strip
  description = nil if description.empty?
  raw_types = parse_type_annotation(type_token)
  audit_type_annotation_tokens(raw_types, method_obj)
  types, allowed_values = partition_type_tokens(raw_types)

  keyword = long_option.delete_prefix('--').tr('-', '_').to_sym
  return nil unless method_accepts_keyword?(method_obj, keyword)

  build_option_definition(
    keyword,
    long_option,
    short_option,
    value_name,
    types,
    description,
    inline_type_annotation: !type_token.nil?,
    doc_format: :rubycli,
    allowed_values: allowed_values
  )
end

#parse_type_annotation(type_str) ⇒ Object



751
752
753
754
755
756
757
758
759
760
# File 'lib/rubycli/documentation/metadata_parser.rb', line 751

def parse_type_annotation(type_str)
  return [] unless type_str

  cleaned = type_str.strip
  cleaned = cleaned.delete_prefix('@')
  cleaned = cleaned[1..-2].strip if cleaned.start_with?('(') && cleaned.end_with?(')')
  cleaned = cleaned[1..-2] if cleaned.start_with?('[') && cleaned.end_with?(']')
  cleaned = cleaned.sub(/\Atype\s*:\s*/i, '')
  cleaned.split(/[,|]/).map { |token| normalize_type_token(token) }.reject(&:empty?)
end

#partition_type_tokens(tokens) ⇒ Object



762
763
764
765
766
767
768
769
770
771
772
773
774
# File 'lib/rubycli/documentation/metadata_parser.rb', line 762

def partition_type_tokens(tokens)
  normalized = Array(tokens).dup
  allowed = []

  normalized.each do |token|
    expand_annotation_token(token).each do |expanded|
      literal_entry = literal_entry_from_token(expanded)
      allowed << literal_entry if literal_entry
    end
  end

  [normalized, allowed.compact.uniq]
end

#placeholder_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
# File 'lib/rubycli/documentation/metadata_parser.rb', line 939

def placeholder_token?(token)
  return false unless token

  candidate = token.strip.delete_prefix('@')
  return false if candidate.empty?

  optional = candidate.start_with?('[') && candidate.end_with?(']')
  candidate = candidate[1..-2].strip if optional
  return false if candidate.empty?

  candidate = candidate.gsub(/[,|]/, '')
  return false if candidate.empty?

  ellipsis = candidate.end_with?('...')
  candidate = candidate[0..-4] if ellipsis
  candidate = candidate.strip
  return false if candidate.empty?

  if candidate.start_with?('<') && candidate.end_with?('>')
    inner = candidate[1..-2]
    inner.match?(/\A[0-9A-Za-z][0-9A-Za-z._-]*\z/)
  else
    cleaned = candidate.gsub(/[^A-Za-z0-9_]/, '')
    return false if cleaned.empty?

    cleaned == cleaned.upcase && cleaned.match?(/[A-Z]/)
  end
end

#positional_documentation_needed?(method_obj, documented_count) ⇒ Boolean

True while the documented placeholders do not yet cover every positional parameter, which is what tells a real placeholder line from prose.

Returns:

  • (Boolean)


115
116
117
118
119
120
# File 'lib/rubycli/documentation/metadata_parser.rb', line 115

def positional_documentation_needed?(method_obj, documented_count)
  return true unless method_obj.respond_to?(:parameters)

  positional_count = method_obj.parameters.count { |type, _| %i[req opt rest].include?(type) }
  documented_count < positional_count
end

#primitive_type_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


1016
1017
1018
1019
1020
1021
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1016

def primitive_type_token?(token)
  return false if token.nil? || token.empty?

  base = token.to_s
  INLINE_TYPE_HINTS.include?(base) || %w[NilClass Fixnum Decimal Struct].include?(base)
end

#reset_type_dictionary_cache!Object



935
936
937
# File 'lib/rubycli/documentation/metadata_parser.rb', line 935

def reset_type_dictionary_cache!
  @type_dictionary = nil
end

#safe_constant_lookup(name) ⇒ Object



1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
# File 'lib/rubycli/documentation/metadata_parser.rb', line 1034

def safe_constant_lookup(name)
  parts = name.to_s.split('::').reject(&:empty?)
  return nil if parts.empty?

  context = Object
  parts.each do |const_name|
    return nil unless context.const_defined?(const_name, false)

    context = context.const_get(const_name)
  end
  context
rescue NameError
  nil
end

#split_parameters(param_string) ⇒ Object



561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/rubycli/documentation/metadata_parser.rb', line 561

def split_parameters(param_string)
  return [] unless param_string

  tokens = []
  current = String.new
  depth = 0
  param_string.each_char do |char|
    case char
    when '(', '[', '{'
      depth += 1
    when ')', ']', '}'
      depth -= 1 if depth > 0
    when ','
      if depth.zero?
        tokens << current.strip unless current.strip.empty?
        current = String.new
        next
      end
    end
    current << char
  end

  tokens << current.strip unless current.strip.empty?
  tokens
end

#take_positional_definition(positional_defs, parameter_name) ⇒ Object



699
700
701
702
703
704
705
706
707
708
709
# File 'lib/rubycli/documentation/metadata_parser.rb', line 699

def take_positional_definition(positional_defs, parameter_name)
  tagged_index = positional_defs.index do |definition|
    definition.doc_format == :tagged_param && definition.param_name == parameter_name
  end
  return positional_defs.delete_at(tagged_index) if tagged_index

  tagless_index = positional_defs.index { |definition| definition.doc_format != :tagged_param }
  return positional_defs.delete_at(tagless_index) if tagless_index

  nil
end

#trim_blank_edges(lines) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
# File 'lib/rubycli/documentation/metadata_parser.rb', line 122

def trim_blank_edges(lines)
  return [] if lines.nil? || lines.empty?

  first = lines.index { |line| line && !line.strip.empty? }
  return [] unless first

  last = lines.rindex { |line| line && !line.strip.empty? }
  return [] unless last

  lines[first..last]
end

#type_dictionaryObject



914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
# File 'lib/rubycli/documentation/metadata_parser.rb', line 914

def type_dictionary
  return @type_dictionary if defined?(@type_dictionary) && @type_dictionary

  builtins = (INLINE_TYPE_HINTS + %w[NilClass Fixnum Decimal Struct]).uniq
  constant_names = []
  begin
    ObjectSpace.each_object(Module) do |mod|
      name = mod.name
      next unless name && !name.empty?

      constant_names << name
      parts = name.split('::')
      constant_names << parts.last if parts.size > 1
    end
  rescue StandardError
    constant_names = Object.constants.map(&:to_s)
  end

  @type_dictionary = (builtins + constant_names).map(&:to_s).map(&:strip).reject(&:empty?).uniq
end

#type_token_candidate?(token) ⇒ Boolean

Returns:

  • (Boolean)


968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
# File 'lib/rubycli/documentation/metadata_parser.rb', line 968

def type_token_candidate?(token)
  return false unless token

  stripped = token.strip
  return false if stripped.empty?

  return true if stripped.start_with?('@')
  return true if stripped.start_with?('%')
  return true if stripped.include?('::')
  return true if stripped.start_with?('(') && stripped.end_with?(')')
  return true if stripped.include?('[') && stripped.include?(']')

  normalized = normalize_type_token(stripped)
  return false if normalized.empty?

  INLINE_TYPE_HINTS.include?(normalized)
end

#type_token_suggestions(token) ⇒ Object



885
886
887
888
889
890
891
892
893
894
# File 'lib/rubycli/documentation/metadata_parser.rb', line 885

def type_token_suggestions(token)
  dictionary = type_dictionary
  return [] if dictionary.empty?

  require 'did_you_mean'
  checker = DidYouMean::SpellChecker.new(dictionary: dictionary)
  checker.correct(token.to_s).take(3)
rescue LoadError, NameError
  []
end

#warn_unknown_allowed_value(token, source_file, line_number) ⇒ Object



873
874
875
876
877
878
879
880
881
882
883
# File 'lib/rubycli/documentation/metadata_parser.rb', line 873

def warn_unknown_allowed_value(token, source_file, line_number)
  return if token.nil? || token.empty?

  suggestions = allowed_value_suggestions(token)
  message = "Unknown allowed value token '#{token}'"
  if suggestions.any?
    hint = suggestions.first(2).join(' or ')
    message = "#{message} (did you mean #{hint}?)"
  end
  @environment.handle_documentation_issue(message, file: source_file, line: line_number)
end

#warn_unknown_type_token(token, source_file, line_number) ⇒ Object



861
862
863
864
865
866
867
868
869
870
871
# File 'lib/rubycli/documentation/metadata_parser.rb', line 861

def warn_unknown_type_token(token, source_file, line_number)
  return if token.nil? || token.empty?

  suggestions = type_token_suggestions(token)
  message = "Unknown type token '#{token}'"
  if suggestions.any?
    hint = suggestions.first(2).join(' or ')
    message = "#{message} (did you mean #{hint}?)"
  end
  @environment.handle_documentation_issue(message, file: source_file, line: line_number)
end