coroutines.go 1000 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package zygo
  2. import (
  3. "errors"
  4. )
  5. type SexpGoroutine struct {
  6. env *Zlisp
  7. }
  8. func (goro *SexpGoroutine) SexpString(ps *PrintState) string {
  9. return "[coroutine]"
  10. }
  11. func (goro *SexpGoroutine) Type() *RegisteredType {
  12. return nil // TODO what goes here
  13. }
  14. func StartGoroutineFunction(env *Zlisp, name string,
  15. args []Sexp) (Sexp, error) {
  16. switch t := args[0].(type) {
  17. case *SexpGoroutine:
  18. go t.env.Run()
  19. default:
  20. return SexpNull, errors.New("not a goroutine")
  21. }
  22. return SexpNull, nil
  23. }
  24. func CreateGoroutineMacro(env *Zlisp, name string,
  25. args []Sexp) (Sexp, error) {
  26. goroenv := env.Duplicate()
  27. err := goroenv.LoadExpressions(args)
  28. if err != nil {
  29. return SexpNull, nil
  30. }
  31. goro := &SexpGoroutine{goroenv}
  32. // (apply StartGoroutineFunction [goro])
  33. return MakeList([]Sexp{env.MakeSymbol("apply"),
  34. MakeUserFunction("__start", StartGoroutineFunction),
  35. &SexpArray{Val: []Sexp{goro}, Env: env}}), nil
  36. }
  37. func (env *Zlisp) ImportGoroutines() {
  38. env.AddMacro("go", CreateGoroutineMacro)
  39. }