2018-09-18 22:42:38 +02:00
|
|
|
package collections
|
|
|
|
|
2018-10-25 03:30:05 +02:00
|
|
|
import (
|
2018-11-13 02:58:12 +02:00
|
|
|
"context"
|
2019-03-29 16:48:51 +02:00
|
|
|
|
2018-10-25 03:30:05 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
|
|
|
)
|
2018-09-18 22:42:38 +02:00
|
|
|
|
2018-10-25 03:30:05 +02:00
|
|
|
type (
|
2019-02-15 14:41:08 +02:00
|
|
|
// Measurable represents an interface of a value that can has length.
|
|
|
|
Measurable interface {
|
2018-10-25 03:30:05 +02:00
|
|
|
Length() values.Int
|
|
|
|
}
|
|
|
|
|
|
|
|
IndexedCollection interface {
|
2019-02-15 14:41:08 +02:00
|
|
|
core.Value
|
|
|
|
Measurable
|
2018-10-25 03:30:05 +02:00
|
|
|
Get(idx values.Int) core.Value
|
|
|
|
Set(idx values.Int, value core.Value) error
|
|
|
|
}
|
|
|
|
|
|
|
|
KeyedCollection interface {
|
2019-02-15 14:41:08 +02:00
|
|
|
core.Value
|
|
|
|
Measurable
|
2019-03-13 20:51:30 +02:00
|
|
|
Keys() []values.String
|
2018-10-25 03:30:05 +02:00
|
|
|
Get(key values.String) (core.Value, values.Boolean)
|
|
|
|
Set(key values.String, value core.Value)
|
|
|
|
}
|
2018-11-13 02:58:12 +02:00
|
|
|
|
2019-02-15 14:41:08 +02:00
|
|
|
coreIterator struct {
|
2018-11-13 02:58:12 +02:00
|
|
|
valVar string
|
|
|
|
keyVar string
|
2019-02-15 14:41:08 +02:00
|
|
|
values core.Iterator
|
2018-11-13 02:58:12 +02:00
|
|
|
}
|
2018-10-25 03:30:05 +02:00
|
|
|
)
|
2018-11-13 02:58:12 +02:00
|
|
|
|
2019-03-29 16:48:51 +02:00
|
|
|
func NewCoreIterator(valVar, keyVar string, values core.Iterator) (Iterator, error) {
|
2019-02-15 14:41:08 +02:00
|
|
|
return &coreIterator{valVar, keyVar, values}, nil
|
2018-11-13 02:58:12 +02:00
|
|
|
}
|
|
|
|
|
2019-02-15 14:41:08 +02:00
|
|
|
func (iterator *coreIterator) Next(ctx context.Context, scope *core.Scope) (*core.Scope, error) {
|
2018-11-13 02:58:12 +02:00
|
|
|
val, key, err := iterator.values.Next(ctx)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// end of iteration
|
|
|
|
if val == values.None {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
nextScope := scope.Fork()
|
|
|
|
|
|
|
|
if err := nextScope.SetVariable(iterator.valVar, val); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if iterator.keyVar != "" {
|
|
|
|
if err := nextScope.SetVariable(iterator.keyVar, key); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nextScope, nil
|
|
|
|
}
|