Module: Docscribe::Infer::Params

Defined in:
lib/docscribe/infer/params.rb

Overview

Parameter type inference.

Class Method Summary collapse

Class Method Details

.infer_param_type(name, default_str, fallback_type: FALLBACK_TYPE, treat_options_keyword_as_hash: true) ⇒ String

Note:

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

Infer a parameter type from an internal parameter name representation and an optional default expression.

Handles:

  • positional/rest/block parameter prefixes (‘*`, `**`, `&`)

  • keyword params with and without defaults

  • special-casing ‘options:` as `Hash` when enabled

  • literal defaults via AST parsing

Parameters:

  • name (String)

    parameter name as used internally (may include ‘*`, `**`, `&`, or trailing `:`)

  • default_str (String, nil)

    source for the default value expression

  • fallback_type (String) (defaults to: FALLBACK_TYPE)

    type returned when inference is uncertain

  • treat_options_keyword_as_hash (Boolean) (defaults to: true)

    whether ‘options:` should be treated specially as Hash

Returns:

  • (String)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/docscribe/infer/params.rb', line 25

def infer_param_type(name, default_str, fallback_type: FALLBACK_TYPE, treat_options_keyword_as_hash: true)
  return 'Array' if name.start_with?('*') && !name.start_with?('**')
  return 'Hash'  if name.start_with?('**')
  return 'Proc'  if name.start_with?('&')

  is_kw = name.end_with?(':')
  node = parse_expr(default_str)
  ty = Literals.type_from_literal(node, fallback_type: fallback_type)

  if is_kw && default_str.nil?
    return (treat_options_keyword_as_hash && name == 'options:' ? 'Hash' : fallback_type)
  end

  return 'Hash' if treat_options_keyword_as_hash && name == 'options:' && (default_str == '{}' || ty == 'Hash')

  ty
end

.parse_expr(src) ⇒ Parser::AST::Node?

Note:

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

Parse a standalone expression for parameter-default inference.

Returns nil if the expression is empty or cannot be parsed.

Parameters:

  • src (String, nil)

    expression source

Returns:

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

Raises:

  • (Parser::SyntaxError)


51
52
53
54
55
56
57
58
59
# File 'lib/docscribe/infer/params.rb', line 51

def parse_expr(src)
  return nil if src.nil? || src.strip.empty?

  buffer = Parser::Source::Buffer.new('(param)')
  buffer.source = src
  Docscribe::Parsing.parse_buffer(buffer)
rescue Parser::SyntaxError
  nil
end