rpl.rb/bin/rpl
2022-02-16 16:28:33 +01:00

86 lines
1.8 KiB
Ruby
Executable file

#!/usr/bin/env ruby
# frozen_string_literal: true
require 'English'
require 'optparse'
require 'readline'
require 'rpl'
class RplRepl
def initialize( interpreter )
interpreter ||= Rpl.new
@interpreter = interpreter
end
def run
print_stack unless @interpreter.stack.empty?
Readline.completion_proc = proc do |s|
( @interpreter.dictionary.words.keys + @interpreter.dictionary.vars.keys ).grep(/^#{Regexp.escape(s)}/)
end
Readline.completion_append_character = ' '
loop do
input = Readline.readline( ' ', true )
break if input.nil? || input == 'quit'
pp Readline::HISTORY if input == 'history'
# Remove blank lines from history
Readline::HISTORY.pop if input.empty?
begin
@interpreter.run( input )
rescue ArgumentError => e
p e
end
print_stack
end
end
def format_element( elt )
@interpreter.stringify( elt )
end
def print_stack
stack_size = @interpreter.stack.size
@interpreter.stack.each_with_index do |elt, i|
puts "#{stack_size - i}: #{format_element( elt )}"
end
end
end
interpreter = Rpl.new
options = { run_REPL: ARGV.empty?,
files: [],
programs: [] }
OptionParser.new do |opts|
opts.on('-c', '--code "program"', ' ') do |program|
options[:programs] << program
end
opts.on('-f', '--file program.rpl', 'load program.rpl') do |filename|
options[:files] << filename
end
opts.on('-i', '--interactive', 'launch interactive REPL') do
options[:run_REPL] = true
end
end.parse!
options[:files].each do |filename|
interpreter.run "\"#{filename}\" feval"
end
options[:programs].each do |program|
interpreter.run program
end
RplRepl.new( interpreter ).run if options[:run_REPL]
pp interpreter.stack.map { |elt| interpreter.stringify( elt ) }.join(' ')