Class: BCDice::CommonCommand::Lexer

Inherits:
Object
  • Object
show all
Defined in:
lib/bcdice/common_command/lexer.rb

Constant Summary collapse

SYMBOLS =
{
  "+" => :PLUS,
  "-" => :MINUS,
  "*" => :ASTERISK,
  "/" => :SLASH,
  "(" => :PARENL,
  ")" => :PARENR,
  "[" => :BRACKETL,
  "]" => :BRACKETR,
  "?" => :QUESTION,
  "@" => :AT,
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Lexer

Returns a new instance of Lexer.



22
23
24
25
26
# File 'lib/bcdice/common_command/lexer.rb', line 22

def initialize(source)
  # sourceが空文字だとString#splitが空になる
  source = source.split(" ", 2).first || ""
  @scanner = StringScanner.new(source)
end

Instance Method Details

#next_tokenObject



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/bcdice/common_command/lexer.rb', line 28

def next_token
  return [false, "$"] if @scanner.eos?

  if (number = @scanner.scan(/\d+/))
    [:NUMBER, number.to_i]
  elsif (cmp_op = @scanner.scan(/[<>!=]+/))
    [:CMP_OP, Normalize.comparison_operator(cmp_op)]
  else
    char = @scanner.getch.upcase
    type = SYMBOLS[char] || char.to_sym
    [type, char]
  end
end

#sourceObject



42
43
44
# File 'lib/bcdice/common_command/lexer.rb', line 42

def source
  @scanner.string
end