Class: LXL::Parser

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

Overview

Lexical Types

;  Statement separator
,  Argument separator
=  Formula prefix
(  Tuple open
)  Tuple close
w  Whitespace
o  Operator
s  String
r  Range
p  Percentage
f  Float
i  Integer
u  Unknown

F Function
C Constant

Constant Summary collapse

RUBY_OPERATORS =
['+', '-', '*', '/', '<=', '>=', '==', '!=', '<', '>', '+', '**']
EXCEL_OPERATORS =
['+', '-', '*', '/', '<=', '>=', '=',  '<>', '<', '>', '&', '^' ]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(namespace = self.class.namespace_class.new) ⇒ Parser

Initialize namespace and lexer.



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/lxl.rb', line 244

def initialize(namespace=self.class.namespace_class.new)
  @namespace = namespace
  ops = EXCEL_OPERATORS.collect { |v| Regexp.quote(v) }.join('|')
  xlr = LXL::Range::EXCEL_RANGE
  @lexer = self.class.lexer_class.new([
    [/\A;+/, ?;],              # Statement separator
    [/\A,+/, ?,],              # Argument separator
    [/\A`=/, ?=],              # Formula prefix
    [/\A\(/, ?(],              # Tuple open
    [/\A\)/, ?)],              # Tuple close
    [/\A\s+/, ?w],             # Whitespace
    [/\A(#{ops})/, ?o],        # Operator
    [/\A("([^"]|"")*")/m, ?s], # String
    [xlr, ?r],                 # Range
    [/\A\d+(\.\d+)?%/, ?p],    # Percentage
    [/\A\d+\.\d+/, ?f],        # Float
    [/\A\d+/, ?i],             # Integer
    [/\A\w+/, ?u],             # Unknown
  ])
end

Class Method Details

.eval(formula) ⇒ Object

Evaluate a formula.



214
215
216
# File 'lib/lxl.rb', line 214

def self.eval(formula)
  self.new.eval(formula)
end

.lexer_classObject

Default lexer class.



226
227
228
# File 'lib/lxl.rb', line 226

def self.lexer_class
  LXL::Lexer
end

.namespace_classObject

Default namespace class.



232
233
234
# File 'lib/lxl.rb', line 232

def self.namespace_class
  LXL::Namespace
end

.range_classObject

Default range class.



238
239
240
# File 'lib/lxl.rb', line 238

def self.range_class
  LXL::Range
end

.token_classObject

Default token class.



220
221
222
# File 'lib/lxl.rb', line 220

def self.token_class
  LXL::Token
end

Instance Method Details

#eval(string) ⇒ Object

Evaluate a formula.



267
268
269
270
271
272
# File 'lib/lxl.rb', line 267

def eval(string)
  formulas = tokenize(string)
  formulas.collect! { |f| f.collect { |t| t.value }.join }
  formulas.collect! { |f| Kernel.eval(f, binding) }
  formulas.size == 1 ? formulas.first : formulas
end