Class: IRB::Irb

Inherits:
Object show all
Defined in:
lib/irb.rb,
lib/irb/ext/multi-irb.rb

Constant Summary collapse

PROMPT_MAIN_TRUNCATE_LENGTH =

Note: instance and index assignment expressions could also be written like: “foo.bar=(1)” and “foo.[]=(1, bar)”, when expressed that way, the former be parsed as :assign and echo will be suppressed, but the latter is parsed as a :method_add_arg and the output won’t be suppressed

32
PROMPT_MAIN_TRUNCATE_OMISSION =
'...'
CONTROL_CHARACTERS_PATTERN =
"\x00-\x1F"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(workspace = nil, input_method = nil, from_binding: false) ⇒ Irb

Creates a new irb session



88
89
90
91
92
93
94
95
96
# File 'lib/irb.rb', line 88

def initialize(workspace = nil, input_method = nil, from_binding: false)
  @from_binding = from_binding
  @prompt_part_cache = nil
  @context = Context.new(self, workspace, input_method)
  @context.workspace.load_helper_methods_to_main
  @signal_status = :IN_IRB
  @scanner = RubyLex.new
  @line_no = 1
end

Instance Attribute Details

#contextObject (readonly)

Returns the current context of this irb session



81
82
83
# File 'lib/irb.rb', line 81

def context
  @context
end

#from_bindingObject (readonly)

Returns the value of attribute from_binding.



85
86
87
# File 'lib/irb.rb', line 85

def from_binding
  @from_binding
end

#scannerObject

The lexer used by this irb session



83
84
85
# File 'lib/irb.rb', line 83

def scanner
  @scanner
end

Instance Method Details

#command?(code) ⇒ Boolean

Returns:

  • (Boolean)


298
299
300
# File 'lib/irb.rb', line 298

def command?(code)
  parse_input(code).is_a?(Statement::Command)
end

#configure_ioObject



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
# File 'lib/irb.rb', line 302

def configure_io
  if @context.io.respond_to?(:check_termination)
    @context.io.check_termination do |code|
      if Reline::IOGate.in_pasting?
        rest = @scanner.check_termination_in_prev_line(code, local_variables: @context.local_variables)
        if rest
          Reline.delete_text
          rest.bytes.reverse_each do |c|
            Reline.ungetc(c)
          end
          true
        else
          false
        end
      else
        next true if command?(code)

        _tokens, _opens, terminated = @scanner.check_code_state(code, local_variables: @context.local_variables)
        terminated
      end
    end
  end
  if @context.io.respond_to?(:dynamic_prompt)
    @context.io.dynamic_prompt do |lines|
      tokens = RubyLex.ripper_lex_without_warning(lines.map{ |l| l + "\n" }.join, local_variables: @context.local_variables)
      line_results = IRB::NestingParser.(tokens)
      tokens_until_line = []
      line_results.map.with_index do |(line_tokens, _prev_opens, next_opens, _min_depth), line_num_offset|
        line_tokens.each do |token, _s|
          # Avoid appending duplicated token. Tokens that include "n" like multiline
          # tstring_content can exist in multiple lines.
          tokens_until_line << token if token != tokens_until_line.last
        end
        continue = @scanner.should_continue?(tokens_until_line)
        generate_prompt(next_opens, continue, line_num_offset)
      end
    end
  end

  if @context.io.respond_to?(:auto_indent) and @context.auto_indent_mode
    @context.io.auto_indent do |lines, line_index, byte_pointer, is_newline|
      next nil if lines == [nil] # Workaround for exit IRB with CTRL+d
      next nil if !is_newline && lines[line_index]&.byteslice(0, byte_pointer)&.match?(/\A\s*\z/)

      code = lines[0..line_index].map { |l| "#{l}\n" }.join
      tokens = RubyLex.ripper_lex_without_warning(code, local_variables: @context.local_variables)
      @scanner.process_indent_level(tokens, lines, line_index, is_newline)
    end
  end
end

#convert_invalid_byte_sequence(str, enc) ⇒ Object



353
354
355
356
357
358
# File 'lib/irb.rb', line 353

def convert_invalid_byte_sequence(str, enc)
  str.force_encoding(enc)
  str.scrub { |c|
    c.bytes.map{ |b| "\\x#{b.to_s(16).upcase}" }.join
  }
end

#debug_breakObject

A hook point for ‘debug` command’s breakpoint after :IRB_EXIT as well as its clean-up



100
101
102
103
104
105
106
107
108
# File 'lib/irb.rb', line 100

def debug_break
  # it means the debug integration has been activated
  if defined?(DEBUGGER__) && DEBUGGER__.respond_to?(:capture_frames_without_irb)
    # after leaving this initial breakpoint, revert the capture_frames patch
    DEBUGGER__.singleton_class.send(:alias_method, :capture_frames, :capture_frames_without_irb)
    # and remove the redundant method
    DEBUGGER__.singleton_class.send(:undef_method, :capture_frames_without_irb)
  end
end

#debug_readline(binding) ⇒ Object



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
# File 'lib/irb.rb', line 110

def debug_readline(binding)
  workspace = IRB::WorkSpace.new(binding)
  context.replace_workspace(workspace)
  context.workspace.load_helper_methods_to_main
  @line_no += 1

  # When users run:
  # 1.  Debugging commands, like `step 2`
  # 2.  Any input that's not irb-command, like `foo = 123`
  #
  #
  # Irb#eval_input will simply return the input, and we need to pass it to the
  # debugger.
  input = nil
  forced_exit = catch(:IRB_EXIT) do
    if History.save_history? && context.io.support_history_saving?
      # Previous IRB session's history has been saved when `Irb#run` is exited We need
      # to make sure the saved history is not saved again by resetting the counter
      context.io.reset_history_counter

      begin
        input = eval_input
      ensure
        context.io.save_history
      end
    else
      input = eval_input
    end
    false
  end

  Kernel.exit if forced_exit

  if input&.include?("\n")
    @line_no += input.count("\n") - 1
  end

  input
end

#each_top_level_statementObject



277
278
279
280
281
282
283
284
285
# File 'lib/irb.rb', line 277

def each_top_level_statement
  loop do
    code = readmultiline
    break unless code
    yield parse_input(code), @line_no
    @line_no += code.count("\n")
  rescue RubyLex::TerminateLineInput
  end
end

#encode_with_invalid_byte_sequence(str, enc) ⇒ Object



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/irb.rb', line 360

def encode_with_invalid_byte_sequence(str, enc)
  conv = Encoding::Converter.new(str.encoding, enc)
  dst = String.new
  begin
    ret = conv.primitive_convert(str, dst)
    case ret
    when :invalid_byte_sequence
      conv.insert_output(conv.primitive_errinfo[3].dump[1..-2])
      redo
    when :undefined_conversion
      c = conv.primitive_errinfo[3].dup.force_encoding(conv.primitive_errinfo[1])
      conv.insert_output(c.dump[1..-2])
      redo
    when :incomplete_input
      conv.insert_output(conv.primitive_errinfo[3].dump[1..-2])
    when :finished
    end
    break
  end while nil
  dst
end

#eval_inputObject

Evaluates input for this session.



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
# File 'lib/irb.rb', line 190

def eval_input
  configure_io

  each_top_level_statement do |statement, line_no|
    signal_status(:IN_EVAL) do
      begin
        # If the integration with debugger is activated, we return certain input if it
        # should be dealt with by debugger
        if @context.with_debugger && statement.should_be_handled_by_debugger?
          return statement.code
        end

        @context.evaluate(statement, line_no)

        if @context.echo? && !statement.suppresses_echo?
          if statement.is_assignment?
            if @context.echo_on_assignment?
              output_value(@context.echo_on_assignment? == :truncate)
            end
          else
            output_value
          end
        end
      rescue SystemExit, SignalException
        raise
      rescue Interrupt, Exception => exc
        handle_exception(exc)
        @context.workspace.local_variable_set(:_, exc)
      end
    end
  end
end

#handle_exception(exc) ⇒ Object



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/irb.rb', line 382

def handle_exception(exc)
  if exc.backtrace[0] =~ /\/irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ &&
     !(SyntaxError === exc) && !(EncodingError === exc)
    # The backtrace of invalid encoding hash (ex. {"\xAE": 1}) raises EncodingError without lineno.
    irb_bug = true
  else
    irb_bug = false
    # To support backtrace filtering while utilizing Exception#full_message, we need to clone
    # the exception to avoid modifying the original exception's backtrace.
    exc = exc.clone
    filtered_backtrace = exc.backtrace.map { |l| @context.workspace.filter_backtrace(l) }.compact
    backtrace_filter = IRB.conf[:BACKTRACE_FILTER]

    if backtrace_filter
      if backtrace_filter.respond_to?(:call)
        filtered_backtrace = backtrace_filter.call(filtered_backtrace)
      else
        warn "IRB.conf[:BACKTRACE_FILTER] #{backtrace_filter} should respond to `call` method"
      end
    end

    exc.set_backtrace(filtered_backtrace)
  end

  highlight = Color.colorable?

  order =
    if RUBY_VERSION < '3.0.0'
      STDOUT.tty? ? :bottom : :top
    else # '3.0.0' <= RUBY_VERSION
      :top
    end

  message = exc.full_message(order: order, highlight: highlight)
  message = convert_invalid_byte_sequence(message, exc.message.encoding)
  message = encode_with_invalid_byte_sequence(message, IRB.conf[:LC_MESSAGES].encoding) unless message.encoding.to_s.casecmp?(IRB.conf[:LC_MESSAGES].encoding.to_s)
  message = message.gsub(/((?:^\t.+$\n)+)/) { |m|
    case order
    when :top
      lines = m.split("\n")
    when :bottom
      lines = m.split("\n").reverse
    end
    unless irb_bug
      if lines.size > @context.back_trace_limit
        omit = lines.size - @context.back_trace_limit
        lines = lines[0..(@context.back_trace_limit - 1)]
        lines << "\t... %d levels..." % omit
      end
    end
    lines = lines.reverse if order == :bottom
    lines.map{ |l| l + "\n" }.join
  }
  # The "<top (required)>" in "(irb)" may be the top level of IRB so imitate the main object.
  message = message.gsub(/\(irb\):(?<num>\d+):in (?<open_quote>[`'])<(?<frame>top \(required\))>'/) { "(irb):#{$~[:num]}:in #{$~[:open_quote]}<main>'" }
  puts message

  if irb_bug
    puts "This may be an issue with IRB. If you believe this is an unexpected behavior, please report it to https://github.com/ruby/irb/issues"
  end
rescue Exception => handler_exc
  begin
    puts exc.inspect
    puts "backtraces are hidden because #{handler_exc} was raised when processing them"
  rescue Exception
    puts 'Uninspectable exception occurred'
  end
end

#inspectObject

Outputs the local variables to this current session, including #signal_status and #context, using IRB::Locale.



562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'lib/irb.rb', line 562

def inspect
  ary = []
  for iv in instance_variables
    case (iv = iv.to_s)
    when "@signal_status"
      ary.push format("%s=:%s", iv, @signal_status.id2name)
    when "@context"
      ary.push format("%s=%s", iv, eval(iv).__to_s__)
    else
      ary.push format("%s=%s", iv, eval(iv))
    end
  end
  format("#<%s: %s>", self.class, ary.join(", "))
end

#output_value(omit = false) ⇒ Object

:nodoc:



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/irb.rb', line 527

def output_value(omit = false) # :nodoc:
  unless @context.return_format.include?('%')
    puts @context.return_format
    return
  end

  winheight, winwidth = @context.io.winsize
  if omit
    content, overflow = Pager.take_first_page(winwidth, 1) do |out|
      @context.inspect_last_value(out)
    end
    if overflow
      content = "\n#{content}" if @context.newline_before_multiline_output?
      content = "#{content}..."
      content = "#{content}\e[0m" if Color.colorable?
    end
    puts format(@context.return_format, content.chomp)
  elsif Pager.should_page? && @context.inspector_support_stream_output?
    formatter_proc = ->(content, multipage) do
      content = content.chomp
      content = "\n#{content}" if @context.newline_before_multiline_output? && (multipage || content.include?("\n"))
      format(@context.return_format, content)
    end
    Pager.page_with_preview(winwidth, winheight, formatter_proc) do |out|
      @context.inspect_last_value(out)
    end
  else
    content = @context.inspect_last_value.chomp
    content = "\n#{content}" if @context.newline_before_multiline_output? && content.include?("\n")
    Pager.page_content(format(@context.return_format, content), retain_content: true)
  end
end

#parse_input(code) ⇒ Object



287
288
289
290
291
292
293
294
295
296
# File 'lib/irb.rb', line 287

def parse_input(code)
  if code.match?(/\A\n*\z/)
    return Statement::EmptyInput.new
  end

  code = code.dup.force_encoding(@context.io.encoding)
  is_assignment_expression = @scanner.assignment_expression?(code, local_variables: @context.local_variables)

  @context.parse_input(code, is_assignment_expression)
end

#read_input(prompt) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/irb.rb', line 223

def read_input(prompt)
  signal_status(:IN_INPUT) do
    @context.io.prompt = prompt
    if l = @context.io.gets
      print l if @context.verbose?
    else
      if @context.ignore_eof? and @context.io.readable_after_eof?
        l = "\n"
        if @context.verbose?
          printf "Use \"exit\" to leave %s\n", @context.ap_name
        end
      else
        print "\n" if @context.prompting?
      end
    end
    l
  end
end

#read_input_nomultiline(prompt) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/irb.rb', line 242

def read_input_nomultiline(prompt)
  code = +''
  line_offset = 0
  loop do
    line = read_input(prompt)
    unless line
      return code.empty? ? nil : code
    end

    code << line
    return code if command?(code)

    tokens, opens, terminated = @scanner.check_code_state(code, local_variables: @context.local_variables)
    return code if terminated

    line_offset += 1
    continue = @scanner.should_continue?(tokens)
    prompt = generate_prompt(opens, continue, line_offset)
  end
end

#readmultilineObject



263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/irb.rb', line 263

def readmultiline
  with_prompt_part_cached do
    prompt = generate_prompt([], false, 0)

    if @context.io.respond_to?(:check_termination)
      # multiline
      read_input(prompt)
    else
      # nomultiline
      read_input_nomultiline(prompt)
    end
  end
end

#run(conf = IRB.conf) ⇒ Object



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
# File 'lib/irb.rb', line 150

def run(conf = IRB.conf)
  in_nested_session = !!conf[:MAIN_CONTEXT]
  conf[:IRB_RC].call(context) if conf[:IRB_RC]
  prev_context = conf[:MAIN_CONTEXT]
  conf[:MAIN_CONTEXT] = context

  load_history = !in_nested_session && context.io.support_history_saving?
  save_history = load_history && History.save_history?

  if load_history
    context.io.load_history
  end

  prev_trap = trap("SIGINT") do
    signal_handle
  end

  begin
    if defined?(RubyVM.keep_script_lines)
      keep_script_lines_backup = RubyVM.keep_script_lines
      RubyVM.keep_script_lines = true
    end

    forced_exit = catch(:IRB_EXIT) do
      eval_input
    end
  ensure
    # Do not restore to nil. It will cause IRB crash when used with threads.
    IRB.conf[:MAIN_CONTEXT] = prev_context if prev_context

    RubyVM.keep_script_lines = keep_script_lines_backup if defined?(RubyVM.keep_script_lines)
    trap("SIGINT", prev_trap)
    conf[:AT_EXIT].each{|hook| hook.call}

    context.io.save_history if save_history
    Kernel.exit if forced_exit
  end
end

#signal_handleObject

Handler for the signal SIGINT, see Kernel#trap for more information.



493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/irb.rb', line 493

def signal_handle
  unless @context.ignore_sigint?
    print "\nabort!\n" if @context.verbose?
    exit
  end

  case @signal_status
  when :IN_INPUT
    print "^C\n"
    raise RubyLex::TerminateLineInput
  when :IN_EVAL
    IRB.irb_abort(self)
  when :IN_LOAD
    IRB.irb_abort(self, LoadAbort)
  when :IN_IRB
    # ignore
  else
    # ignore other cases as well
  end
end

#signal_status(status) ⇒ Object

Evaluates the given block using the given ‘status`.



515
516
517
518
519
520
521
522
523
524
525
# File 'lib/irb.rb', line 515

def signal_status(status)
  return yield if @signal_status == :IN_LOAD

  signal_status_back = @signal_status
  @signal_status = status
  begin
    yield
  ensure
    @signal_status = signal_status_back
  end
end

#suspend_input_method(input_method) ⇒ Object

Evaluates the given block using the given ‘input_method` as the Context#io.

Used by the irb commands ‘source` and `irb_load`, see IRB@IRB+Sessions for more information.



482
483
484
485
486
487
488
489
490
# File 'lib/irb.rb', line 482

def suspend_input_method(input_method)
  back_io = @context.io
  @context.instance_eval{@io = input_method}
  begin
    yield back_io
  ensure
    @context.instance_eval{@io = back_io}
  end
end

#suspend_name(path = nil, name = nil) ⇒ Object

Evaluates the given block using the given ‘path` as the Context#irb_path and `name` as the Context#irb_name.

Used by the irb command ‘source`, see IRB@IRB+Sessions for more information.



455
456
457
458
459
460
461
462
463
464
# File 'lib/irb.rb', line 455

def suspend_name(path = nil, name = nil)
  @context.irb_path, back_path = path, @context.irb_path if path
  @context.irb_name, back_name = name, @context.irb_name if name
  begin
    yield back_path, back_name
  ensure
    @context.irb_path = back_path if path
    @context.irb_name = back_name if name
  end
end

#suspend_workspace(workspace) ⇒ Object

Evaluates the given block using the given ‘workspace` as the Context#workspace.

Used by the irb command ‘irb_load`, see IRB@IRB+Sessions for more information.



470
471
472
473
474
475
476
# File 'lib/irb.rb', line 470

def suspend_workspace(workspace)
  current_workspace = @context.workspace
  @context.replace_workspace(workspace)
  yield
ensure
  @context.replace_workspace current_workspace
end