rpl.rb/bin/rpl

89 lines
1.9 KiB
Text
Raw Normal View History

2022-02-15 17:06:19 +01:00
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'English'
require 'optparse'
2022-02-15 17:06:19 +01:00
require 'readline'
require 'rpl'
class RplRepl
def initialize( interpreter )
interpreter ||= Rpl.new
2022-02-24 15:28:40 +01:00
@interpreter = interpreter
2022-02-15 17:06:19 +01:00
end
def run
print_stack unless @interpreter.stack.empty?
2022-02-15 17:06:19 +01:00
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
2022-02-24 15:28:40 +01:00
pp e
2022-02-15 17:06:19 +01:00
end
print_stack
end
end
def print_stack
stack_size = @interpreter.stack.size
@interpreter.stack.each_with_index do |elt, i|
2022-02-26 18:53:39 +01:00
puts "#{stack_size - i}: #{elt}"
2022-02-15 17:06:19 +01:00
end
end
end
2022-02-16 16:28:33 +01:00
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!
2022-02-24 15:28:40 +01:00
# Instantiate interpreter
interpreter = Rpl.new
# first run provided files if any
options[:files].each do |filename|
interpreter.run "\"#{filename}\" feval"
end
2022-02-24 15:28:40 +01:00
# second run provided code if any
options[:programs].each do |program|
interpreter.run program
end
2022-02-24 15:28:40 +01:00
# third launch REPL if (explicitely or implicitely) asked
RplRepl.new( interpreter ).run if options[:run_REPL]
2022-02-24 15:28:40 +01:00
# last print resulting stack on exit (formatted so that it can be fed back later to interpreter)
2022-02-26 18:53:39 +01:00
pp interpreter.export_stack