rpl.rb/repl.rb

51 lines
960 B
Ruby
Raw Normal View History

2021-10-30 19:27:15 +02:00
# frozen_string_literal: true
2021-11-10 11:01:26 +01:00
require 'readline'
2021-10-30 19:27:15 +02:00
require './interpreter'
2021-10-30 23:36:49 +02:00
2021-12-07 16:09:17 +01:00
class RplRepl
def initialize
@interpreter = Rpl::Interpreter.new
2021-12-07 16:09:17 +01:00
end
2021-12-07 15:50:58 +01:00
2021-12-07 16:09:17 +01:00
def run
Readline.completion_proc = proc do |s|
Readline::HISTORY.grep(/^#{Regexp.escape(s)}/)
end
Readline.completion_append_character = ' '
2021-10-30 19:27:15 +02:00
2021-12-07 16:09:17 +01:00
loop do
input = Readline.readline( ' ', true )
break if input.nil? || input == 'quit'
2021-10-30 19:27:15 +02:00
2021-12-07 16:09:17 +01:00
pp Readline::HISTORY if input == 'history'
2021-12-07 16:09:17 +01:00
# Remove blank lines from history
Readline::HISTORY.pop if input.empty?
2021-10-30 19:27:15 +02:00
2021-12-08 13:45:29 +01:00
begin
@interpreter.run( input )
2022-02-09 16:31:24 +01:00
rescue ArgumentError => e
2021-12-08 13:45:29 +01:00
p e
end
2021-10-30 19:27:15 +02:00
2021-12-07 16:09:17 +01:00
print_stack
2021-11-09 16:50:01 +01:00
end
2021-12-07 16:09:17 +01:00
end
2021-10-30 19:27:15 +02:00
2021-12-07 16:09:17 +01:00
def format_element( elt )
Rpl::Lang.stringify( elt )
2021-12-07 16:09:17 +01:00
end
def print_stack
stack_size = @interpreter.stack.size
2021-10-30 19:27:15 +02:00
@interpreter.stack.each_with_index do |elt, i|
2021-12-07 16:09:17 +01:00
puts "#{stack_size - i}: #{format_element( elt )}"
2021-11-09 16:50:01 +01:00
end
end
2021-10-30 19:27:15 +02:00
end
2021-12-07 16:09:17 +01:00
RplRepl.new.run