Custom object types
Every runtime value in Goblin is a Go implementation of object.Object. The interface is the contract between a value and the interpreter or transpiler. It includes these groups of methods:
| Group | Object methods |
|---|---|
| Display and conversion | ToString(), ToBool() (which ! negates) |
| Comparison and operators | Equals(), Compare(), Add(), Minus(), Multiply(), Divide(), Modulo() |
| Reflected operators | RAdd(), RMinus(), RMultiply(), RDivide(), RModulo() |
| Collection protocols | Iter(), Index() |
| Members | GetAttr(), Attributes(), SetIndex(), SetAttr() |
| Identity | TypeName() |
The reflected operators are required, but most types have nothing to say through them: embed object.NoReflectedOps and they all answer "not handled".
Types should also implement String() string, satisfying fmt.Stringer. It is not part of the interface, but diagnostics and formatting use fmt.Stringer and fall back to TypeName() when String is not available. ToString is the failing counterpart, which for a Goblin-defined type runs its Show impl.
Assignment is part of the interface too: SetIndex and SetAttr return a bool saying whether the value accepts that form of assignment at all. A value that accepts neither embeds object.NoAssignment and says nothing.
Start with a Go struct
This excerpt shows the state, conversion, and member portion of a Counter value. A complete implementation must also provide every remaining object.Object method listed above. Unsupported operators should return the standard TypeError rather than silently accepting an operation.
type Counter struct {
object.NoReflectedOps // nothing completes an operation from Counter's right
object.NoAssignment // counter[i] = x and counter.f = x are not accepted
Value int64
}
func (c *Counter) TypeName() string { return "Counter" }
func (c *Counter) String() string { return fmt.Sprintf("Counter(%d)", c.Value) }
func (c *Counter) ToString() (string, error) { return c.String(), nil }
func (c *Counter) ToBool() (bool, error) { return c.Value != 0, nil }
func (c *Counter) GetAttr(name string) (object.Object, error) {
switch name {
case "value":
return object.Integer(c.Value), nil
case "increment":
return &object.Function{Name: "increment", Fn: c.increment}, nil
default:
return nil, object.NewAttributeError("Counter has no attribute '%s'", name)
}
}
// Attributes lists what attributes(counter) shows: properties first, then
// methods.
func (c *Counter) Attributes() []string {
return []string{"value", "increment"}
}
func (c *Counter) increment(args object.CallArgs) (object.Object, error) {
if err := object.RequireNoKeyword("increment", args); err != nil {
return nil, err
}
if len(args.Positional) != 0 {
return nil, object.NewTypeError("increment() takes no arguments")
}
c.Value++
return object.Integer(c.Value), nil
}
The receiver-bound object.Function is the key pattern: Goblin evaluates counter.increment() by looking up increment and then calling the returned function. It can safely mutate the Go receiver.
For example, a Counter that has no addition at all should implement Add by returning object.Unsupported with the matching object.ErrFmt format, which reads "cannot add Counter". Apply the same principle to the other unsupported protocol methods. A handle type with no operators at all can embed object.OpaqueBase instead of writing them out.
func (c *Counter) Add(other object.Object) (object.Object, error) {
return nil, object.Unsupported("Counter", object.ErrFmtCannotAdd)
}
Define protocol behavior deliberately
Return a useful result for supported operations and a TypeError for unsupported ones. For example, a Vector can implement Add and Compare while a Counter may only need display, truthiness, and members. When the operation exists but the right operand does not fit, object.NewOperandError words the error the way the built-in types do: "cannot add Vector and String".
func (v Vector) Add(other object.Object) (object.Object, error) {
right, ok := other.(Vector)
if !ok {
return nil, object.NewOperandError(object.OpAdd, "Vector", other)
}
return Vector{X: v.X + right.X, Y: v.Y + right.Y}, nil
}
Compare returns a negative value, zero, or a positive value. Iter returns a slice of object.Object values. Index must verify that its index is an object.Integer and return IndexError for an invalid position.
A type whose elements are produced one at a time (lines of a stream, a large
or unbounded sequence) also implements object.Iterable, whose Iterator method
starts a pass and returns an object.Iterator. Its Next returns the next value
and true, false at the end, or an error that the loop raises at the for
statement. Every consumer — for, destructuring, * arguments, List(x) —
goes through object.Iterate, which prefers Iterable over Iter, so Iter can then
simply return object.Collect(v). Go code that walks an arbitrary value calls
object.Iterate (or object.Collect for the whole slice) rather than Iter.
A loop may stop pulling before the end (break, return, an error), so a pass
is ended explicitly: whoever starts one with object.Iterate calls the
Iteration's Close exactly once however the pass ends, and never calls Next
after it. An iterator that holds something for the duration of one pass (a
file it opened in Iterator, say) also implements object.Closer and releases it
in Close, and only there; object.IteratorWithClose(next, close) builds one from
two functions. Close cannot fail, so a source whose release can fail reports
that from its last Next. A pass owns only what it acquired when it started:
iterating a file leaves the file open, because the file is the iterable's, not
the pass's.
func (c Countdown) Iter() ([]object.Object, error) { return object.Collect(c) }
func (c Countdown) Iterator() (object.Iterator, error) {
n := c.From
return object.IteratorFunc(func() (object.Object, bool, error) {
if n <= 0 {
return nil, false, nil
}
n--
return object.Integer(n + 1), true, nil
}), nil
}
Name types in messages with TypeName
Use value.TypeName(), not %T, when an error mentions the type of a value. A Go
type name is an implementation detail that differs between the two backends — a
user-defined Point is *interpreter.instance under goblin run and *main.Point
in a compiled program — so %T makes the same program report different messages
depending on how it was executed. TypeName returns the Goblin-level name, which
is why every type declares it:
func (v Vector) TypeName() string { return "Vector" }
Embedding is not enough here: a type that embeds another for its defaults inherits that type's name too, which is exactly the wrong answer.
Operators dispatch through package-level helpers
The operators do not call Equals, Compare, Add and friends on the left operand
directly: both backends go through object.Equals and object.NotEquals, the
ordering helpers object.Less, object.LessEqual, object.Greater and
object.GreaterEqual, and object.Add, object.Minus, object.Multiply,
object.Divide and object.Modulo, which also give the right operand a chance to
answer.
A custom type therefore only has to recognize the types it knows, and its
Compare is reached even when it appears on the right of 1 < value. Report an
unfit pair with object.NewTypeError so the reflected attempt is made; any other
error propagates as-is. Equals follows the same rule with its own error return:
a TypeError from it means "not this type" and leaves == total, while any
other error fails the comparison.
Arithmetic reaches the right operand through RAdd, RMinus, RMultiply, RDivide
and RModulo, the Go side of Add.radd and friends. Their argument is the LEFT
operand — RMinus(left) computes left - receiver — and the bool they return
reports whether the receiver handled this operand at all; returning false
leaves the left operand's error in place. Embed object.NoReflectedOps and
override only the operator a type completes from the right, the way
object.String and object.List override RMultiply to make 3 * "ab" work:
type Vector struct {
object.NoReflectedOps
X, Y float64
}
// `2 * v` — scaling reads the same in either operand order.
func (v Vector) RMultiply(left object.Object) (object.Object, bool, error) {
n, ok := left.(object.Integer)
if !ok {
return nil, false, nil
}
return Vector{X: v.X * float64(n), Y: v.Y * float64(n)}, true, nil
}
A Go type has no impl blocks: it implements the object.Object methods, and by
that the protocols. a < b or compare(a, b) on a Go value calls
object.Compare, String(x) calls ToString, a + b calls object.Add, and so
on, so a Go type that implements Compare works with max and sort without
further work.
For a complete reference implementation, read the existing runtime types in object/, especially path.go, list.go, dict.go, bytes.go, and chan.go. They show how to report errors consistently and how to expose methods through GetAttr.
Expose a constructor with stable type identity
Most custom values need a constructor added to a module or to the built-ins
map. Use object.NewNativeConstructor so the exported callable and every
instance share one stable identity, matching Goblin-defined types:
var CounterType = object.NewNativeConstructor(
"Counter",
func(args object.CallArgs) (object.Object, error) {
p := object.NewArgParser("Counter", args)
start := p.IntOr("start", 0)
if err := p.Finish(); err != nil {
return nil, err
}
return &Counter{Value: int64(start)}, nil
},
)
Place CounterType.Function in the module members map, and have the value
return the same function from a Constructor method, which is what
type_of asks for (the object.Constructed interface):
func (c *Counter) Constructor() *object.Function { return CounterType.Function }
Goblin can then use the same constructor identity check for native, built-in, and source-defined values:
var counter = module.Counter(start=10)
print(type_of(counter) == module.Counter) # true
A type that a module exports only for type_of comparisons, with no way to
build it from arguments, uses object.NewOpaqueConstructor("File", "fs.open(path)"):
calling it raises TypeError: File cannot be constructed; use fs.open(path).
A value without a Constructor method still has a type: type_of answers a
stand-in function named after its TypeName, which cannot be called.
Create the helper once at package scope. Constructing it during every module load would give the same native type multiple identities. See Functions and arguments for the argument parser used by the constructor.