module Kernel

def debugger(*a, up_level: 0, **kw)

def debugger(*a, up_level: 0, **kw)
  begin
    require_relative 'version'
    cur_version = ::DEBUGGER__::VERSION
    require_relative 'frame_info'
    if !defined?(::DEBUGGER__::SO_VERSION) || ::DEBUGGER__::VERSION != ::DEBUGGER__::SO_VERSION
      ::Object.send(:remove_const, :DEBUGGER__)
      raise LoadError
    end
    require_relative 'session'
    up_level += 1
  rescue LoadError
    $LOADED_FEATURES.delete_if{|e|
      e.start_with?(__dir__) || e.end_with?('debug/debug.so')
    }
    require 'debug/session'
    require 'debug/version'
    ::DEBUGGER__.info "Can not activate debug #{cur_version} specified by debug/prelude.rb. Activate debug #{DEBUGGER__::VERSION} instead."
    up_level += 1
  end
  ::DEBUGGER__::start no_sigint_hook: true, nonstop: true
  begin
    debugger(*a, up_level: up_level, **kw)
    self
  rescue ArgumentError # for 1.2.4 and earlier
    debugger(*a, **kw)
    self
  end
end

def debugger pre: nil, do: nil, up_level: 0

def debugger pre: nil, do: nil, up_level: 0
  return if !defined?(::DEBUGGER__::SESSION) || !::DEBUGGER__::SESSION.active?
  if pre || (do_expr = binding.local_variable_get(:do))
    cmds = ['#debugger', pre, do_expr]
  end
  if ::DEBUGGER__::SESSION.in_subsession?
    if cmds
      commands = [*cmds[1], *cmds[2]].map{|c| c.split(';;').join("\n")}
      ::DEBUGGER__::SESSION.add_preset_commands cmds[0], commands, kick: false, continue: false
    end
  else
    loc = caller_locations(up_level, 1).first; ::DEBUGGER__.add_line_breakpoint loc.path, loc.lineno + 1, oneshot: true, command: cmds
  end
  self
end