-
Notifications
You must be signed in to change notification settings - Fork 0
/
wasm.rb
79 lines (59 loc) · 1.59 KB
/
wasm.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def main
input = 'test'
expected = 'test'
actual = SExpressionParser.new.parse(input)
raise actual.inspect unless actual == expected
input = '(test)'
output = ['test']
actual = SExpressionParser.new.parse(input)
raise actual.inspect unless actual == output
input = '(test case)'
output = %w[test case]
actual = SExpressionParser.new.parse(input)
raise actual.inspect unless actual == output
return if ARGV.empty?
s_expression = SExpressionParser.new.parse(ARGF.read)
pp s_expression
end
# Parse through using string using Regexp
class SExpressionParser
def parse(string)
self.string = string
parse_expression
end
# Uses regexp to find opening parentheses, and adds to array. Once finds closing parentheses, it returns the array.
def parse_expression
if can_read?(/\(/)
expressions = []
read(/\(/)
loop do
skip_whitespace
break if can_read?(/\)/)
expressions << parse_expression
end
read(/\)/)
expressions
else
parse_atom
end
end
private
def skip_whitespace
return unless can_read?(%r{ +})
read(%r{ +})
end
def parse_atom
read(/[^) ]+/)
end
def can_read?(pattern)
/\A#{pattern}/.match?(string)
end
# Uses regexp to match a pattern, sets the currently interpreted string to the remainder of the string that isn't matched, and returns the matched string.
def read(pattern)
match = /\A#{pattern}/.match(string) or raise "Expected #{pattern} but got #{string}"
self.string = match.post_match
match.to_s
end
attr_accessor :string
end
main