module Vernacular::AST::Modifiers::TypedMethodArgs::TypedMethodArgsRewriter

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

Public Instance Methods

on_def(node) click to toggle source

Triggered whenever a `:def` node is added to the AST. Finds any `type_check_arg` nodes, replaces them with normal `:arg` nodes, and adds in the represented type check to the beginning of the method.

Calls superclass method
# File lib/vernacular/ast/modifiers/typed_method_args.rb, line 31
def on_def(node)
  type_checks = build_type_checks(node.children[1].children)
  if type_checks.any?
    insert_before(node.children[2].loc.expression, type_checks.join)
  end

  super
end

Private Instance Methods

build_constant(node, suffix = nil) click to toggle source
# File lib/vernacular/ast/modifiers/typed_method_args.rb, line 42
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
build_type_checks(arg_list_node) click to toggle source
# File lib/vernacular/ast/modifiers/typed_method_args.rb, line 48
def build_type_checks(arg_list_node)
  arg_list_node.each_with_object([]) do |arg, type_checks|
    next unless arg.type == :type_check_arg

    type_checks << type_check(arg)
    remove(arg.loc.operator)
    remove(arg.children[1].loc.expression)
  end
end
type_check(arg_node) click to toggle source
# File lib/vernacular/ast/modifiers/typed_method_args.rb, line 58
def type_check(arg_node)
  arg_name = arg_node.children[0][0].children[0]
  type = build_constant(arg_node.children[1])
  "raise ArgumentError, \"Invalid type, expected #{type}, got " \
    "\#{#{arg_name}.class.name}\" unless #{arg_name}.is_a?(#{type});"
end