Class: Superscript::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/superscript/runner.rb

Instance Method Summary collapse

Constructor Details

#initialize(path = nil) ⇒ Runner

Returns a new instance of Runner.



3
4
5
6
7
8
9
# File 'lib/superscript/runner.rb', line 3

def initialize path=nil
  @path = if path
    path
  else
    "<interactive>"
  end
end

Instance Method Details

#run!(ctx: nil, contents: nil) ⇒ Object



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
# File 'lib/superscript/runner.rb', line 11

def run!(ctx:nil, contents:nil)
  contents = File.read(@path) unless contents
  ctx = Superscript::Ctx.new unless ctx

  @armed = false
  trace = TracePoint.new do |tp|
    #p [@armed, tp.path, tp.lineno, tp.method_id, tp.event, tp.defined_class]

    if tp.defined_class.name == "BasicObject" && tp.method_id == :instance_eval
      if tp.event == :script_compiled
        @armed = true
      elsif tp.event == :c_return
        @armed = false
      end
    end

    if tp.event == :return && tp.defined_class.name == "Superscript::Ctx"
      @armed = true
    end

    next unless @armed

    case tp.event
    when :line
      puts "< " + contents.split("\n")[tp.lineno - 1]
    when :c_call
      @armed = false
      trace.disable

      puts "Error: Command not found '#{tp.method_id}'"

      exit 1
    when :call
      if tp.defined_class.name == "Superscript::Ctx"
        @armed = false
      end
    end
  end

  value = begin
    trace.enable
    ctx.instance_eval contents, @path
    trace.disable
  rescue Exception => ex
    case ex.class.to_s
    when "SystemExit"
      exit ex.status
    when "NameError"
      print "#{@path}:#{ex.backtrace_locations.first.lineno} "
      puts ex.message.split(" for ").first
    else
      p [:exception, ex]
    end
  ensure
    trace.disable
  end

  value
end