116 lines
1.9 KiB
Go
116 lines
1.9 KiB
Go
package object
|
|
|
|
import (
|
|
"fmt"
|
|
"monkey/internal/context"
|
|
)
|
|
|
|
// Type represents the type of an object
|
|
type Type int
|
|
|
|
const (
|
|
NullType = iota
|
|
IntegerType
|
|
FloatType
|
|
StringType
|
|
BooleanType
|
|
ReturnType
|
|
ErrorType
|
|
FunctionType
|
|
CFunctionType
|
|
BuiltinType
|
|
ClosureType
|
|
ArrayType
|
|
HashType
|
|
ModuleType
|
|
)
|
|
|
|
func (t Type) String() string {
|
|
switch t {
|
|
case NullType:
|
|
return "null"
|
|
case IntegerType:
|
|
return "int"
|
|
case FloatType:
|
|
return "float"
|
|
case StringType:
|
|
return "str"
|
|
case BooleanType:
|
|
return "bool"
|
|
case ReturnType:
|
|
return "Return"
|
|
case ErrorType:
|
|
return "error"
|
|
case FunctionType:
|
|
return "fn"
|
|
case CFunctionType:
|
|
return "CFunction"
|
|
case BuiltinType:
|
|
return "Builtin"
|
|
case ClosureType:
|
|
return "Closure"
|
|
case ArrayType:
|
|
return "array"
|
|
case HashType:
|
|
return "hash"
|
|
case ModuleType:
|
|
return "module"
|
|
default:
|
|
return "???"
|
|
}
|
|
}
|
|
|
|
// Copyable is the interface for creating copies of objects
|
|
type Copyable interface {
|
|
Copy() Object
|
|
}
|
|
|
|
// Object represents a value and implementations are expected to implement
|
|
// `Type()` and `Inspect()` functions
|
|
type Object interface {
|
|
fmt.Stringer
|
|
Type() Type
|
|
Bool() bool
|
|
Compare(Object) int
|
|
Inspect() string
|
|
}
|
|
|
|
type BaseObject struct{}
|
|
|
|
func (o BaseObject) Compare(other Object) int { return -1 }
|
|
|
|
// Hasher is the interface for objects to provide suitable hash keys
|
|
type Hasher interface {
|
|
Hash() HashKey
|
|
}
|
|
|
|
// BuiltinFunction represents the builtin function type
|
|
type BuiltinFunction func(ctx context.Context, args ...Object) Object
|
|
|
|
func AssertTypes(obj Object, types ...Type) bool {
|
|
for _, t := range types {
|
|
if t == obj.Type() {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func FromNativeBoolean(b bool) Boolean {
|
|
if b {
|
|
return TRUE
|
|
}
|
|
return FALSE
|
|
}
|
|
|
|
func IsTruthy(obj Object) bool {
|
|
switch obj := obj.(type) {
|
|
case Boolean:
|
|
return obj.Value
|
|
case Null:
|
|
return false
|
|
default:
|
|
return true
|
|
}
|
|
}
|