2021-10-30 19:27:15 +02:00
|
|
|
# coding: utf-8
|
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2021-11-10 11:01:26 +01:00
|
|
|
require 'readline'
|
2021-10-30 19:27:15 +02:00
|
|
|
|
2021-11-10 16:20:47 +01:00
|
|
|
require './lib/core'
|
2021-11-10 11:01:26 +01:00
|
|
|
require './lib/dictionary'
|
|
|
|
require './lib/parser'
|
|
|
|
require './lib/runner'
|
2021-10-30 23:36:49 +02:00
|
|
|
|
2021-11-09 16:50:01 +01:00
|
|
|
module Rpn
|
|
|
|
class Repl
|
|
|
|
def initialize
|
|
|
|
@stack = []
|
2021-11-10 11:01:26 +01:00
|
|
|
@dictionary = Dictionary.new
|
|
|
|
@parser = Parser.new
|
|
|
|
@runner = Runner.new
|
2021-11-18 15:44:09 +01:00
|
|
|
|
|
|
|
Rpn::Core.init
|
2021-10-30 19:27:15 +02:00
|
|
|
end
|
|
|
|
|
2021-11-09 16:50:01 +01:00
|
|
|
def run
|
|
|
|
Readline.completion_proc = proc do |s|
|
2021-11-10 16:44:29 +01:00
|
|
|
Readline::HISTORY.grep(/^#{Regexp.escape(s)}/)
|
2021-11-09 16:50:01 +01:00
|
|
|
end
|
2021-11-10 11:01:26 +01:00
|
|
|
Readline.completion_append_character = ' '
|
2021-10-30 19:27:15 +02:00
|
|
|
|
2021-11-09 16:50:01 +01:00
|
|
|
loop do
|
2021-11-10 11:01:26 +01:00
|
|
|
input = Readline.readline( ' ', true )
|
2021-11-10 16:20:47 +01:00
|
|
|
break if input.nil? || input == 'quit'
|
2021-10-30 19:27:15 +02:00
|
|
|
|
2021-11-10 16:44:29 +01:00
|
|
|
pp Readline::HISTORY if input == 'history'
|
|
|
|
|
|
|
|
input = '"rpn.rb version 0.0"' if %w[version uname].include?( input )
|
|
|
|
|
2021-11-09 16:50:01 +01:00
|
|
|
# Remove blank lines from history
|
|
|
|
Readline::HISTORY.pop if input.empty?
|
2021-10-30 19:27:15 +02:00
|
|
|
|
2021-11-10 11:01:26 +01:00
|
|
|
@stack, @dictionary = @runner.run_input( @stack, @dictionary,
|
|
|
|
@parser.parse_input( input ) )
|
2021-10-30 19:27:15 +02:00
|
|
|
|
2021-11-09 16:50:01 +01:00
|
|
|
print_stack
|
|
|
|
end
|
|
|
|
end
|
2021-10-30 19:27:15 +02:00
|
|
|
|
2021-11-09 16:50:01 +01:00
|
|
|
def format_element( elt )
|
2021-11-10 11:01:26 +01:00
|
|
|
elt[:value]
|
2021-11-09 16:50:01 +01:00
|
|
|
end
|
2021-10-30 19:27:15 +02:00
|
|
|
|
2021-11-09 16:50:01 +01:00
|
|
|
def print_stack
|
|
|
|
stack_size = @stack.size
|
2021-10-30 19:27:15 +02:00
|
|
|
|
2021-11-09 16:50:01 +01:00
|
|
|
@stack.each_with_index do |elt, i|
|
|
|
|
puts "#{stack_size - i}: #{format_element( elt )}"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2021-10-30 19:27:15 +02:00
|
|
|
end
|
|
|
|
|
2021-11-09 16:50:01 +01:00
|
|
|
Rpn::Repl.new.run
|