forked from elct9620/5compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.rb
91 lines (70 loc) · 1.31 KB
/
token.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
80
81
82
83
84
85
86
87
88
89
90
91
# frozen_string_literal: true
module C5
# :nodoc:
class Token
OPERATORS = %w[+ - / *].freeze
FUNCTIONS = %w[puts].freeze
CONDITION = %w[== >= <= > < !=].freeze
attr_reader :type, :body
def initialize(type, body)
@type = type
@body = body
end
alias to_s body
def inspect
return @type if linefeed?
"#{@type} (#{@body})"
end
def value
return unless value?
return body.to_i if number?
body[1..-2]
end
def op
return unless operator? || condition?
body.to_sym
end
def symbol?
type == :symbol
end
def keyword?
type == :keyword
end
def string?
type == :string
end
def number?
type == :number
end
def linefeed?
type == :linefeed
end
def literal?
type == :literal
end
def value?
string? || number?
end
def assign?
symbol? && body == '='
end
def operator?
symbol? && OPERATORS.include?(body)
end
def condition?
symbol? && CONDITION.include?(body)
end
def fn?
keyword? && FUNCTIONS.include?(body)
end
def if?
keyword? && body == 'if'
end
def else?
keyword? && body == 'else'
end
def exit?
keyword? && body == 'end'
end
end
end