Class: Loxxy::BackEnd::BinaryOperator

Inherits:
Object
  • Object
show all
Defined in:
lib/loxxy/back_end/binary_operator.rb

Overview

A Lox binary operator

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(aName, theSignatures) ⇒ BinaryOperator

Returns a new instance of BinaryOperator.

Parameters:

  • aName (String)

    "name" of operator

  • theSignatures (Array<Signature>)

    allowed signatures



19
20
21
22
# File 'lib/loxxy/back_end/binary_operator.rb', line 19

def initialize(aName, theSignatures)
  @name = aName
  @signatures = theSignatures
end

Instance Attribute Details

#nameString (readonly)

Returns text representation of the operator.

Returns:

  • (String)

    text representation of the operator



12
13
14
# File 'lib/loxxy/back_end/binary_operator.rb', line 12

def name
  @name
end

#signaturesArray<Class> (readonly)

Returns:

  • (Array<Class>)


15
16
17
# File 'lib/loxxy/back_end/binary_operator.rb', line 15

def signatures
  @signatures
end

Instance Method Details

#validate_operands(operand1, operand2) ⇒ Object

rubocop: disable Style/ClassEqualityComparison



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/loxxy/back_end/binary_operator.rb', line 25

def validate_operands(operand1, operand2)
  compliant = signatures.find do |(type1, type2)|
    next unless operand1.kind_of?(type1)

    if type2 == :idem
      (operand2.class == operand1.class)
    else
      operand2.kind_of?(type2)
    end
  end
  # rubocop: enable Style/ClassEqualityComparison

  unless compliant
    err = Loxxy::RuntimeError
    if signatures.size == 1 && signatures[0].last == :idem
      raise err, "Operands must be #{datatype_name(signatures[0].first)}s."
    elsif signatures.size == 2 && signatures.all? { |(_, second)| second == :idem }
      type1 = datatype_name(signatures[0].first)
      type2 = datatype_name(signatures[1].first)
      raise err, "Operands must be two #{type1}s or two #{type2}s."
    end
  end
end