Module: Docscribe::Infer::Literals

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

Overview

Literal inference: map simple AST literals to type names.

Class Method Summary collapse

Class Method Details

.type_from_literal(node, fallback_type: FALLBACK_TYPE) ⇒ String

Note:

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

Infer a type name from a literal-like AST node.

Supports common literal/value node types such as:

  • integers, floats, strings, symbols

  • booleans and nil

  • arrays, hashes, regexps

  • constants

  • ‘Foo.new` constructor calls

If the node does not match a supported pattern, the fallback type is returned.

Parameters:

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

    literal/value node

  • fallback_type (String) (defaults to: FALLBACK_TYPE)

    type returned when inference is uncertain

Returns:

  • (String)


24
25
26
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
# File 'lib/docscribe/infer/literals.rb', line 24

def type_from_literal(node, fallback_type: FALLBACK_TYPE)
  return fallback_type unless node

  case node.type
  when :int then 'Integer'
  when :float then 'Float'
  when :str, :dstr then 'String'
  when :sym then 'Symbol'
  when :true, :false then 'Boolean' # rubocop:disable Lint/BooleanSymbol
  when :nil then 'nil'
  when :array then 'Array'
  when :hash then 'Hash'
  when :regexp then 'Regexp'

  when :const
    node.children.last.to_s

  when :send
    recv, meth, = node.children
    if meth == :new && recv && recv.type == :const
      recv.children.last.to_s
    else
      fallback_type
    end

  else
    fallback_type
  end
end