extract some classes, write some tests

FossilOrigin-Name: a0174386a70769c2c274f725ccb1a52a11ec925acdd6c63a1d13ceb8fd4fd9a8
private
alpha 2 years ago
parent 506d3a444c
commit 6e484507d0

@ -5,4 +5,6 @@ source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
gem "minitest" gem "minitest"
gem "mocktail"
gem "pry" gem "pry"
gem "rake"

@ -4,16 +4,20 @@ GEM
coderay (1.1.3) coderay (1.1.3)
method_source (1.0.0) method_source (1.0.0)
minitest (5.16.2) minitest (5.16.2)
mocktail (1.1.3)
pry (0.14.1) pry (0.14.1)
coderay (~> 1.1) coderay (~> 1.1)
method_source (~> 1.0) method_source (~> 1.0)
rake (13.0.6)
PLATFORMS PLATFORMS
arm64-darwin-21 arm64-darwin-21
DEPENDENCIES DEPENDENCIES
minitest minitest
mocktail
pry pry
rake
BUNDLED WITH BUNDLED WITH
2.3.18 2.3.18

@ -1,8 +1,14 @@
#!/usr/bin/env ruby -w #!/usr/bin/env ruby -w
module Lox module Lox
class << self class Error < StandardError
@had_error = false def initialize(line:, where: "", message:)
@line, @where, @message = line, where, message
end
def to_s
"[line #@line] Error#@where: #@message"
end
end end
def self.run_prompt def self.run_prompt
@ -10,33 +16,42 @@ module Lox
print "> " print "> "
line = gets line = gets
break if line.empty? break if line.empty?
run(line) begin
@had_error = false run(line)
rescue Error => e
puts e.message
end
end end
end end
def self.run_file(io) def self.run_file(io)
run(io.read) run(io.read)
rescue Error
exit 65 if @had_error puts e.message
exit 65
end end
def self.run(src) def self.run(src)
scanner = Scanner.new(src) Runner.new(src).run
tokens = scanner.scan()
tokens.each do |token|
puts token
end
end end
def self.error(line, msg) def self.error(line, msg)
report(line, "", msg) raise Error(line:, message:)
end end
def self.report(line, where, message) class Runner
puts "[line #{line}] Error#{where}: #{message}" def initialize(scanner:)
@had_error = true; @scanner = scanner
end
def run(src)
@scanner.scan(src)
end
end
class Scanner
def scan(src)
end
end end
end end

@ -1,8 +1,9 @@
require "minitest/autorun"
require "lox" require "lox"
require "open3" require "open3"
require "minitest/autorun"
require "mocktail"
require "pry" require "pry"
class TestLox < Minitest::Test class TestLox < Minitest::Test
@ -12,3 +13,21 @@ class TestLox < Minitest::Test
assert_equal "Usage: ./lox.rb [script]\n", o assert_equal "Usage: ./lox.rb [script]\n", o
end end
end end
class TestRunner < Minitest::Test
include Mocktail::DSL
def teardown
Mocktail.reset
end
def test_returns_tokens
scanner = Mocktail.of(Lox::Scanner)
runner = Lox::Runner.new(scanner:)
stubs { scanner.scan("src") }.with { %w[ some tokens ] }
tokens = runner.run("src")
assert_equal %w[ some tokens ], tokens
end
end

Loading…
Cancel
Save