module Vernacular::AST::Modifiers::TypedMethodReturns::TypedMethodReturnsRewriter

Methods to be included in the rewriter in order to handle `type_check_arglist` nodes.

Public Instance Methods

on_def(method_node) click to toggle source
Calls superclass method
# File lib/vernacular/ast/modifiers/typed_method_returns.rb, line 26
def on_def(method_node)
  type_check_node = type_check_node_from(method_node)
  return super unless type_check_node

  type_node = type_check_node.children[1]
  remove(type_check_node.children[0][1])
  remove(type_node.loc.expression)
  type_check_method(method_node, type_node)

  super
end

Private Instance Methods

build_constant(node, suffix = nil) click to toggle source
# File lib/vernacular/ast/modifiers/typed_method_returns.rb, line 40
def build_constant(node, suffix = nil)
  child_node, name = node.children
  new_name = suffix ? "#{name}::#{suffix}" : name
  child_node ? build_constant(child_node, new_name) : new_name
end
type_check_method(method_node, type_node) click to toggle source
# File lib/vernacular/ast/modifiers/typed_method_returns.rb, line 55
def type_check_method(method_node, type_node)
  expression = method_node.children[2].loc.expression
  type = build_constant(type_node)

  @source_rewriter.transaction do
    insert_before(expression, "result = begin\n")
    insert_after(expression, "\nend\nraise \"Invalid return value, " \
      "expected #{type}, got \#{result.class.name}\" unless " \
      "result.is_a?(#{type})\nresult")
  end
end
type_check_node_from(method_node) click to toggle source
# File lib/vernacular/ast/modifiers/typed_method_returns.rb, line 46
def type_check_node_from(method_node)
  type_check_node = method_node.children[1].children.last

  return if !type_check_node ||
            type_check_node.type != :type_check_arglist

  type_check_node
end