summaryrefslogtreecommitdiff
path: root/lib/pry/pry_instance.rb
blob: 241949612a3d77b0a8c8bbc7b4fda08566954eac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
class Pry

  # The list of configuration options.
  CONFIG_OPTIONS = [:input, :output, :commands, :print,
                   :prompt, :hooks]

  attr_accessor *CONFIG_OPTIONS

  # Returns the target binding for the session. Note that altering this
  # attribute will not change the target binding.
  # @return [Binding] The target object for the session
  attr_accessor :session_target

  # Create a new `Pry` object.
  # @param [Hash] options The optional configuration parameters.
  # @option options [#readline] :input The object to use for input. 
  # @option options [#puts] :output The object to use for output. 
  # @option options [Pry::CommandBase] :commands The object to use for
  #   commands. (see commands.rb)
  # @option options [Hash] :hooks The defined hook Procs (see hooks.rb)
  # @option options [Array<Proc>] :default_prompt The array of Procs
  #   to use for the prompts. (see prompts.rb)
  # @option options [Proc] :print The Proc to use for the 'print'
  #   component of the REPL. (see print.rb)
  def initialize(options={})

    default_options = {}
    CONFIG_OPTIONS.each { |v| default_options[v] = Pry.send(v) }
    default_options.merge!(options)

    CONFIG_OPTIONS.each do |key|
      instance_variable_set("@#{key}", default_options[key])
    end
  end

  # Get nesting data.
  # This method should not need to be accessed directly.
  # @return [Array] The unparsed nesting information.
  def nesting
    self.class.nesting
  end

  # Set nesting data.
  # This method should not need to be accessed directly.
  # @param v nesting data.
  def nesting=(v)
    self.class.nesting = v
  end

  # Return parent of current Pry session.
  # @return [Pry] The parent of the current Pry session.
  def parent
    idx = Pry.sessions.index(self)

    if idx > 0
      Pry.sessions[idx - 1]
    else
      nil
    end
  end

  # Execute the hook `hook_name`, if it is defined.
  # @param [Symbol] hook_name The hook to execute
  # @param [Array] args The arguments to pass to the hook.
  def exec_hook(hook_name, *args, &block)
    hooks[hook_name].call(*args, &block) if hooks[hook_name]
  end

  # Initialize the repl session.
  # @param [Binding] target The target binding for the session.
  def repl_prologue(target)
    exec_hook :before_session, output, target
    Pry.active_instance = self

    # Make sure special locals exist
    target.eval("_pry_ = Pry.active_instance")
    target.eval("_ = Pry.last_result")
    self.session_target = target
  end

  # Clean-up after the repl session.
  # @param [Binding] target The target binding for the session.
  # @return [Object] The return value of the repl session (if one exists).
  def repl_epilogue(target, nesting_level, break_data)
    nesting.pop
    exec_hook :after_session, output, target

    # If break_data is an array, then the last element is the return value
    break_level, return_value = Array(break_data)
    
    # keep throwing until we reach the desired nesting level
    if nesting_level != break_level
      throw :breakout, break_data
    end

    return_value
  end
  
  # Start a read-eval-print-loop.
  # If no parameter is given, default to top-level (main).
  # @param [Object, Binding] target The receiver of the Pry session
  # @return [Object] The target of the Pry session or an explictly given
  #   return value. If given return value is `nil` or no return value
  #   is specified then `target` will be returned.
  # @example
  #   Pry.new.repl(Object.new)
  def repl(target=TOPLEVEL_BINDING)
    target = Pry.binding_for(target)
    target_self = target.eval('self')

    repl_prologue(target)
    
    # cannot rely on nesting.level as
    # nesting.level changes with new sessions
    nesting_level = nesting.size

    break_data = catch(:breakout) do
      nesting.push [nesting.size, target_self, self]
      loop do
        rep(target)
      end
    end

    return_value = repl_epilogue(target, nesting_level, break_data)

    # if one was provided, return the return value
    return return_value if return_value
    
    # otherwise return the target_self
    target_self
  end

  # Perform a read-eval-print.
  # If no parameter is given, default to top-level (main).
  # @param [Object, Binding] target The receiver of the read-eval-print
  # @example
  #   Pry.new.rep(Object.new)
  def rep(target=TOPLEVEL_BINDING)
    target = Pry.binding_for(target)
    print.call output, re(target)
  end

  # Perform a read-eval
  # If no parameter is given, default to top-level (main).
  # @param [Object, Binding] target The receiver of the read-eval-print
  # @return [Object] The result of the eval or an `Exception` object in case of error.
  # @example
  #   Pry.new.re(Object.new)
  def re(target=TOPLEVEL_BINDING)
    target = Pry.binding_for(target)

    if input == Readline
      # Readline tab completion
      Readline.completion_proc = Pry::InputCompleter.build_completion_proc(target, commands.commands.keys)
    end


    # save the pry instance to active_instance
    Pry.active_instance = self
    target.eval("_pry_ = Pry.active_instance")

    # eval the expression and save to last_result
    # Do not want __FILE__, __LINE__ here because we need to distinguish
    # (eval) methods for show-method and friends.
    # This also sets the `_` local for the session.
    set_last_result(target.eval(r(target)), target)
  rescue SystemExit => e
    exit
  rescue Exception => e
    set_last_exception(e, target)
  end

  # Perform a read.
  # If no parameter is given, default to top-level (main).
  # This is a multi-line read; so the read continues until a valid
  # Ruby expression is received.
  # Pry commands are also accepted here and operate on the target.
  # @param [Object, Binding] target The receiver of the read.
  # @return [String] The Ruby expression.
  # @example
  #   Pry.new.r(Object.new)
  def r(target=TOPLEVEL_BINDING)
    target = Pry.binding_for(target)
    eval_string = ""

    loop do
      current_prompt = select_prompt(eval_string.empty?, target.eval('self'))

      val = readline(current_prompt)

      # exit pry if we receive EOF character
      if !val
        output.puts
        throw(:breakout, nesting.level) 
      end
      
      val.chomp!

      Pry.cmd_ret_value = process_commands(val, eval_string, target)

      if Pry.cmd_ret_value
        eval_string << "Pry.cmd_ret_value\n"
      else
        eval_string << "#{val}\n"
      end

      break eval_string if valid_expression?(eval_string)
    end
  end

  # Set the last result of an eval.
  # @param [Object] result The result.
  # @param [Binding] target The binding to set `_` on.
  def set_last_result(result, target)
    Pry.last_result = result
    target.eval("_ = Pry.last_result")
  end

  # Set the last exception for a session.
  # @param [Exception] ex The exception.
  # @param [Binding] target The binding to set `_ex_` on.
  def set_last_exception(ex, target)
    Pry.last_exception = ex
    target.eval("_ex_ = Pry.last_exception")
  end

  # Process Pry commands. Pry commands are not Ruby methods and are evaluated
  # prior to Ruby expressions.
  # Commands can be modified/configured by the user: see `Pry::Commands`
  # This method should not need to be invoked directly - it is called
  # by `Pry#r`.
  # @param [String] val The current line of input.
  # @param [String] eval_string The cumulative lines of input for
  #   multi-line input.
  # @param [Binding] target The receiver of the commands.
  def process_commands(val, eval_string, target)
    def val.clear() replace("") end
    def eval_string.clear() replace("") end

    pattern, cmd_data = commands.commands.find do |name, cmd_data|
      /^#{name}(?!\S)(?:\s+(.+))?/ =~ val
    end

    # no command was matched, so return to caller
    return if !pattern
    
    args_string = $1
    args = args_string ? Shellwords.shellwords(args_string) : []
    action = cmd_data[:action]
    keep_retval = cmd_data[:keep_retval]
    
    options = {
      :val => val,
      :eval_string => eval_string,
      :nesting => nesting,
      :commands => commands.commands
    }

    # set some useful methods to be used by the action blocks
    commands.opts = options
    commands.target = target
    commands.output = output

    case action.arity <=> 0
    when -1

      # Use instance_exec() to make the `opts` method, etc available
      ret_value = commands.instance_exec(*args, &action)
    when 1, 0

      # ensure that we get the right number of parameters
      # since 1.8.7 complains about incorrect arity (1.9.2
      # doesn't care)
      args_with_corrected_arity = args.values_at *0..(action.arity - 1)
      ret_value = commands.instance_exec(*args_with_corrected_arity, &action)
    end
    
    # a command was processed so we can now clear the input string
    val.clear

    # return value of block only if :keep_retval is true
    ret_value if keep_retval
  end

  # Returns the next line of input to be used by the pry instance.
  # This method should not need to be invoked directly.
  # @param [String] current_prompt The prompt to use for input.
  # @return [String] The next line of input.
  def readline(current_prompt="> ")

    if input == Readline

      # Readline must be treated differently
      # as it has a second parameter.
      input.readline(current_prompt, true)
    else
      if input.method(:readline).arity == 1
        input.readline(current_prompt)
      else
        input.readline
      end
    end
  end

  # Returns the appropriate prompt to use.
  # This method should not need to be invoked directly.
  # @param [Boolean] first_line Whether this is the first line of input
  #   (and not multi-line input).
  # @param [Object] target_self The receiver of the Pry session.
  # @return [String] The prompt.
  def select_prompt(first_line, target_self)

    if first_line
      Array(prompt).first.call(target_self, nesting.level)
    else
      Array(prompt).last.call(target_self, nesting.level)
    end
  end

  if RUBY_VERSION =~ /1.9/
    require 'ripper'

    # Determine if a string of code is a valid Ruby expression.
    # Ruby 1.9 uses Ripper, Ruby 1.8 uses RubyParser.
    # @param [String] code The code to validate.
    # @return [Boolean] Whether or not the code is a valid Ruby expression.
    # @example
    #   valid_expression?("class Hello") #=> false
    #   valid_expression?("class Hello; end") #=> true
    def valid_expression?(code)
      !!Ripper::SexpBuilder.new(code).parse
    end

  else
    require 'ruby_parser'

    # Determine if a string of code is a valid Ruby expression.
    # Ruby 1.9 uses Ripper, Ruby 1.8 uses RubyParser.
    # @param [String] code The code to validate.
    # @return [Boolean] Whether or not the code is a valid Ruby expression.
    # @example
    #   valid_expression?("class Hello") #=> false
    #   valid_expression?("class Hello; end") #=> true
    def valid_expression?(code)
      RubyParser.new.parse(code)
    rescue Racc::ParseError, SyntaxError
      false
    else
      true
    end
  end
end