1
0
Fork 0
mirror of https://github.com/pry/pry.git synced 2022-11-09 12:35:05 -05:00
pry--pry/lib/pry/method.rb

552 lines
19 KiB
Ruby
Raw Normal View History

require 'pry/helpers/documentation_helpers'
class Pry
2012-01-09 22:59:13 -05:00
class << self
# If the given object is a `Pry::Method`, return it unaltered. If it's
# anything else, return it wrapped in a `Pry::Method` instance.
def Method(obj)
if obj.is_a? Pry::Method
obj
else
Pry::Method.new(obj)
end
end
end
# This class wraps the normal `Method` and `UnboundMethod` classes
# to provide extra functionality useful to Pry.
class Method
require 'pry/method/weird_method_locator'
require 'pry/method/disowned'
require 'pry/method/patcher'
extend Helpers::BaseHelpers
include Helpers::BaseHelpers
include Helpers::DocumentationHelpers
include CodeObject::Helpers
2011-09-25 01:13:52 -04:00
class << self
2011-10-02 04:25:49 -04:00
# Given a string representing a method name and optionally a binding to
# search in, find and return the requested method wrapped in a `Pry::Method`
# instance.
#
# @param [String] name The name of the method to retrieve.
# @param [Binding] target The context in which to search for the method.
# @param [Hash] options
# @option options [Boolean] :instance Look for an instance method if `name` doesn't
# contain any context.
# @option options [Boolean] :methods Look for a bound/singleton method if `name` doesn't
# contain any context.
2011-10-02 04:25:49 -04:00
# @return [Pry::Method, nil] A `Pry::Method` instance containing the requested
# method, or `nil` if name is `nil` or no method could be located matching the parameters.
def from_str(name, target=TOPLEVEL_BINDING, options={})
if name.nil?
nil
elsif name.to_s =~ /(.+)\#(\S+)\Z/
2011-09-25 01:13:52 -04:00
context, meth_name = $1, $2
from_module(target.eval(context), meth_name, target)
2013-12-09 14:20:29 -05:00
elsif name.to_s =~ /(.+)(\[\])\Z/
2013-12-08 20:22:34 -05:00
context, meth_name = $1, $2
from_obj(target.eval(context), meth_name, target)
elsif name.to_s =~ /(.+)(\.|::)(\S+)\Z/
context, meth_name = $1, $3
from_obj(target.eval(context), meth_name, target)
2011-09-25 01:13:52 -04:00
elsif options[:instance]
from_module(target.eval("self"), name, target)
2011-09-25 01:13:52 -04:00
elsif options[:methods]
from_obj(target.eval("self"), name, target)
2011-09-25 01:13:52 -04:00
else
from_str(name, target, :instance => true) or
2013-12-11 11:44:49 -05:00
from_str(name, target, :methods => true)
2011-09-25 01:13:52 -04:00
end
rescue Pry::RescuableException
nil
2011-09-25 01:13:52 -04:00
end
# Given a `Binding`, try to extract the `::Method` it originated from and
# use it to instantiate a `Pry::Method`. Return `nil` if this isn't
# possible.
2011-10-02 04:25:49 -04:00
#
# @param [Binding] b
# @return [Pry::Method, nil]
2011-10-02 04:25:49 -04:00
#
2011-09-25 01:13:52 -04:00
def from_binding(b)
meth_name = b.eval('::Kernel.__method__')
if [:__script__, nil].include?(meth_name)
2011-09-25 01:13:52 -04:00
nil
else
method = begin
if Object === b.eval('self')
new(Kernel.instance_method(:method).bind(b.eval("self")).call(meth_name))
else
new(b.eval('class << self; self; end.instance_method(::Kernel.__method__).bind(self)'))
end
rescue NameError, NoMethodError
Disowned.new(b.eval('self'), meth_name.to_s)
end
if WeirdMethodLocator.weird_method?(method, b)
WeirdMethodLocator.new(method, b).get_method || method
else
method
end
2011-09-25 01:13:52 -04:00
end
end
# In order to support 2.0 Refinements we need to look up methods
# inside the relevant Binding.
# @param [Object] obj The owner/receiver of the method.
# @param [Symbol] method_name The name of the method.
# @param [Symbol] method_type The type of method: :method or :instance_method
# @param [Binding] target The binding where the method is looked up.
# @return [Method, UnboundMethod] The 'refined' method object.
def lookup_method_via_binding(obj, method_name, method_type, target=TOPLEVEL_BINDING)
2013-01-15 17:29:23 -05:00
Pry.current[:obj] = obj
Pry.current[:name] = method_name
receiver = obj.is_a?(Module) ? "Module" : "Kernel"
2013-01-15 17:29:23 -05:00
target.eval("::#{receiver}.instance_method(:#{method_type}).bind(Pry.current[:obj]).call(Pry.current[:name])")
ensure
2013-01-15 17:29:23 -05:00
Pry.current[:obj] = Pry.current[:name] = nil
end
# Given a `Class` or `Module` and the name of a method, try to
# instantiate a `Pry::Method` containing the instance method of
# that name. Return `nil` if no such method exists.
2011-10-02 04:25:49 -04:00
#
# @param [Class, Module] klass
# @param [String] name
# @param [Binding] target The binding where the method is looked up.
# @return [Pry::Method, nil]
def from_class(klass, name, target=TOPLEVEL_BINDING)
new(lookup_method_via_binding(klass, name, :instance_method, target)) rescue nil
end
alias from_module from_class
# Given an object and the name of a method, try to instantiate
# a `Pry::Method` containing the method of that name bound to
# that object. Return `nil` if no such method exists.
2011-10-02 04:25:49 -04:00
#
# @param [Object] obj
# @param [String] name
# @param [Binding] target The binding where the method is looked up.
# @return [Pry::Method, nil]
def from_obj(obj, name, target=TOPLEVEL_BINDING)
new(lookup_method_via_binding(obj, name, :method, target)) rescue nil
end
# Get all of the instance methods of a `Class` or `Module`
# @param [Class,Module] klass
# @param [Boolean] include_super Whether to include methods from ancestors.
# @return [Array[Pry::Method]]
def all_from_class(klass, include_super=true)
2014-10-14 12:31:27 -04:00
%w(public protected private).flat_map do |visibility|
safe_send(klass, :"#{visibility}_instance_methods", include_super).map do |method_name|
new(safe_send(klass, :instance_method, method_name), :visibility => visibility.to_sym)
end
2014-10-14 12:31:27 -04:00
end
end
#
# Get all of the methods on an `Object`
#
# @param [Object] obj
#
# @param [Boolean] include_super
# indicates whether or not to include methods from ancestors.
#
# @return [Array[Pry::Method]]
#
def all_from_obj(obj, include_super=true)
all_from_class(singleton_class_of(obj), include_super)
end
#
# @deprecated
2015-08-17 10:07:41 -04:00
# please use {all_from_obj} instead.
# the `method_type` argument is ignored.
#
def all_from_common(obj, method_type = nil, include_super=true)
all_from_obj(obj, include_super)
end
# Get every `Class` and `Module`, in order, that will be checked when looking
# for an instance method to call on this object.
# @param [Object] obj
# @return [Array[Class, Module]]
def resolution_order(obj)
if Class === obj
singleton_class_resolution_order(obj) + instance_resolution_order(Class)
else
klass = singleton_class_of(obj) rescue obj.class
instance_resolution_order(klass)
end
end
# Get every `Class` and `Module`, in order, that will be checked when looking
# for methods on instances of the given `Class` or `Module`.
# This does not treat singleton classes of classes specially.
# @param [Class, Module] klass
# @return [Array[Class, Module]]
def instance_resolution_order(klass)
# include klass in case it is a singleton class,
([klass] + Pry::Method.safe_send(klass, :ancestors)).uniq
end
def method_definition?(name, definition_line)
singleton_method_definition?(name, definition_line) ||
instance_method_definition?(name, definition_line)
end
def singleton_method_definition?(name, definition_line)
/^define_singleton_method\(?\s*[:\"\']#{Regexp.escape(name)}|^def\s*self\.#{Regexp.escape(name)}/ =~ definition_line.strip
end
def instance_method_definition?(name, definition_line)
/^define_method\(?\s*[:\"\']#{Regexp.escape(name)}|^def\s*#{Regexp.escape(name)}/ =~ definition_line.strip
end
# Get the singleton classes of superclasses that could define methods on
# the given class object, and any modules they include.
# If a module is included at multiple points in the ancestry, only
# the lowest copy will be returned.
def singleton_class_resolution_order(klass)
ancestors = Pry::Method.safe_send(klass, :ancestors)
2014-10-14 12:31:27 -04:00
resolution_order = ancestors.grep(Class).flat_map do |anc|
[singleton_class_of(anc), *singleton_class_of(anc).included_modules]
2014-10-14 12:31:27 -04:00
end
resolution_order.reverse.uniq.reverse - Class.included_modules
end
2014-02-05 18:32:45 -05:00
def singleton_class_of(obj)
begin
class << obj; self; end
rescue TypeError # can't define singleton. Fixnum, Symbol, Float, ...
obj.class
end
end
end
2011-10-02 04:25:49 -04:00
# A new instance of `Pry::Method` wrapping the given `::Method`, `UnboundMethod`, or `Proc`.
#
# @param [::Method, UnboundMethod, Proc] method
2012-06-27 01:30:00 -04:00
# @param [Hash] known_info Can be used to pre-cache expensive to compute stuff.
2011-10-02 04:25:49 -04:00
# @return [Pry::Method]
def initialize(method, known_info={})
@method = method
@visibility = known_info[:visibility]
end
# Get the name of the method as a String, regardless of the underlying Method#name type.
# @return [String]
def name
@method.name.to_s
end
# Get the owner of the method as a Pry::Module
# @return [Pry::Module]
def wrapped_owner
@wrapped_owner ||= Pry::WrappedModule.new(owner)
end
# Get underlying object wrapped by this Pry::Method instance
# @return [Method, UnboundMethod, Proc]
def wrapped
@method
end
# Is the method undefined? (aka `Disowned`)
# @return [Boolean] false
def undefined?
false
end
# Get the name of the method including the class on which it was defined.
# @example
# method(:puts).method_name
# => "Kernel.puts"
# @return [String]
def name_with_owner
"#{wrapped_owner.method_prefix}#{name}"
end
2011-10-02 04:25:49 -04:00
# @return [String, nil] The source code of the method, or `nil` if it's unavailable.
def source
@source ||= case source_type
when :c
2013-03-28 02:48:20 -04:00
c_source
when :ruby
ruby_source
end
end
# Update the live copy of the method's source.
def redefine(source)
Patcher.new(self).patch_in_ram source
Pry::Method(owner.instance_method(name))
end
2012-06-03 23:09:00 -04:00
# Can we get the source code for this method?
# @return [Boolean]
def source?
!!source
rescue MethodSource::SourceNotFoundError
false
end
2011-10-02 04:25:49 -04:00
# @return [String, nil] The documentation for the method, or `nil` if it's
# unavailable.
def doc
@doc ||=
case source_type
when :c
info = pry_doc_info
info.docstring if info
when :ruby
2013-05-10 03:27:01 -04:00
get_comment_content(comment)
end
end
2011-10-02 04:25:49 -04:00
# @return [Symbol] The source type of the method. The options are
2011-11-06 01:02:40 -04:00
# `:ruby` for Ruby methods or `:c` for methods written in C.
def source_type
2011-11-06 01:02:40 -04:00
source_location.nil? ? :c : :ruby
end
2011-10-02 04:25:49 -04:00
# @return [String, nil] The name of the file the method is defined in, or
# `nil` if the filename is unavailable.
def source_file
2011-10-02 23:13:10 -04:00
if source_location.nil?
if source_type == :c
2011-10-02 23:13:10 -04:00
info = pry_doc_info
info.file if info
end
else
source_location.first
end
end
2011-10-02 04:25:49 -04:00
# @return [Fixnum, nil] The line of code in `source_file` which begins
# the method's definition, or `nil` if that information is unavailable.
def source_line
source_location.nil? ? nil : source_location.last
end
# @return [Range, nil] The range of lines in `source_file` which contain
# the method's definition, or `nil` if that information is unavailable.
def source_range
source_location.nil? ? nil : (source_line)..(source_line + source.lines.count - 1)
end
2011-10-02 04:25:49 -04:00
# @return [Symbol] The visibility of the method. May be `:public`,
# `:protected`, or `:private`.
def visibility
2011-10-26 00:39:35 -04:00
@visibility ||= if owner.public_instance_methods.any? { |m| m.to_s == name }
:public
2011-10-26 00:39:35 -04:00
elsif owner.protected_instance_methods.any? { |m| m.to_s == name }
:protected
2011-10-26 00:41:19 -04:00
elsif owner.private_instance_methods.any? { |m| m.to_s == name }
:private
else
:none
end
end
2011-10-02 04:25:49 -04:00
# @return [String] A representation of the method's signature, including its
# name and parameters. Optional and "rest" parameters are marked with `*`
2018-02-20 22:46:04 -05:00
# and block parameters with `&`. Keyword arguments are shown with `:`
2018-02-20 16:44:16 -05:00
# If the parameter names are unavailable, they're given numbered names instead.
2011-10-02 04:25:49 -04:00
# Paraphrased from `awesome_print` gem.
def signature
2011-09-25 01:51:06 -04:00
if respond_to?(:parameters)
2018-02-20 22:46:04 -05:00
args = parameters.inject([]) do |args_array, (arg_type, name)|
name ||= (arg_type == :block ? 'block' : "arg#{args_array.size + 1}")
args_array.push(
case arg_type
when :req then name.to_s
when :opt then "#{name}=?"
when :rest then "*#{name}"
when :block then "&#{name}"
when :key then "#{name}:?"
when :keyreq then "#{name}:"
else '?'
end
)
end
else
args = (1..arity.abs).map { |i| "arg#{i}" }
args[-1] = "*#{args[-1]}" if arity < 0
end
"#{name}(#{args.join(', ')})"
end
# @return [Pry::Method, nil] The wrapped method that is called when you
2011-10-14 03:02:55 -04:00
# use "super" in the body of this method.
def super(times=1)
2012-02-01 02:04:52 -05:00
if UnboundMethod === @method
sup = super_using_ancestors(Pry::Method.instance_resolution_order(owner), times)
else
2011-10-14 03:02:55 -04:00
sup = super_using_ancestors(Pry::Method.resolution_order(receiver), times)
sup &&= sup.bind(receiver)
end
Pry::Method.new(sup) if sup
end
# @return [String, nil] The original name the method was defined under,
# before any aliasing, or `nil` if it can't be determined.
def original_name
return nil if source_type != :ruby
2011-11-26 21:33:13 -05:00
method_name_from_first_line(source.lines.first)
end
2011-10-02 04:25:49 -04:00
# @return [Boolean] Was the method defined outside a source file?
def dynamically_defined?
2011-10-02 04:25:49 -04:00
!!(source_file and source_file =~ /(\(.*\))|<.*>/)
end
# @return [Boolean] Whether the method is unbound.
def unbound_method?
is_a?(::UnboundMethod)
end
# @return [Boolean] Whether the method is bound.
def bound_method?
is_a?(::Method)
end
# @return [Boolean] Whether the method is a singleton method.
def singleton_method?
wrapped_owner.singleton_class?
end
2011-10-02 04:25:49 -04:00
# @return [Boolean] Was the method defined within the Pry REPL?
def pry_method?
source_file == Pry.eval_path
end
# @return [Array<String>] All known aliases for the method.
def aliases
owner = @method.owner
# Avoid using `to_sym` on {Method#name}, which returns a `String`, because
# it won't be garbage collected.
name = @method.name
all_methods_to_compare = owner.instance_methods | owner.private_instance_methods
alias_list = all_methods_to_compare.combination(2).select do |pair|
pair.include?(name) &&
owner.instance_method(pair.first) == owner.instance_method(pair.last)
end.flatten
alias_list.delete(name)
alias_list.map(&:to_s)
end
# @return [Boolean] Is the method definitely an alias?
def alias?
name != original_name
end
# @return [Boolean]
def ==(obj)
if obj.is_a? Pry::Method
obj == @method
else
@method == obj
end
end
# @param [Class] klass
# @return [Boolean]
2011-09-25 01:14:04 -04:00
def is_a?(klass)
klass == Pry::Method or @method.is_a?(klass)
end
alias kind_of? is_a?
# @param [String, Symbol] method_name
# @return [Boolean]
def respond_to?(method_name, include_all=false)
super or @method.respond_to?(method_name, include_all)
2011-09-25 01:51:06 -04:00
end
2011-10-02 04:25:49 -04:00
# Delegate any unknown calls to the wrapped method.
def method_missing(method_name, *args, &block)
@method.send(method_name, *args, &block)
end
def comment
Pry::Code.from_file(source_file).comment_describing(source_line)
end
private
# @return [YARD::CodeObjects::MethodObject]
# @raise [CommandError] when the method can't be found or `pry-doc` isn't installed.
def pry_doc_info
if Pry.config.has_pry_doc
Pry::MethodInfo.info_for(@method) or raise CommandError, "Cannot locate this method: #{name}. (source_location returns nil)"
else
fail_msg = "Cannot locate this method: #{name}."
if mri?
fail_msg += " Invoke the 'gem-install pry-doc' Pry command to get access to Ruby Core documentation.\n"
end
raise CommandError, fail_msg
end
end
# @param [Class, Module] ancestors The ancestors to investigate
# @return [Method] The unwrapped super-method
def super_using_ancestors(ancestors, times=1)
next_owner = self.owner
times.times do
i = ancestors.index(next_owner) + 1
while ancestors[i] && !(ancestors[i].method_defined?(name) || ancestors[i].private_method_defined?(name))
i += 1
end
next_owner = ancestors[i] or return nil
2011-10-14 03:02:55 -04:00
end
2011-11-26 21:33:13 -05:00
safe_send(next_owner, :instance_method, name) rescue nil
end
2011-11-26 21:33:13 -05:00
# @param [String] first_ln The first line of a method definition.
# @return [String, nil]
def method_name_from_first_line(first_ln)
return nil if first_ln.strip !~ /^def /
2011-11-26 21:33:13 -05:00
tokens = CodeRay.scan(first_ln, :ruby)
tokens = tokens.tokens.each_slice(2) if tokens.respond_to?(:tokens)
tokens.each_cons(2) do |t1, t2|
if t2.last == :method || t2.last == :ident && t1 == [".", :operator]
return t2.first
end
2011-11-26 21:33:13 -05:00
end
nil
end
2013-03-28 02:48:20 -04:00
def c_source
info = pry_doc_info
if info and info.source
strip_comments_from_c_code(info.source)
end
end
def ruby_source
# Clone of `MethodSource.source_helper` that knows to use our
# hacked version of `source_location` for our input buffer for methods
# defined in `(pry)`.
2013-03-28 02:48:20 -04:00
file, line = *source_location
raise SourceNotFoundError, "Could not locate source for #{name_with_owner}!" unless file
begin
code = Pry::Code.from_file(file).expression_at(line)
rescue SyntaxError => e
raise MethodSource::SourceNotFoundError.new(e.message)
end
strip_leading_whitespace(code)
end
end
end