Class: Rubic::Lexer

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

Constant Summary collapse

EOT =

end of token

[false, nil]
SYM_CHARS =
Regexp.escape("+-*/<>=!?")
KEYWORD_TABLE =
{
  'define' => :KW_DEFINE,
  'cond'   => :KW_COND,
  'else'   => :KW_ELSE,
  'if'     => :KW_IF,
  'and'    => :KW_AND,
  'or'     => :KW_OR,
  'lambda' => :KW_LAMBDA,
  'let'    => :KW_LET,
  'quote'  => :KW_QUOTE,
  'set!'   => :KW_SET_BANG,
  'begin'  => :KW_BEGIN,
}

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ Lexer

Returns a new instance of Lexer.



21
22
23
24
# File 'lib/rubic/lexer.rb', line 21

def initialize(str)
  @s = StringScanner.new(str)
  @state = :start
end

Instance Method Details

#next_tokenObject



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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/rubic/lexer.rb', line 26

def next_token
  case @state
  when :start
    @s.skip(/\s+/)
    return EOT if @s.eos?

    case
    when @s.check(/[+-]?[.0-9]|[+-]i/)
      @state = :num_char
      next_token

    when @s.check(/#/)
      @state = :num_prefix
      next_token

    when @s.scan(/[()']/)
      [@s[0], nil]

    when @s.scan(/[A-Za-z_#{SYM_CHARS}][A-Za-z0-9_#{SYM_CHARS}]*/o)
      if KEYWORD_TABLE.key? @s[0]
        [KEYWORD_TABLE.fetch(@s[0]), nil]
      else
        [:IDENT, @s[0].to_sym]
      end

    when @s.scan(/"([^"]*)"/)
      [:STRING, @s[1]]

    else
      raise Rubic::ParseError, "unknown character #{@s.getch}"

    end

  when :num_prefix
    case
    when @s.scan(/#[eibodx]/)
      {
        '#e' => [:NUM_PREFIX_E, true],
        '#i' => [:NUM_PREFIX_I, false],
        '#b' => [:NUM_PREFIX_B, nil],
        '#o' => [:NUM_PREFIX_O, nil],
        '#d' => [:NUM_PREFIX_D, nil],
        '#x' => [:NUM_PREFIX_X, nil],
      }.fetch(@s[0])
    else
      @state = :num_char
      next_token
    end

  when :num_char
    case
    when @s.check(/[+-]?[.0-9a-f\/]*i/i) # complex
      @state = :num_char_complex
      next_token
    when @s.scan(/\+/)
      [:U_PLUS, '+']
    when @s.scan(/-/)
      [:U_MINUS, '-']
    when @s.scan(/[@.0-9a-f\/]/i)
      [@s[0].downcase, @s[0].downcase]
    else
      @state = :num_wrapup
      next_token
    end

  when :num_char_complex
    case
    when @s.scan(/[[email protected]\/]/i)
      [@s[0].downcase, @s[0].downcase]
    else
      @state = :num_wrapup
      next_token
    end

  when :num_wrapup
    case
    when @s.eos? || @s.check(/[\s()";]/) # separator characters
      @state = :start
      [:NUM_END, nil]
    else
      @state = :start
      next_token
    end

  else # NOT REACHED
    raise "unknown state: #{@state}"

  end
end