rpl.rb/repl.rb

70 lines
1.3 KiB
Ruby
Raw Normal View History

2021-10-30 19:27:15 +02:00
# coding: utf-8
# frozen_string_literal: true
2021-10-31 09:18:34 +01:00
require "readline"
2021-10-30 19:27:15 +02:00
2021-10-31 09:18:34 +01:00
require "./lib/parser.rb"
2021-10-30 23:36:49 +02:00
2021-11-09 16:50:01 +01:00
module Rpn
class Repl
def initialize
@parser = Parser.new
@stack = []
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|
directory_list = Dir.glob("#{s}*")
if directory_list.positive?
directory_list
else
Readline::HISTORY.grep(/^#{Regexp.escape(s)}/)
end
end
Readline.completion_append_character = " "
2021-10-30 19:27:15 +02:00
2021-11-09 16:50:01 +01:00
loop do
input = Readline.readline( "", true )
break if input.nil? || input == "exit"
2021-10-30 19:27:15 +02:00
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-09 16:50:01 +01:00
process_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 process_input( input )
@parser.parse_input( input ).each do |elt|
@stack << elt
end
end
2021-10-30 19:27:15 +02:00
2021-11-09 16:50:01 +01:00
def format_element( elt )
pp elt
# case elt[:type]
# when :program
# "« #{elt[:value]} »"
# when :string
# "\"#{elt[:value]}\""
# when :name
# "'#{elt[:value]}'"
# else
elt[:value]
# end
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