github.com/lab47/exprcore@v0.0.0-20210525052339-fb7d6bd9331e/exprcorestruct/module.go (about)

     1  package exprcorestruct
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/lab47/exprcore/exprcore"
     7  )
     8  
     9  // A Module is a named collection of values,
    10  // typically a suite of functions imported by a load statement.
    11  //
    12  // It differs from Struct primarily in that its string representation
    13  // does not enumerate its fields.
    14  type Module struct {
    15  	Name    string
    16  	Members exprcore.StringDict
    17  }
    18  
    19  var _ exprcore.HasAttrs = (*Module)(nil)
    20  
    21  func (m *Module) Attr(name string) (exprcore.Value, error) { return m.Members[name], nil }
    22  func (m *Module) AttrNames() []string                      { return m.Members.Keys() }
    23  func (m *Module) Freeze()                                  { m.Members.Freeze() }
    24  func (m *Module) Hash() (uint32, error)                    { return 0, fmt.Errorf("unhashable: %s", m.Type()) }
    25  func (m *Module) String() string                           { return fmt.Sprintf("<module %q>", m.Name) }
    26  func (m *Module) Truth() exprcore.Bool                     { return true }
    27  func (m *Module) Type() string                             { return "module" }
    28  
    29  // MakeModule may be used as the implementation of a exprcore built-in
    30  // function, module(name, **kwargs). It returns a new module with the
    31  // specified name and members.
    32  func MakeModule(thread *exprcore.Thread, b *exprcore.Builtin, args exprcore.Tuple, kwargs []exprcore.Tuple) (exprcore.Value, error) {
    33  	var name string
    34  	if err := exprcore.UnpackPositionalArgs(b.Name(), args, nil, 1, &name); err != nil {
    35  		return nil, err
    36  	}
    37  	members := make(exprcore.StringDict, len(kwargs))
    38  	for _, kwarg := range kwargs {
    39  		k := string(kwarg[0].(exprcore.String))
    40  		members[k] = kwarg[1]
    41  	}
    42  	return &Module{name, members}, nil
    43  }