Sha256: 9f9518e6b0be07c74a85f0fbd6b12b7c8f0306e6b5aabe5355f52eb367b05d27

Contents?: true

Size: 1.49 KB

Versions: 3

Compression:

Stored size: 1.49 KB

Contents

# frozen_string_literal: true

require_relative '../datatype/all_datatypes'

module Loxxy
  module BackEnd
    # Runtime representation of a Lox object (instance).
    class LoxInstance
      # @return BackEnd::LoxClass] the class that this object is an instance of
      attr_reader :klass

      attr_reader :engine

      # @return [Hash{String => BuiltinDatatype | LoxFunction | LoxInstance }]
      attr_reader :fields

      # Create an instance from given class
      # @param aClass [BackEnd::LoxClass] the class this this object belong
      def initialize(aClass, anEngine)
        @klass = aClass
        @engine = anEngine
        @fields = {}
      end

      def accept(_visitor)
        engine.stack.push self
      end

      # Text representation of a Lox instance
      def to_str
        "#{klass.to_str} instance"
      end

      # Look up the value of property with given name
      # aName [String] name of object property
      def get(aName)
        return fields[aName] if fields.include? aName

        method = klass.find_method(aName)
        unless method
          raise StandardError, "Undefined property '#{aName}'."
        end

        method.bind(self)
      end

      # Set the value of property with given name
      # aName [String] name of object property
      def set(aName, aValue)
        unless fields.include? aName
          raise StandardError, "Undefined property '#{aName}'."
        end

        fields[aName] = aValue
      end
    end # class
  end # module
end # module

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
loxxy-0.1.16 lib/loxxy/back_end/lox_instance.rb
loxxy-0.1.15 lib/loxxy/back_end/lox_instance.rb
loxxy-0.1.14 lib/loxxy/back_end/lox_instance.rb