Class: Optimus::ParsedCalculator::ExpressionParser

Inherits:
Object
  • Object
show all
Extended by:
RParsec::Parsers
Includes:
RParsec::Parsers
Defined in:
lib/parsed_calculator.rb

Instance Method Summary collapse

Constructor Details

#initializeExpressionParser

Returns a new instance of ExpressionParser.



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
# File 'lib/parsed_calculator.rb', line 26

def initialize
  @operators = RParsec::Operators.new(
    %w{+ - * / % & ( ) not and or = != > >= < <=}
  )
  expr = nil
  lazy_expr = lazy { expr }
  atom = (
    token(:str) { |lex| StringLiteral.new(lex) } |
    token(:number) { |lex| NumberLiteral.new(lex) } |
    token(:column) { |lex| ColumnReference.new(lex) } )
  
  lit = atom | (@operators['('] >> lazy_expr << @operators[')'])
  
  # Follows hte standard C 
  table = RParsec::OperatorTable.new.
    prefix(@operators['-'] >>   lambda {|a| -a}, 50).
    prefix(@operators['not'] >> lambda {|a| a.logical_not}, 50).
    infixl(@operators['*'] >>   lambda {|a, b| a*b}, 30).
    infixl(@operators['/'] >>   lambda {|a, b| a/b}, 30).
    infixl(@operators['%'] >>   lambda {|a, b| a%b}, 30).
    infixl(@operators['+'] >>   lambda {|a, b| a+b}, 27).
    infixl(@operators['-'] >>   lambda {|a, b| a-b}, 27).
    infixl(@operators['&'] >>   lambda {|a, b| a&b}, 25).
    infixl(@operators['>'] >>   lambda {|a, b| a>b}, 17).
    infixl(@operators['>='] >>  lambda {|a, b| a>=b}, 17).
    infixl(@operators['<'] >>   lambda {|a, b| a<b}, 17).
    infixl(@operators['<='] >>  lambda {|a, b| a<=b}, 17).
    infixl(@operators['='] >>   lambda {|a, b| a.eq(b)}, 15).
    infixl(@operators['!='] >>  lambda {|a, b| a.neq(b)}, 15).
    infixl(@operators['and'] >> lambda {|a, b| a.logical_and(b)}, 5).
    infixl(@operators['or'] >>  lambda {|a, b| a.logical_or(b)}, 4)
  
  expr = RParsec::Expressions.build(lit, table)
  
  lexeme = tokenizer.lexeme(whitespaces) << eof
  @parser = lexeme.nested(expr << eof)
end

Instance Method Details

#parse(str) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/parsed_calculator.rb', line 64

def parse(str)
  begin
    @parser.parse(str)
  rescue Exception
    raise
  end
end