Class: WMLAction::Tag::Expr

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

Defined Under Namespace

Classes: Op, Var

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(elements) ⇒ Expr

Returns a new instance of Expr.



20
21
22
# File 'lib/wml_action/expr.rb', line 20

def initialize(elements)
  @line = elements
end

Instance Attribute Details

#lineObject

Returns the value of attribute line.



5
6
7
# File 'lib/wml_action/expr.rb', line 5

def line
  @line
end

Class Method Details

.[](*elements) ⇒ Object



78
79
80
# File 'lib/wml_action/expr.rb', line 78

def self.[](*elements)
  new elements
end

Instance Method Details

#<<(other) ⇒ Object



73
74
75
76
# File 'lib/wml_action/expr.rb', line 73

def <<(other)
  @line=@line+other.line
  return self
end

#==(other) ⇒ Object



59
60
61
# File 'lib/wml_action/expr.rb', line 59

def ==(other)
  @line==other.line
end

#dot_concat(s1, s2) ⇒ Object

Raises:

  • (NoMethodError)


50
51
52
53
54
55
56
57
# File 'lib/wml_action/expr.rb', line 50

def dot_concat(s1,s2)
  quote=/\"/
  m1=s1.match(quote)
  m2=s2.match(quote)
  raise NoMethodError.new("Can not dot-concat #{s1} and #{s2}, all have quotes") if m1 && m2
  return s1.clone.insert(s1.rindex(quote),s2) if m1
  return s2.clone.insert(s2.index(quote)+1,s1) if m2
end

#dumpObject



69
70
71
# File 'lib/wml_action/expr.rb', line 69

def dump
  @line.join(' ')
end

#result(vars = {}) ⇒ Object

Raises:

  • (SyntaxError)


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
# File 'lib/wml_action/expr.rb', line 24

def result(vars={})
  return '' if @line.empty?
  stack=[]
  @line.each do |e|
    case e
    when Var then stack.push vars[e.name]
    when Op then
      x2 = stack.pop
      x1 = stack.pop
      raise SyntaxError.new("Invalid expression #{dump}, no values in stack") unless x1 && x2
      case e.value
      when '+' then stack.push(x1+x2)
      when '-' then stack.push(x1-x2)
      when '*' then stack.push(x1.to_f*x2)
      when '/' then stack.push(x1.to_f/x2)
      when '.' then stack.push(dot_concat(x1,x2))
      else raise NoMethodError.new("No such operation #{e.value}")
      end
    else stack.push e
    end
  end
  raise SyntaxError.new("Invalid expression #{dump}, still have #{stack.size} values") unless stack.size == 1
  return stack[0].to_i if stack[0].class==Float
  return stack[0]
end

#to_sObject



63
64
65
66
67
# File 'lib/wml_action/expr.rb', line 63

def to_s
  #TODO should revert to infix notation for file output
  # needed to read outputted file
  dump
end