Module: Docscribe::InlineRewriter::DocBuilder

Defined in:
lib/docscribe/inline_rewriter/doc_builder.rb

Overview

Build generated YARD-style doc lines for methods and attribute helpers.

DocBuilder combines:

  • Ruby visibility/container metadata from Collector

  • optional external signatures from Sorbet/RBS providers

  • fallback AST inference from Docscribe::Infer

It is responsible for producing complete doc blocks for aggressive mode and “missing lines only” payloads for safe merge mode.

Class Method Summary collapse

Class Method Details

.build(insertion, config:, signature_provider: nil, core_rbs_provider: nil, param_types: nil) ⇒ String?

Note:

module_function: when included, also defines #build (instance visibility: private)

Build a complete doc block for one collected method insertion.

External signatures, when available, override inferred param and return types.

Parameters:

  • insertion (Docscribe::InlineRewriter::Collector::Insertion)
  • config (Docscribe::Config)
  • signature_provider (Object, nil) (defaults to: nil)

    provider responding to ‘signature_for(container:, scope:, name:)`

  • core_rbs_provider (nil) (defaults to: nil)

    Param documentation.

  • param_types (nil) (defaults to: nil)

    Param documentation.

Returns:

  • (String, nil)

Raises:

  • (StandardError)


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
112
113
114
115
116
117
118
119
120
121
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 35

def build(insertion, config:, signature_provider: nil, core_rbs_provider: nil, param_types: nil)
  node = insertion.node
  name = SourceHelpers.node_name(node)
  return nil unless name

  indent = SourceHelpers.line_indent(node)
  scope = insertion.scope
  visibility = insertion.visibility
  container = insertion.container
  method_symbol = scope == :instance ? '#' : '.'

  external_sig = signature_provider&.signature_for(
    container: container,
    scope: scope,
    name: name
  )

  effective_param_types =
    param_types || build_param_types_from_node(node, external_sig: external_sig, config: config)

  if config.emit_param_tags?
    params_lines = build_params_lines(node, indent, external_sig: external_sig, config: config)
  end
  raise_types = config.emit_raise_tags? ? Docscribe::Infer.infer_raises_from_node(node) : []

  returns_spec = Docscribe::Infer.returns_spec_from_node(
    node,
    fallback_type: config.fallback_type,
    nil_as_optional: config.nil_as_optional?,
    param_types: effective_param_types,
    core_rbs_provider: core_rbs_provider
  )

  normal_type = external_sig&.return_type || returns_spec[:normal]
  rescue_specs = returns_spec[:rescues] || []

  lines = []

  if config.emit_header?
    lines << "#{indent}# +#{container}#{method_symbol}#{name}+ -> #{normal_type}"
    lines << "#{indent}#"
  end

  if config.include_default_message?
    lines << "#{indent}# #{config.default_message(scope, visibility)}"
    lines << "#{indent}#"
  end

  if config.emit_visibility_tags?
    case visibility
    when :private
      lines << "#{indent}# @private"
    when :protected
      lines << "#{indent}# @protected"
    end
  end

  if insertion.respond_to?(:module_function) && insertion.module_function
    included_vis =
      if insertion.respond_to?(:included_instance_visibility) && insertion.included_instance_visibility
        insertion.included_instance_visibility
      else
        :private
      end

    lines << "#{indent}# @note module_function: when included, also defines ##{name} " \
             "(instance visibility: #{included_vis})"
  end

  lines.concat(params_lines) if params_lines
  raise_types.each { |rt| lines << "#{indent}# @raise [#{rt}]" } if config.emit_raise_tags?
  lines << "#{indent}# @return [#{normal_type}]" if config.emit_return_tag?(scope, visibility)

  if config.emit_rescue_conditional_returns?
    rescue_specs.each do |exceptions, rtype|
      lines << "#{indent}# @return [#{rtype}] if #{exceptions.join(', ')}"
    end
  end
  plugin_tags = Docscribe::Plugin.run_tag_plugins(
    build_plugin_context(insertion, normal_type: normal_type)
  )
  lines.concat(render_plugin_tags(plugin_tags, indent))
  lines.map { |l| "#{l}\n" }.join
rescue StandardError => e
  debug_warn(e, insertion: insertion, name: name || '(unknown)', phase: 'DocBuilder.build')
  nil
end

.build_merge_additions(insertion, existing_lines:, config:, signature_provider: nil, core_rbs_provider: nil, param_types: nil) ⇒ String?

Note:

module_function: when included, also defines #build_merge_additions (instance visibility: private)

Build only the missing doc lines that should be merged into an existing doc-like block.

This is used by safe mode for non-destructive updates.

Parameters:

Returns:

  • (String, nil)

Raises:

  • (StandardError)


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
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 137

def build_merge_additions(insertion, existing_lines:, config:, signature_provider: nil, core_rbs_provider: nil,
                          param_types: nil)
  node = insertion.node
  name = SourceHelpers.node_name(node)
  return '' unless name

  indent = SourceHelpers.line_indent(node)
  info = parse_existing_doc_tags(existing_lines)
  scope = insertion.scope
  visibility = insertion.visibility

  external_sig = signature_provider&.signature_for(
    container: insertion.container,
    scope: scope,
    name: name
  )

  returns_spec = Docscribe::Infer.returns_spec_from_node(
    node,
    fallback_type: config.fallback_type,
    nil_as_optional: config.nil_as_optional?,
    param_types: param_types,
    core_rbs_provider: core_rbs_provider
  )

  normal_type = external_sig&.return_type || returns_spec[:normal]
  rescue_specs = returns_spec[:rescues] || []

  lines = []
  lines << "#{indent}#" if existing_lines.any? && existing_lines.last.strip != '#'

  if config.emit_visibility_tags?
    if visibility == :private && !info[:has_private]
      lines << "#{indent}# @private"
    elsif visibility == :protected && !info[:has_protected]
      lines << "#{indent}# @protected"
    end
  end

  if insertion.respond_to?(:module_function) && insertion.module_function && !info[:has_module_function_note]
    included_vis = insertion.included_instance_visibility || :private
    lines << "#{indent}# @note module_function: when included, also defines ##{name} " \
             "(instance visibility: #{included_vis})"
  end

  if config.emit_param_tags?
    all_params = build_params_lines(node, indent, external_sig: external_sig, config: config)
    all_params&.each do |pl|
      pname = extract_param_name_from_param_line(pl)
      next if pname.nil? || info[:param_names].include?(pname)

      lines << pl
    end
  end

  if config.emit_raise_tags?
    inferred = Docscribe::Infer.infer_raises_from_node(node)
    existing = info[:raise_types] || {}
    missing = inferred.reject { |rt| existing[rt] }
    missing.each { |rt| lines << "#{indent}# @raise [#{rt}]" }
  end

  if config.emit_return_tag?(scope, visibility) && !info[:has_return]
    lines << "#{indent}# @return [#{normal_type}]"
  end

  if config.emit_rescue_conditional_returns? && !info[:has_return]
    rescue_specs.each do |exceptions, rtype|
      lines << "#{indent}# @return [#{rtype}] if #{exceptions.join(', ')}"
    end
  end

  useful = lines.reject { |l| l.strip == '#' }
  return '' if useful.empty?

  lines.map { |l| "#{l}\n" }.join
rescue StandardError => e
  debug_warn(e, insertion: insertion, name: name || '(unknown)', phase: 'DocBuilder.build_merge_additions')
  nil
end

.build_missing_merge_result(insertion, existing_lines:, config:, signature_provider: nil, core_rbs_provider: nil, param_types: nil, strategy: nil) ⇒ Hash

Note:

module_function: when included, also defines #build_missing_merge_result (instance visibility: private)

Build structured missing-line information for safe merge mode.

Returns both:

  • generated missing lines

  • structured reasons used by ‘–explain`

Parameters:

  • insertion (Docscribe::InlineRewriter::Collector::Insertion)
  • existing_lines (Array<String>)
  • config (Docscribe::Config)
  • signature_provider (Object, nil) (defaults to: nil)
  • core_rbs_provider (nil) (defaults to: nil)

    Param documentation.

  • param_types (nil) (defaults to: nil)

    Param documentation.

  • strategy (nil) (defaults to: nil)

    Param documentation.

Returns:

  • (Hash)

Raises:

  • (StandardError)


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
270
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
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 234

def build_missing_merge_result(insertion, existing_lines:, config:, signature_provider: nil,
                               core_rbs_provider: nil, param_types: nil, strategy: nil)
  node = insertion.node
  name = SourceHelpers.node_name(node)
  return { lines: [], reasons: [] } unless name

  indent = SourceHelpers.line_indent(node)
  info = parse_existing_doc_tags(existing_lines)
  scope = insertion.scope
  visibility = insertion.visibility

  external_sig = signature_provider&.signature_for(
    container: insertion.container,
    scope: scope,
    name: name
  )

  returns_spec = Docscribe::Infer.returns_spec_from_node(
    node,
    fallback_type: config.fallback_type,
    nil_as_optional: config.nil_as_optional?,
    param_types: param_types,
    core_rbs_provider: core_rbs_provider
  )

  normal_type = external_sig&.return_type || returns_spec[:normal]
  rescue_specs = returns_spec[:rescues] || []

  lines = []
  reasons = []

  if config.emit_visibility_tags?
    if visibility == :private && !info[:has_private]
      lines << "#{indent}# @private\n"
      reasons << { type: :missing_visibility, message: 'missing @private' }
    elsif visibility == :protected && !info[:has_protected]
      lines << "#{indent}# @protected\n"
      reasons << { type: :missing_visibility, message: 'missing @protected' }
    end
  end

  if insertion.respond_to?(:module_function) && insertion.module_function && !info[:has_module_function_note]
    included_vis = insertion.included_instance_visibility || :private
    lines << "#{indent}# @note module_function: when included, also defines ##{name} " \
             "(instance visibility: #{included_vis})\n"
    reasons << { type: :missing_module_function_note, message: 'missing module_function note' }
  end

  if config.emit_param_tags?
    all_params = build_params_lines(node, indent, external_sig: external_sig, config: config)

    all_params&.each do |pl|
      pname = extract_param_name_from_param_line(pl)
      next unless pname

      if !info[:param_names].include?(pname)
        lines << "#{pl}\n"
        reasons << { type: :missing_param, message: "missing @param #{pname}", extra: { param: pname } }
      elsif info[:param_types][pname] && strategy != :safe
        new_type = extract_param_type_from_param_line(pl)
        if new_type && info[:param_types][pname] != new_type
          lines << "#{pl}\n"
          reasons << {
            type: :updated_param,
            message: "updated @param #{pname} from #{info[:param_types][pname]} to #{new_type}",
            extra: { param: pname }
          }
        end
      end
    end
  end

  if config.emit_raise_tags?
    inferred = Docscribe::Infer.infer_raises_from_node(node)
    existing = info[:raise_types] || {}
    missing = inferred.reject { |rt| existing[rt] }

    missing.each do |rt|
      lines << "#{indent}# @raise [#{rt}]\n"
      reasons << { type: :missing_raise, message: "missing @raise [#{rt}]", extra: { raise_type: rt } }
    end
  end

  if config.emit_return_tag?(scope, visibility)
    if !info[:has_return]
      lines << "#{indent}# @return [#{normal_type}]\n"
      reasons << { type: :missing_return, message: 'missing @return' }
    elsif info[:return_type] && info[:return_type] != normal_type && strategy != :safe
      lines << "#{indent}# @return [#{normal_type}]\n"
      reasons << {
        type: :updated_return,
        message: "updated @return from #{info[:return_type]} to #{normal_type}"
      }
    end
  end

  if config.emit_rescue_conditional_returns? && !info[:has_return]
    rescue_specs.each do |exceptions, rtype|
      lines << "#{indent}# @return [#{rtype}] if #{exceptions.join(', ')}\n"
      reasons << {
        type: :missing_return,
        message: "missing conditional @return for #{exceptions.join(', ')}"
      }
    end
  end
  plugin_tags = Docscribe::Plugin.run_tag_plugins(
    build_plugin_context(insertion, normal_type: normal_type)
  )
  plugin_tags.each do |tag|
    next if info[:plugin_tags]&.[](tag.name)

    rendered = render_plugin_tags([tag], indent).first
    lines << "#{rendered}\n"
    reasons << { type: :missing_plugin_tag, message: "missing @#{tag.name}" }
  end
  { lines: lines, reasons: reasons }
rescue StandardError => e
  debug_warn(e, insertion: insertion, name: name || '(unknown)', phase: 'DocBuilder.build_missing_merge_result')
  { lines: [], reasons: [] }
end

.build_param_types_from_node(node, external_sig:, config:) ⇒ Hash{String => String}?

Note:

module_function: when included, also defines #build_param_types_from_node (instance visibility: private)

Build a param name => type map from a method node.

Parameters:

  • node (Parser::AST::Node)

    def or defs node

  • external_sig (Object, nil)

    external signature if available

  • config (Docscribe::Config)

Returns:

  • (Hash{String => String}, nil)


449
450
451
452
453
454
455
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 449

def build_param_types_from_node(node, external_sig:, config:)
  return nil unless node

  args =
    case node.type
    when :def then node.children[1]
    when :defs then node.children[2]
    end

  return nil unless args

  param_types = {}

  (args.children || []).each do |a|
    case a.type
    when :arg
      pname = a.children.first.to_s
      ty = external_sig&.param_types&.[](pname) ||
           Infer.infer_param_type(
             pname,
             nil,
             fallback_type: config.fallback_type,
             treat_options_keyword_as_hash: config.treat_options_keyword_as_hash?
           )
      param_types[pname] = ty

    when :optarg
      pname, default = *a
      pname = pname.to_s
      default_src = default&.loc&.expression&.source
      ty = external_sig&.param_types&.[](pname) ||
           Infer.infer_param_type(
             pname,
             default_src,
             fallback_type: config.fallback_type,
             treat_options_keyword_as_hash: config.treat_options_keyword_as_hash?
           )
      param_types[pname] = ty

    when :kwarg
      pname = a.children.first.to_s
      ty = external_sig&.param_types&.[](pname) ||
           Infer.infer_param_type(
             "#{pname}:",
             nil,
             fallback_type: config.fallback_type,
             treat_options_keyword_as_hash: config.treat_options_keyword_as_hash?
           )
      param_types[pname] = ty

    when :kwoptarg
      pname, default = *a
      pname = pname.to_s
      default_src = default&.loc&.expression&.source
      ty = external_sig&.param_types&.[](pname) ||
           Infer.infer_param_type(
             "#{pname}:",
             default_src,
             fallback_type: config.fallback_type,
             treat_options_keyword_as_hash: config.treat_options_keyword_as_hash?
           )
      param_types[pname] = ty
    end
  end

  param_types.empty? ? nil : param_types
end

.build_params_lines(node, indent, external_sig:, config:) ⇒ Array<String>?

Note:

module_function: when included, also defines #build_params_lines (instance visibility: private)

Build generated ‘@param` / `@option` lines for a method node.

External signatures take precedence over inferred parameter types.

Parameters:

Returns:

  • (Array<String>, nil)


527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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
586
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
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 527

def build_params_lines(node, indent, external_sig:, config:)
  fallback_type = config.fallback_type
  treat_options_keyword_as_hash = config.treat_options_keyword_as_hash?
  param_tag_style = config.param_tag_style
  param_documentation = config.include_param_documentation? ? config.param_documentation : ''

  args =
    case node.type
    when :def then node.children[1]
    when :defs then node.children[2]
    end

  return nil unless args

  params = []

  (args.children || []).each do |a|
    case a.type
    when :arg
      pname = a.children.first.to_s
      ty = external_sig&.param_types&.[](pname) ||
           Infer.infer_param_type(
             pname,
             nil,
             fallback_type: fallback_type,
             treat_options_keyword_as_hash: treat_options_keyword_as_hash
           )
      params << format_param_tag(indent, pname, ty, param_documentation, style: param_tag_style)

    when :optarg
      pname, default = *a
      pname = pname.to_s
      default_src = default&.loc&.expression&.source
      ty = external_sig&.param_types&.[](pname) ||
           Infer.infer_param_type(
             pname,
             default_src,
             fallback_type: fallback_type,
             treat_options_keyword_as_hash: treat_options_keyword_as_hash
           )
      params << format_param_tag(indent, pname, ty, param_documentation, style: param_tag_style)

      hash_option_pairs(default).each do |pair|
        key_node, value_node = pair.children
        option_key = option_key_name(key_node)
        option_type = Infer::Literals.type_from_literal(value_node, fallback_type: fallback_type)
        option_default = node_default_literal(value_node)

        line = "#{indent}# @option #{pname} [#{option_type}] :#{option_key}"
        line += " (#{option_default})" if option_default
        line += ' Option documentation.'
        params << line
      end

    when :kwarg
      pname = a.children.first.to_s
      ty = external_sig&.param_types&.[](pname) ||
           Infer.infer_param_type(
             "#{pname}:",
             nil,
             fallback_type: fallback_type,
             treat_options_keyword_as_hash: treat_options_keyword_as_hash
           )
      params << format_param_tag(indent, pname, ty, param_documentation, style: param_tag_style)

    when :kwoptarg
      pname, default = *a
      pname = pname.to_s
      default_src = default&.loc&.expression&.source
      ty = external_sig&.param_types&.[](pname) ||
           Infer.infer_param_type(
             "#{pname}:",
             default_src,
             fallback_type: fallback_type,
             treat_options_keyword_as_hash: treat_options_keyword_as_hash
           )
      params << format_param_tag(indent, pname, ty, param_documentation, style: param_tag_style)

    when :restarg
      pname = (a.children.first || 'args').to_s
      ty =
        if external_sig&.rest_positional&.element_type
          "Array<#{external_sig.rest_positional.element_type}>"
        else
          Infer.infer_param_type(
            "*#{pname}",
            nil,
            fallback_type: fallback_type,
            treat_options_keyword_as_hash: treat_options_keyword_as_hash
          )
        end
      params << format_param_tag(indent, pname, ty, param_documentation, style: param_tag_style)

    when :kwrestarg
      pname = (a.children.first || 'kwargs').to_s
      ty = external_sig&.rest_keywords&.type ||
           Infer.infer_param_type(
             "**#{pname}",
             nil,
             fallback_type: fallback_type,
             treat_options_keyword_as_hash: treat_options_keyword_as_hash
           )
      params << format_param_tag(indent, pname, ty, param_documentation, style: param_tag_style)

    when :blockarg
      pname = (a.children.first || 'block').to_s
      ty = external_sig&.param_types&.[](pname) ||
           Infer.infer_param_type(
             "&#{pname}",
             nil,
             fallback_type: fallback_type,
             treat_options_keyword_as_hash: treat_options_keyword_as_hash
           )
      params << format_param_tag(indent, pname, ty, param_documentation, style: param_tag_style)

    when :forward_arg
      # skip
    end
  end

  params.empty? ? nil : params
end

.build_plugin_context(insertion, normal_type:) ⇒ Docscribe::Plugin::Context

Note:

module_function

Note:

module_function: when included, also defines #build_plugin_context (instance visibility: private)

Build a Plugin::Context from a collected insertion.

Parameters:

Returns:

Raises:

  • (StandardError)


740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 740

def build_plugin_context(insertion, normal_type:)
  node = insertion.node
  source = begin
    node.loc.expression.source
  rescue StandardError
    ''
  end

  Docscribe::Plugin::Context.new(
    node: node,
    container: insertion.container,
    scope: insertion.scope,
    visibility: insertion.visibility,
    method_name: SourceHelpers.node_name(node),
    inferred_params: {},
    inferred_return: normal_type,
    source: source
  )
end

.debug?Boolean

Note:

module_function: when included, also defines #debug? (instance visibility: private)

Check whether debug mode is enabled.

Returns:

  • (Boolean)


804
805
806
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 804

def debug?
  ENV['DOCSCRIBE_DEBUG'] == '1'
end

.debug_warn(e, insertion:, name:, phase:) ⇒ void

Note:

module_function: when included, also defines #debug_warn (instance visibility: private)

This method returns an undefined value.

Print a debug warning for a failed doc build phase.

Parameters:

  • e (StandardError)

    the error that occurred

  • insertion (Collector::Insertion)

    the method insertion being processed

  • name (String)

    the method name

  • phase (String)

    the processing phase



783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 783

def debug_warn(e, insertion:, name:, phase:)
  return unless debug?

  node = insertion&.node
  buf_name = node&.loc&.expression&.source_buffer&.name || '(unknown)'
  line = node&.loc&.expression&.line
  scope = insertion&.scope
  method_symbol = scope == :class ? '.' : '#'
  container = insertion&.container || 'Object'

  where = +buf_name.to_s
  where << ":#{line}" if line
  where << " #{container}#{method_symbol}#{name}"

  warn "Docscribe DEBUG: #{phase} failed at #{where}: #{e.class}: #{e.message}"
end

.extract_param_name_from_param_line(line) ⇒ String?

Note:

module_function: when included, also defines #extract_param_name_from_param_line (instance visibility: private)

Extract the parameter name from a ‘@param` doc line.

Handles both ‘“@param [Type] name”` and `“@param name [Type]”` styles.

Parameters:

  • line (String)

    a ‘@param` doc line

Returns:

  • (String, nil)

    the parameter name or nil



714
715
716
717
718
719
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 714

def extract_param_name_from_param_line(line)
  return Regexp.last_match(1) if line =~ /@param\b\s+\[[^\]]+\]\s+(\S+)/
  return Regexp.last_match(1) if line =~ /@param\b\s+(\S+)\s+\[[^\]]+\]/

  nil
end

.extract_param_type_from_param_line(line) ⇒ Object

Note:

module_function: when included, also defines #extract_param_type_from_param_line (instance visibility: private)

Method documentation.

Parameters:

  • line (Object)

    Param documentation.

Returns:

  • (Object)


726
727
728
729
730
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 726

def extract_param_type_from_param_line(line)
  if (m = line.match(/@param\s+\[([^\]]+)\]\s+\S+/) || line.match(/@param\s+\S+\s+\[([^\]]+)\]/))
    m[1]
  end
end

.extract_raise_types_from_line(line) ⇒ String, ...

Note:

module_function: when included, also defines #extract_raise_types_from_line (instance visibility: private)

Extract exception names from a ‘@raise` doc line.

Parameters:

  • line (String)

    a ‘@raise` doc line

Returns:

  • (String, nil)

    the exception name or nil

  • (Array)

    if StandardError or line not matched

Raises:

  • (StandardError)


418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 418

def extract_raise_types_from_line(line)
  return [] unless line.match?(/^\s*#\s*@raise\b/)

  if (m = line.match(/^\s*#\s*@raise\s*\[([^\]]+)\]/))
    parse_raise_bracket_list(m[1])
  elsif (m = line.match(/^\s*#\s*@raise\s+([A-Z]\w*(?:::[A-Z]\w*)*)/))
    [m[1]]
  else
    []
  end
rescue StandardError
  []
end

.format_param_tag(indent, name, type, documentation, style:) ⇒ String

Note:

module_function: when included, also defines #format_param_tag (instance visibility: private)

Format a ‘@param` tag line using the configured param tag style.

Parameters:

  • indent (String)

    leading whitespace

  • name (String)

    parameter name

  • type (String)

    parameter type

  • documentation (String)

    optional documentation text

  • style (String, Symbol)

    param tag style (‘“name_type”` or `“type_name”`)

Returns:

  • (String)


659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 659

def format_param_tag(indent, name, type, documentation, style:)
  doc = documentation.to_s.strip
  type = type.to_s

  line = case style.to_s
         when 'name_type'
           "#{indent}# @param #{name} [#{type}]"
         else
           "#{indent}# @param [#{type}] #{name}"
         end

  doc.empty? ? line : "#{line} #{doc}"
end

.hash_option_pairs(node) ⇒ Array<Parser::AST::Node>

Note:

module_function: when included, also defines #hash_option_pairs (instance visibility: private)

Extract keyword argument option pairs from a hash default value.

Parameters:

  • node (Parser::AST::Node, nil)

    a ‘:hash` node

Returns:

  • (Array<Parser::AST::Node>)

    the ‘:pair` children



678
679
680
681
682
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 678

def hash_option_pairs(node)
  return [] unless node&.type == :hash

  node.children.select { |child| child.is_a?(Parser::AST::Node) && child.type == :pair }
end

.node_default_literal(node) ⇒ String?

Note:

module_function: when included, also defines #node_default_literal (instance visibility: private)

Get the raw source literal for a default value node.

Parameters:

  • node (Parser::AST::Node, nil)

    a default value node

Returns:

  • (String, nil)

    the source literal or nil



703
704
705
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 703

def node_default_literal(node)
  node&.loc&.expression&.source
end

.option_key_name(key_node) ⇒ String

Note:

module_function: when included, also defines #option_key_name (instance visibility: private)

Get the symbol name from an option key node.

Parameters:

  • key_node (Parser::AST::Node)

    a ‘:sym` node

Returns:

  • (String)

    the option key name



689
690
691
692
693
694
695
696
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 689

def option_key_name(key_node)
  case key_node&.type
  when :sym, :str
    key_node.children.first.to_s
  else
    key_node&.loc&.expression&.source.to_s.sub(/\A:/, '')
  end
end

.parse_existing_doc_tags(lines) ⇒ Hash

Note:

module_function: when included, also defines #parse_existing_doc_tags (instance visibility: private)

Parse existing doc comment lines and extract known YARD tags.

Extracts: ‘@param` names, `@return`, `@raise`, `@private`, `@protected`, `@module_function` notes, and `@option` lines.

Parameters:

  • lines (Array<String>)

    existing doc comment lines

Returns:

  • (Hash)

    parsed tag info



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
405
406
407
408
409
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 363

def parse_existing_doc_tags(lines)
  param_names = {}
  param_types = {}
  has_return = false
  return_type = nil
  has_private = false
  has_protected = false
  has_module_function_note = false
  raise_types = {}
  plugin_tags = {}

  Array(lines).each do |line|
    if (m = line.match(/^\s*#\s*@(\w+)\b/))
      plugin_tags[m[1]] = true
    end
    if (pname = extract_param_name_from_param_line(line))
      param_names[pname] = true
      if (type_match = line.match(/@param\s+\[([^\]]+)\]\s+\S+/) || line.match(/@param\s+\S+\s+\[([^\]]+)\]/))
        param_types[pname] = type_match[1]
      end
    end

    if line.match?(/^\s*#\s*@return\b/)
      has_return = true
      if (m = line.match(/@return\s+\[([^\]]+)\]/))
        return_type = m[1]
      end
    end
    has_private ||= line.match?(/^\s*#\s*@private\b/)
    has_protected ||= line.match?(/^\s*#\s*@protected\b/)
    has_module_function_note ||= line.match?(/^\s*#\s*@note\s+module_function:/)

    extract_raise_types_from_line(line).each { |t| raise_types[t] = true }
  end

  {
    param_names: param_names,
    param_types: param_types,
    has_return: has_return,
    return_type: return_type,
    raise_types: raise_types,
    has_private: has_private,
    has_protected: has_protected,
    has_module_function_note: has_module_function_note,
    plugin_tags: plugin_tags
  }
end

.parse_raise_bracket_list(s) ⇒ Array<String>?

Note:

module_function: when included, also defines #parse_raise_bracket_list (instance visibility: private)

Parse exception names from a ‘@raise [ExceptionA, ExceptionB]` line.

Parameters:

  • s (String)

    the ‘@raise` line text

Returns:

  • (Array<String>, nil)

    the exception names or nil



437
438
439
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 437

def parse_raise_bracket_list(s)
  s.to_s.split(',').map(&:strip).reject(&:empty?)
end

.render_plugin_tags(tags, indent) ⇒ Array<String>

Note:

module_function

Note:

module_function: when included, also defines #render_plugin_tags (instance visibility: private)

Render plugin tags as indented comment lines.

Parameters:

Returns:

  • (Array<String>)


767
768
769
770
771
772
773
# File 'lib/docscribe/inline_rewriter/doc_builder.rb', line 767

def render_plugin_tags(tags, indent)
  tags.map do |tag|
    type_part = tag.types&.any? ? " [#{tag.types.join(', ')}]" : ''
    text_part = tag.text ? " #{tag.text}" : ''
    "#{indent}# @#{tag.name}#{type_part}#{text_part}"
  end
end