check.go 987 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
  2. // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
  3. package expr
  4. import (
  5. "fmt"
  6. )
  7. //!+Check
  8. func (v Var) Check(vars map[Var]interface{}) error {
  9. vars[v] = true
  10. return nil
  11. }
  12. func (literal) Check(vars map[Var]interface{}) error {
  13. return nil
  14. }
  15. func (u unary) Check(vars map[Var]interface{}) error {
  16. return u.x.Check(vars)
  17. }
  18. func (b binary) Check(vars map[Var]interface{}) error {
  19. if err := b.x.Check(vars); err != nil {
  20. return err
  21. }
  22. return b.y.Check(vars)
  23. }
  24. func (c call) Check(vars map[Var]interface{}) error {
  25. arity, ok := numParams[c.fn]
  26. if !ok {
  27. return fmt.Errorf("unknown function %q", c.fn)
  28. }
  29. if len(c.args) != arity {
  30. return fmt.Errorf("call to %s has %d args, want %d",
  31. c.fn, len(c.args), arity)
  32. }
  33. for _, arg := range c.args {
  34. if err := arg.Check(vars); err != nil {
  35. return err
  36. }
  37. }
  38. return nil
  39. }
  40. var numParams = map[string]int{"pow": 2, "sin": 1, "sqrt": 1}
  41. //!-Check