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
|
|
|
|
2021-12-07 16:03:03 +01:00
|
|
|
require './language'
|
2021-10-30 23:36:49 +02:00
|
|
|
|
2021-12-07 16:09:17 +01:00
|
|
|
class RplRepl
|
|
|
|
def initialize
|
|
|
|
@lang = Rpl::Language.new
|
|
|
|
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-11-10 16:44:29 +01:00
|
|
|
|
2021-12-07 16:09:17 +01:00
|
|
|
input = '"rpn.rb version 0.0"' if %w[version uname].include?( input )
|
2021-11-10 16:44:29 +01:00
|
|
|
|
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
|
|
|
|
@lang.run( input )
|
|
|
|
rescue ArgumentError, ZeroDivisionError => e
|
|
|
|
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 )
|
2021-12-15 13:31:32 +01:00
|
|
|
case elt[:type]
|
|
|
|
when :numeric
|
2021-12-07 16:09:17 +01:00
|
|
|
prefix = case elt[:base]
|
|
|
|
when 2
|
|
|
|
'0b'
|
|
|
|
when 8
|
|
|
|
'0o'
|
2021-12-15 13:31:32 +01:00
|
|
|
when 10
|
|
|
|
''
|
2021-12-07 16:09:17 +01:00
|
|
|
when 16
|
|
|
|
'0x'
|
|
|
|
else
|
|
|
|
"0#{elt[:base]}_"
|
|
|
|
end
|
2021-12-15 13:31:32 +01:00
|
|
|
"#{prefix}#{elt[:value].to_s( elt[:base] )}"
|
|
|
|
else
|
|
|
|
elt[:value]
|
2021-11-09 16:50:01 +01:00
|
|
|
end
|
2021-12-07 16:09:17 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def print_stack
|
|
|
|
stack_size = @lang.stack.size
|
2021-10-30 19:27:15 +02:00
|
|
|
|
2021-12-07 16:09:17 +01:00
|
|
|
@lang.stack.each_with_index do |elt, i|
|
|
|
|
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
|