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

.const_type_for(node, _fallback_type) ⇒ String?

Note:

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

Extract a constant name from a ‘:const` node.

Parameters:

  • node (Parser::AST::Node)
  • fallback_type (String)
  • _fallback_type (String)

    fallback type string (unused here)

Returns:

  • (String, nil)


49
50
51
52
53
# File 'lib/docscribe/infer/literals.rb', line 49

def const_type_for(node, _fallback_type)
  return unless node.type == :const

  node.children.last.to_s
end

.literal_type_for(type) ⇒ String?

Note:

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

Map a node type symbol to a known literal type name.

Parameters:

  • type (Symbol)

    node type

Returns:

  • (String, nil)


37
38
39
# File 'lib/docscribe/infer/literals.rb', line 37

def literal_type_for(type)
  LITERAL_TYPE_MAP[type]
end

.send_new_type_for(node, _fallback_type) ⇒ String?

Note:

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

Extract a type from a ‘Foo.new` send node.

Parameters:

  • node (Parser::AST::Node)
  • fallback_type (String)
  • _fallback_type (String)

    fallback type string (unused here)

Returns:

  • (String, nil)


63
64
65
66
67
68
69
70
# File 'lib/docscribe/infer/literals.rb', line 63

def send_new_type_for(node, _fallback_type)
  return unless node.type == :send

  recv, meth, = node.children
  return unless meth == :new && recv&.type == :const

  recv.children.last.to_s
end

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

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

  literal_type_for(node.type) || const_type_for(node, fallback_type) ||
    send_new_type_for(node, fallback_type) || fallback_type
end