operation.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Find a way to improve this mess
  2. package flow
  3. import (
  4. "errors"
  5. "reflect"
  6. )
  7. type operation interface {
  8. fref() ref
  9. Process(params ...Data) Data
  10. }
  11. // Ref and cacher?
  12. // common operation
  13. type ref struct {
  14. flow *Flow
  15. // Type? serializable
  16. ID int `json:"id"`
  17. }
  18. // ref ref ref
  19. func (r ref) fref() ref {
  20. return r
  21. }
  22. func typeName(o operation) string {
  23. switch o.(type) {
  24. case OpIn:
  25. return "in"
  26. case OpVar:
  27. return "data"
  28. case OpConst:
  29. return "const"
  30. case OpFunc:
  31. return "func"
  32. }
  33. return ""
  34. }
  35. type OpIn struct{ ref }
  36. type OpVar struct{ ref }
  37. type OpConst struct{ ref }
  38. type OpFunc struct{ ref }
  39. func (o OpIn) Process(p ...Data) Data {
  40. if o.ID >= len(p) || o.ID < 0 {
  41. o.flow.err = errors.New("Invalid input")
  42. return nil
  43. }
  44. return p[o.ID]
  45. }
  46. func (o OpVar) Process(...Data) Data { return o.flow.data[o.ID] } // Get
  47. // Set variable set
  48. func (o OpVar) Set(value Data) { o.flow.data[o.ID] = value }
  49. // OpConst const operator
  50. func (o OpConst) Process(...Data) Data { return o.flow.consts[o.ID] } // Get
  51. // Make this else where?
  52. func (o OpFunc) Process(params ...Data) Data {
  53. op := o.flow.operations[o.ID]
  54. // Grab operation inputs from flow
  55. callParam := make([]reflect.Value, len(op.inputs))
  56. for i, in := range op.inputs {
  57. switch v := in.(type) {
  58. case operation:
  59. callParam[i] = reflect.ValueOf(v.Process(params...))
  60. default: // {lpf} Analyse this
  61. panic(errors.New("Is not operation"))
  62. }
  63. }
  64. return reflect.ValueOf(op.executor).Call(callParam)[0].Interface()
  65. }