diff --git a/bin/keisan b/bin/keisan index 374b0d4..ba25fce 100755 --- a/bin/keisan +++ b/bin/keisan @@ -2,6 +2,17 @@ require "bundler/setup" require "keisan" -require "keisan/repl" +require "keisan/interpreter" -Keisan::Repl.new.start +file_name = nil +allow_recursive = false + +ARGV.each do |arg| + if arg == "--allow_recursive" + allow_recursive = true + else + file_name = arg + end +end + +Keisan::Interpreter.new(allow_recursive: allow_recursive).run(file_name) diff --git a/lib/keisan/interpreter.rb b/lib/keisan/interpreter.rb new file mode 100644 index 0000000..03f0172 --- /dev/null +++ b/lib/keisan/interpreter.rb @@ -0,0 +1,40 @@ +module Keisan + class Interpreter + attr_reader :calculator + + def initialize(allow_recursive: false) + @calculator = Calculator.new(allow_recursive: allow_recursive) + end + + def run(file_name) + if file_name.nil? + run_from_stdin + else + run_from_file(file_name) + end + end + + private + + def run_from_stdin + run_on_content STDIN.read + end + + def run_from_file(file_name) + run_on_content( + File.exists?(file_name) ? File.open(file_name) do |file| + file.read + end : "" + ) + end + + def run_on_content(content) + content = content.strip + if content.nil? || content.empty? + Repl.new.start + else + calculator.evaluate(content) + end + end + end +end diff --git a/lib/keisan/repl.rb b/lib/keisan/repl.rb index a06fb6d..c2e4b48 100644 --- a/lib/keisan/repl.rb +++ b/lib/keisan/repl.rb @@ -1,4 +1,4 @@ -require "pry" +require "coderay" require "readline" module Keisan