/lib/pry/pry_instance.rb

http://github.com/pry/pry · Ruby · 701 lines · 390 code · 79 blank · 232 comment · 42 complexity · 67cc0be34168625e8d734016ffedf0e4 MD5 · raw file

  1. # frozen_string_literal: true
  2. require 'method_source'
  3. require 'ostruct'
  4. ##
  5. # Pry is a powerful alternative to the standard IRB shell for Ruby. It
  6. # features syntax highlighting, a flexible plugin architecture, runtime
  7. # invocation and source and documentation browsing.
  8. #
  9. # Pry can be started similar to other command line utilities by simply running
  10. # the following command:
  11. #
  12. # pry
  13. #
  14. # Once inside Pry you can invoke the help message:
  15. #
  16. # help
  17. #
  18. # This will show a list of available commands and their usage. For more
  19. # information about Pry you can refer to the following resources:
  20. #
  21. # * http://pryrepl.org/
  22. # * https://github.com/pry/pry
  23. # * the IRC channel, which is #pry on the Freenode network
  24. #
  25. # rubocop:disable Metrics/ClassLength
  26. class Pry
  27. extend Pry::Forwardable
  28. attr_accessor :binding_stack
  29. attr_accessor :custom_completions
  30. attr_accessor :eval_string
  31. attr_accessor :backtrace
  32. attr_accessor :suppress_output
  33. attr_accessor :last_result
  34. attr_accessor :last_file
  35. attr_accessor :last_dir
  36. attr_reader :last_exception
  37. attr_reader :exit_value
  38. # @since v0.12.0
  39. attr_reader :input_ring
  40. # @since v0.12.0
  41. attr_reader :output_ring
  42. attr_reader :config
  43. def_delegators(
  44. :@config, :input, :input=, :output, :output=, :commands,
  45. :commands=, :print, :print=, :exception_handler, :exception_handler=,
  46. :hooks, :hooks=, :color, :color=, :pager, :pager=, :editor, :editor=,
  47. :memory_size, :memory_size=, :extra_sticky_locals, :extra_sticky_locals=
  48. )
  49. EMPTY_COMPLETIONS = [].freeze
  50. # Create a new {Pry} instance.
  51. # @param [Hash] options
  52. # @option options [#readline] :input
  53. # The object to use for input.
  54. # @option options [#puts] :output
  55. # The object to use for output.
  56. # @option options [Pry::CommandBase] :commands
  57. # The object to use for commands.
  58. # @option options [Hash] :hooks
  59. # The defined hook Procs.
  60. # @option options [Pry::Prompt] :prompt
  61. # The array of Procs to use for prompts.
  62. # @option options [Proc] :print
  63. # The Proc to use for printing return values.
  64. # @option options [Boolean] :quiet
  65. # Omit the `whereami` banner when starting.
  66. # @option options [Array<String>] :backtrace
  67. # The backtrace of the session's `binding.pry` line, if applicable.
  68. # @option options [Object] :target
  69. # The initial context for this session.
  70. def initialize(options = {})
  71. @binding_stack = []
  72. @indent = Pry::Indent.new(self)
  73. @eval_string = ''.dup
  74. @backtrace = options.delete(:backtrace) || caller
  75. target = options.delete(:target)
  76. @config = self.class.config.merge(options)
  77. push_prompt(config.prompt)
  78. @input_ring = Pry::Ring.new(config.memory_size)
  79. @output_ring = Pry::Ring.new(config.memory_size)
  80. @custom_completions = config.command_completions
  81. set_last_result nil
  82. @input_ring << nil
  83. push_initial_binding(target)
  84. exec_hook(:when_started, target, options, self)
  85. @prompt_warn = false
  86. end
  87. # This is the prompt at the top of the prompt stack.
  88. # @return [Pry::Prompt] the current prompt
  89. def prompt
  90. prompt_stack.last
  91. end
  92. # Sets the Pry prompt.
  93. # @param [Pry::Prompt] new_prompt
  94. # @return [void]
  95. def prompt=(new_prompt)
  96. if prompt_stack.empty?
  97. push_prompt new_prompt
  98. else
  99. prompt_stack[-1] = new_prompt
  100. end
  101. end
  102. # Initialize this instance by pushing its initial context into the binding
  103. # stack. If no target is given, start at the top level.
  104. def push_initial_binding(target = nil)
  105. push_binding(target || Pry.toplevel_binding)
  106. end
  107. # The currently active `Binding`.
  108. # @return [Binding] The currently active `Binding` for the session.
  109. def current_binding
  110. binding_stack.last
  111. end
  112. alias current_context current_binding # support previous API
  113. # Push a binding for the given object onto the stack. If this instance is
  114. # currently stopped, mark it as usable again.
  115. def push_binding(object)
  116. @stopped = false
  117. binding_stack << Pry.binding_for(object)
  118. end
  119. #
  120. # Generate completions.
  121. #
  122. # @param [String] str
  123. # What the user has typed so far
  124. #
  125. # @return [Array<String>]
  126. # Possible completions
  127. #
  128. def complete(str)
  129. return EMPTY_COMPLETIONS unless config.completer
  130. Pry.critical_section do
  131. completer = config.completer.new(config.input, self)
  132. completer.call(
  133. str,
  134. target: current_binding,
  135. custom_completions: custom_completions.call.push(*sticky_locals.keys)
  136. )
  137. end
  138. end
  139. #
  140. # Injects a local variable into the provided binding.
  141. #
  142. # @param [String] name
  143. # The name of the local to inject.
  144. #
  145. # @param [Object] value
  146. # The value to set the local to.
  147. #
  148. # @param [Binding] binding
  149. # The binding to set the local on.
  150. #
  151. # @return [Object]
  152. # The value the local was set to.
  153. #
  154. def inject_local(name, value, binding)
  155. value = value.is_a?(Proc) ? value.call : value
  156. if binding.respond_to?(:local_variable_set)
  157. binding.local_variable_set name, value
  158. else # < 2.1
  159. begin
  160. Pry.current[:pry_local] = value
  161. binding.eval "#{name} = ::Pry.current[:pry_local]"
  162. ensure
  163. Pry.current[:pry_local] = nil
  164. end
  165. end
  166. end
  167. undef :memory_size if method_defined? :memory_size
  168. # @return [Integer] The maximum amount of objects remembered by the inp and
  169. # out arrays. Defaults to 100.
  170. def memory_size
  171. @output_ring.max_size
  172. end
  173. undef :memory_size= if method_defined? :memory_size=
  174. def memory_size=(size)
  175. @input_ring = Pry::Ring.new(size)
  176. @output_ring = Pry::Ring.new(size)
  177. end
  178. # Inject all the sticky locals into the current binding.
  179. def inject_sticky_locals!
  180. sticky_locals.each_pair do |name, value|
  181. inject_local(name, value, current_binding)
  182. end
  183. end
  184. # Add a sticky local to this Pry instance.
  185. # A sticky local is a local that persists between all bindings in a session.
  186. # @param [Symbol] name The name of the sticky local.
  187. # @yield The block that defines the content of the local. The local
  188. # will be refreshed at each tick of the repl loop.
  189. def add_sticky_local(name, &block)
  190. config.extra_sticky_locals[name] = block
  191. end
  192. def sticky_locals
  193. {
  194. _in_: input_ring,
  195. _out_: output_ring,
  196. pry_instance: self,
  197. _ex_: last_exception && last_exception.wrapped_exception,
  198. _file_: last_file,
  199. _dir_: last_dir,
  200. _: proc { last_result },
  201. __: proc { output_ring[-2] }
  202. }.merge(config.extra_sticky_locals)
  203. end
  204. # Reset the current eval string. If the user has entered part of a multiline
  205. # expression, this discards that input.
  206. def reset_eval_string
  207. @eval_string = ''.dup
  208. end
  209. # Pass a line of input to Pry.
  210. #
  211. # This is the equivalent of `Binding#eval` but with extra Pry!
  212. #
  213. # In particular:
  214. # 1. Pry commands will be executed immediately if the line matches.
  215. # 2. Partial lines of input will be queued up until a complete expression has
  216. # been accepted.
  217. # 3. Output is written to `#output` in pretty colours, not returned.
  218. #
  219. # Once this method has raised an exception or returned false, this instance
  220. # is no longer usable. {#exit_value} will return the session's breakout
  221. # value if applicable.
  222. #
  223. # @param [String?] line The line of input; `nil` if the user types `<Ctrl-D>`
  224. # @option options [Boolean] :generated Whether this line was generated automatically.
  225. # Generated lines are not stored in history.
  226. # @return [Boolean] Is Pry ready to accept more input?
  227. # @raise [Exception] If the user uses the `raise-up` command, this method
  228. # will raise that exception.
  229. def eval(line, options = {})
  230. return false if @stopped
  231. exit_value = nil
  232. exception = catch(:raise_up) do
  233. exit_value = catch(:breakout) do
  234. handle_line(line, options)
  235. # We use 'return !@stopped' here instead of 'return true' so that if
  236. # handle_line has stopped this pry instance (e.g. by opening pry_instance.repl and
  237. # then popping all the bindings) we still exit immediately.
  238. return !@stopped
  239. end
  240. exception = false
  241. end
  242. @stopped = true
  243. @exit_value = exit_value
  244. # TODO: make this configurable?
  245. raise exception if exception
  246. false
  247. end
  248. # Potentially deprecated. Use `Pry::REPL.new(pry, :target => target).start`
  249. # (If nested sessions are going to exist, this method is fine, but a goal is
  250. # to come up with an alternative to nested sessions altogether.)
  251. def repl(target = nil)
  252. Pry::REPL.new(self, target: target).start
  253. end
  254. def evaluate_ruby(code)
  255. inject_sticky_locals!
  256. exec_hook :before_eval, code, self
  257. result = current_binding.eval(code, Pry.eval_path, Pry.current_line)
  258. set_last_result(result, code)
  259. ensure
  260. update_input_history(code)
  261. exec_hook :after_eval, result, self
  262. end
  263. # Output the result or pass to an exception handler (if result is an exception).
  264. def show_result(result)
  265. if last_result_is_exception?
  266. exception_handler.call(output, result, self)
  267. elsif should_print?
  268. print.call(output, result, self)
  269. end
  270. rescue RescuableException => e
  271. # Being uber-paranoid here, given that this exception arose because we couldn't
  272. # serialize something in the user's program, let's not assume we can serialize
  273. # the exception either.
  274. begin
  275. output.puts "(pry) output error: #{e.inspect}\n#{e.backtrace.join("\n")}"
  276. rescue RescuableException
  277. if last_result_is_exception?
  278. output.puts "(pry) output error: failed to show exception"
  279. else
  280. output.puts "(pry) output error: failed to show result"
  281. end
  282. end
  283. ensure
  284. output.flush if output.respond_to?(:flush)
  285. end
  286. # If the given line is a valid command, process it in the context of the
  287. # current `eval_string` and binding.
  288. # @param [String] val The line to process.
  289. # @return [Boolean] `true` if `val` is a command, `false` otherwise
  290. def process_command(val)
  291. val = val.lstrip if /^\s\S/ !~ val
  292. val = val.chomp
  293. result = commands.process_line(
  294. val,
  295. target: current_binding,
  296. output: output,
  297. eval_string: @eval_string,
  298. pry_instance: self,
  299. hooks: hooks
  300. )
  301. # set a temporary (just so we can inject the value we want into eval_string)
  302. Pry.current[:pry_cmd_result] = result
  303. # note that `result` wraps the result of command processing; if a
  304. # command was matched and invoked then `result.command?` returns true,
  305. # otherwise it returns false.
  306. if result.command?
  307. unless result.void_command?
  308. # the command that was invoked was non-void (had a return value) and so we make
  309. # the value of the current expression equal to the return value
  310. # of the command.
  311. @eval_string = "::Pry.current[:pry_cmd_result].retval\n"
  312. end
  313. true
  314. else
  315. false
  316. end
  317. end
  318. # Same as process_command, but outputs exceptions to `#output` instead of
  319. # raising.
  320. # @param [String] val The line to process.
  321. # @return [Boolean] `true` if `val` is a command, `false` otherwise
  322. def process_command_safely(val)
  323. process_command(val)
  324. rescue CommandError,
  325. Pry::Slop::InvalidOptionError,
  326. MethodSource::SourceNotFoundError => e
  327. Pry.last_internal_error = e
  328. output.puts "Error: #{e.message}"
  329. true
  330. end
  331. # Run the specified command.
  332. # @param [String] val The command (and its params) to execute.
  333. # @return [Pry::Command::VOID_VALUE]
  334. # @example
  335. # pry_instance.run_command("ls -m")
  336. def run_command(val)
  337. commands.process_line(
  338. val,
  339. eval_string: @eval_string,
  340. target: current_binding,
  341. pry_instance: self,
  342. output: output
  343. )
  344. Pry::Command::VOID_VALUE
  345. end
  346. # Execute the specified hook.
  347. # @param [Symbol] name The hook name to execute
  348. # @param [*Object] args The arguments to pass to the hook
  349. # @return [Object, Exception] The return value of the hook or the exception raised
  350. #
  351. # If executing a hook raises an exception, we log that and then continue sucessfully.
  352. # To debug such errors, use the global variable $pry_hook_error, which is set as a
  353. # result.
  354. def exec_hook(name, *args, &block)
  355. e_before = hooks.errors.size
  356. hooks.exec_hook(name, *args, &block).tap do
  357. hooks.errors[e_before..-1].each do |e|
  358. output.puts "#{name} hook failed: #{e.class}: #{e.message}"
  359. output.puts e.backtrace.first.to_s
  360. output.puts "(see pry_instance.hooks.errors to debug)"
  361. end
  362. end
  363. end
  364. # Set the last result of an eval.
  365. # This method should not need to be invoked directly.
  366. # @param [Object] result The result.
  367. # @param [String] code The code that was run.
  368. def set_last_result(result, code = "")
  369. @last_result_is_exception = false
  370. @output_ring << result
  371. self.last_result = result unless code =~ /\A\s*\z/
  372. end
  373. # Set the last exception for a session.
  374. # @param [Exception] exception The last exception.
  375. def last_exception=(exception)
  376. @last_result_is_exception = true
  377. last_exception = Pry::LastException.new(exception)
  378. @output_ring << last_exception
  379. @last_exception = last_exception
  380. end
  381. # Update Pry's internal state after evalling code.
  382. # This method should not need to be invoked directly.
  383. # @param [String] code The code we just eval'd
  384. def update_input_history(code)
  385. # Always push to the @input_ring as the @output_ring is always pushed to.
  386. @input_ring << code
  387. return unless code
  388. Pry.line_buffer.push(*code.each_line)
  389. Pry.current_line += code.lines.count
  390. end
  391. # @return [Boolean] True if the last result is an exception that was raised,
  392. # as opposed to simply an instance of Exception (like the result of
  393. # Exception.new)
  394. def last_result_is_exception?
  395. @last_result_is_exception
  396. end
  397. # Whether the print proc should be invoked.
  398. # Currently only invoked if the output is not suppressed.
  399. # @return [Boolean] Whether the print proc should be invoked.
  400. def should_print?
  401. !@suppress_output
  402. end
  403. # Returns the appropriate prompt to use.
  404. # @return [String] The prompt.
  405. def select_prompt
  406. object = current_binding.eval('self')
  407. open_token = @indent.open_delimiters.last || @indent.stack.last
  408. c = OpenStruct.new(
  409. object: object,
  410. nesting_level: binding_stack.size - 1,
  411. open_token: open_token,
  412. session_line: Pry.history.session_line_count + 1,
  413. history_line: Pry.history.history_line_count + 1,
  414. expr_number: input_ring.count,
  415. pry_instance: self,
  416. binding_stack: binding_stack,
  417. input_ring: input_ring,
  418. eval_string: @eval_string,
  419. cont: !@eval_string.empty?
  420. )
  421. Pry.critical_section do
  422. # If input buffer is empty, then use normal prompt. Otherwise use the wait
  423. # prompt (indicating multi-line expression).
  424. if prompt.is_a?(Pry::Prompt)
  425. prompt_proc = eval_string.empty? ? prompt.wait_proc : prompt.incomplete_proc
  426. return prompt_proc.call(c.object, c.nesting_level, c.pry_instance)
  427. end
  428. unless @prompt_warn
  429. @prompt_warn = true
  430. Kernel.warn(
  431. "warning: setting prompt with help of " \
  432. "`Pry.config.prompt = [proc {}, proc {}]` is deprecated. " \
  433. "Use Pry::Prompt API instead"
  434. )
  435. end
  436. # If input buffer is empty then use normal prompt
  437. if eval_string.empty?
  438. generate_prompt(Array(prompt).first, c)
  439. # Otherwise use the wait prompt (indicating multi-line expression)
  440. else
  441. generate_prompt(Array(prompt).last, c)
  442. end
  443. end
  444. end
  445. # Pushes the current prompt onto a stack that it can be restored from later.
  446. # Use this if you wish to temporarily change the prompt.
  447. #
  448. # @example
  449. # push_prompt(Pry::Prompt[:my_prompt])
  450. #
  451. # @param [Pry::Prompt] new_prompt
  452. # @return [Pry::Prompt] new_prompt
  453. def push_prompt(new_prompt)
  454. prompt_stack.push new_prompt
  455. end
  456. # Pops the current prompt off of the prompt stack. If the prompt you are
  457. # popping is the last prompt, it will not be popped. Use this to restore the
  458. # previous prompt.
  459. #
  460. # @example
  461. # pry = Pry.new(prompt: Pry::Prompt[:my_prompt1])
  462. # pry.push_prompt(Pry::Prompt[:my_prompt2])
  463. # pry.pop_prompt # => prompt2
  464. # pry.pop_prompt # => prompt1
  465. # pry.pop_prompt # => prompt1
  466. #
  467. # @return [Pry::Prompt] the prompt being popped
  468. def pop_prompt
  469. prompt_stack.size > 1 ? prompt_stack.pop : prompt
  470. end
  471. undef :pager if method_defined? :pager
  472. # Returns the currently configured pager
  473. # @example
  474. # pry_instance.pager.page text
  475. def pager
  476. Pry::Pager.new(self)
  477. end
  478. undef :output if method_defined? :output
  479. # Returns an output device
  480. # @example
  481. # pry_instance.output.puts "ohai!"
  482. def output
  483. Pry::Output.new(self)
  484. end
  485. # Raise an exception out of Pry.
  486. #
  487. # See Kernel#raise for documentation of parameters.
  488. # See rb_make_exception for the inbuilt implementation.
  489. #
  490. # This is necessary so that the raise-up command can tell the
  491. # difference between an exception the user has decided to raise,
  492. # and a mistake in specifying that exception.
  493. #
  494. # (i.e. raise-up RunThymeError.new should not be the same as
  495. # raise-up NameError, "unititialized constant RunThymeError")
  496. #
  497. def raise_up_common(force, *args)
  498. exception = if args == []
  499. last_exception || RuntimeError.new
  500. elsif args.length == 1 && args.first.is_a?(String)
  501. RuntimeError.new(args.first)
  502. elsif args.length > 3
  503. raise ArgumentError, "wrong number of arguments"
  504. elsif !args.first.respond_to?(:exception)
  505. raise TypeError, "exception class/object expected"
  506. elsif args.size == 1
  507. args.first.exception
  508. else
  509. args.first.exception(args[1])
  510. end
  511. raise TypeError, "exception object expected" unless exception.is_a? Exception
  512. exception.set_backtrace(args.size == 3 ? args[2] : caller(1))
  513. if force || binding_stack.one?
  514. binding_stack.clear
  515. throw :raise_up, exception
  516. else
  517. binding_stack.pop
  518. raise exception
  519. end
  520. end
  521. def raise_up(*args)
  522. raise_up_common(false, *args)
  523. end
  524. def raise_up!(*args)
  525. raise_up_common(true, *args)
  526. end
  527. # Convenience accessor for the `quiet` config key.
  528. # @return [Boolean]
  529. def quiet?
  530. config.quiet
  531. end
  532. private
  533. def handle_line(line, options)
  534. if line.nil?
  535. config.control_d_handler.call(self)
  536. return
  537. end
  538. ensure_correct_encoding!(line)
  539. Pry.history << line unless options[:generated]
  540. @suppress_output = false
  541. inject_sticky_locals!
  542. begin
  543. unless process_command_safely(line)
  544. @eval_string += "#{line.chomp}\n" if !line.empty? || !@eval_string.empty?
  545. end
  546. rescue RescuableException => e
  547. self.last_exception = e
  548. result = e
  549. Pry.critical_section do
  550. show_result(result)
  551. end
  552. return
  553. end
  554. # This hook is supposed to be executed after each line of ruby code
  555. # has been read (regardless of whether eval_string is yet a complete expression)
  556. exec_hook :after_read, eval_string, self
  557. begin
  558. complete_expr = Pry::Code.complete_expression?(@eval_string)
  559. rescue SyntaxError => e
  560. output.puts e.message.gsub(/^.*syntax error, */, "SyntaxError: ")
  561. reset_eval_string
  562. end
  563. if complete_expr
  564. if @eval_string =~ /;\Z/ || @eval_string.empty? || @eval_string =~ /\A *#.*\n\z/
  565. @suppress_output = true
  566. end
  567. # A bug in jruby makes java.lang.Exception not rescued by
  568. # `rescue Pry::RescuableException` clause.
  569. #
  570. # * https://github.com/pry/pry/issues/854
  571. # * https://jira.codehaus.org/browse/JRUBY-7100
  572. #
  573. # Until that gets fixed upstream, treat java.lang.Exception
  574. # as an additional exception to be rescued explicitly.
  575. #
  576. # This workaround has a side effect: java exceptions specified
  577. # in `Pry.config.unrescued_exceptions` are ignored.
  578. jruby_exceptions = []
  579. jruby_exceptions << Java::JavaLang::Exception if Helpers::Platform.jruby?
  580. begin
  581. # Reset eval string, in case we're evaluating Ruby that does something
  582. # like open a nested REPL on this instance.
  583. eval_string = @eval_string
  584. reset_eval_string
  585. result = evaluate_ruby(eval_string)
  586. rescue RescuableException, *jruby_exceptions => e
  587. # Eliminate following warning:
  588. # warning: singleton on non-persistent Java type X
  589. # (http://wiki.jruby.org/Persistence)
  590. if Helpers::Platform.jruby? && e.class.respond_to?('__persistent__')
  591. e.class.__persistent__ = true
  592. end
  593. self.last_exception = e
  594. result = e
  595. end
  596. Pry.critical_section do
  597. show_result(result)
  598. end
  599. end
  600. throw(:breakout) if current_binding.nil?
  601. end
  602. # Force `eval_string` into the encoding of `val`. [Issue #284]
  603. def ensure_correct_encoding!(val)
  604. if @eval_string.empty? &&
  605. val.respond_to?(:encoding) &&
  606. val.encoding != @eval_string.encoding
  607. @eval_string.force_encoding(val.encoding)
  608. end
  609. end
  610. def generate_prompt(prompt_proc, conf)
  611. if prompt_proc.arity == 1
  612. prompt_proc.call(conf)
  613. else
  614. prompt_proc.call(conf.object, conf.nesting_level, conf.pry_instance)
  615. end
  616. end
  617. # the array that the prompt stack is stored in
  618. def prompt_stack
  619. @prompt_stack ||= []
  620. end
  621. end
  622. # rubocop:enable Metrics/ClassLength