8.challenges.1

FossilOrigin-Name: 4dd1670a4466cf079d61e11677e4aa8dd9b9ec096700e2ae565a4073ec4efc12
private
alpha 2 years ago
parent ce32eea3d9
commit e21f070968

@ -4,33 +4,17 @@ $LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
require "lox" require "lox"
def run_prompt def run_prompt(runner)
loop do loop do
print "> " print "> "
line = gets line = gets
break if line.nil? || line.empty? break if line.nil? || line.empty?
begin runner.run(line)
run(line)
rescue Lox::ParseError => e
STDERR.puts e.message
rescue Lox::RuntimeError => e
STDERR.puts e.message
end
end end
end end
def run_file(io) def run_file(runner, io)
run(io.read) runner.run(io.read)
rescue Lox::ParseError => e
STDERR.puts e.message
exit 65
rescue Lox::RuntimeError => e
STDERR.puts e.message, "[line #{e.token.line}]"
exit 70
end
def run(src)
Lox::Runner.new.run(src)
end end
@ -38,8 +22,8 @@ if __FILE__ == $0
puts "Usage: #$0 [script]" or exit 64 if ARGV.length > 1 puts "Usage: #$0 [script]" or exit 64 if ARGV.length > 1
if ARGV.empty? if ARGV.empty?
run_prompt run_prompt(Lox::PromptRunner.new)
else else
run_file(ARGF) Lox::FileRunner.new.run(ARGF.read)
end end
end end

@ -10,18 +10,48 @@ require_relative "lox/token"
module Lox module Lox
class Runner class Runner
def initialize(scanner: Scanner.new, interpreter: Interpreter.new)
@scanner, @interpreter = scanner, interpreter
end
def run(src) = interpret(parse(scan(src)))
def scan(src) = @scanner.scan(src)
def parse(tokens) = Parser.new(tokens).parse!
def interpret(stmts) = @interpreter.interpret(stmts)
end
class FileRunner < Runner
def run(src)
super
rescue Lox::ParseError => e
STDERR.puts e.message
exit 65
rescue Lox::RuntimeError => e
STDERR.puts e.message, "[line #{e.token.line}]"
exit 70
end
end
class PromptRunner < Runner
def initialize def initialize
@scanner = Scanner.new super(interpreter: Interpreter.new(Environment.new))
@parser = Parser.new
@interpreter = Interpreter.new
end end
def run(src) def run(src)
tokens = @scanner.scan(src) super
expr = @parser.parse(tokens) rescue Lox::ParseError => e
value = @interpreter.interpret(expr) STDERR.puts e.message
rescue Lox::RuntimeError => e
STDERR.puts e.message
end
puts value def parse(tokens)
stmts = Parser.new(tokens).parse!
if stmts.last.instance_of?(Stmt::Expr)
stmts << Stmt::Print.new(stmts.pop.expr)
end
stmts
end end
end end
end end

@ -3,8 +3,8 @@ require_relative "environment"
module Lox module Lox
class Interpreter class Interpreter
def initialize def initialize(env=Environment.new)
@env = Environment.new @env = env
end end
# The book does printing and error catching here, but # The book does printing and error catching here, but

Loading…
Cancel
Save