File: lexer.rb

package info (click to toggle)
ruby-expression-parser 0.9.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 152 kB
  • sloc: ruby: 293; makefile: 11
file content (77 lines) | stat: -rw-r--r-- 1,581 bytes parent folder | download | duplicates (3)
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
# Taken from http://lukaszwrobel.pl/blog/math-parser-part-3-implementation
module ExpressionParser

  class Lexer

    def initialize(input)
      @input = input
      @return_previous_token = false
    end

    def get_next_token
      if @return_previous_token
	@return_previous_token = false
	return @previous_token
      end

      token = Token.new

      @input.lstrip!

      case @input
      when /\A\+/ then
	token.kind = Token::Plus
      when /\A-/ then
	token.kind = Token::Minus
      when /\A\*/ then
	token.kind = Token::Multiply
      when /\Adiv/ then
	token.kind = Token::Divide
      when /\A\// then
	token.kind = Token::Divide
      when /\A\d+(\.\d+)?/
	token.kind = Token::Number
	token.value = $&.to_f
      when /\A\(/
	token.kind = Token::LParen
      when /\A\)/
	token.kind = Token::RParen
      when ''
	token.kind = Token::End
      when /\Ae/
	token.kind = Token::Number
	token.value = 2.718281828459
      when /\Api/
	token.kind = Token::Number
	token.value = 3.1415926535898
      when /\Amod/
	token.kind = Token::MOD
      when /\A!=/
	token.kind = Token::NotEqual
      when /\A<>/
	token.kind = Token::NotEqual
      when /\A>=/
	token.kind = Token::GThanE
      when /\A>/
	token.kind = Token::GThan
      when /\A<=/
	token.kind = Token::LThanE
      when /\A</
	token.kind = Token::LThan
      when /\A=/
	token.kind = Token::Equal
      end

      raise "Unknown token #{@input}" if token.unknown?
      @input = $'

      @previous_token = token
      token
    end

    def revert
      @return_previous_token = true
    end
  end

end