well_formed.cc 1.51 KB
Newer Older
1 2 3 4 5 6 7
/*!
 *  Copyright (c) 2018 by Contributors
 * \file well_formed.cc
 * \brief check that expression is well formed.
 */
#include <tvm/relay/pass.h>
#include <tvm/relay/expr_functor.h>
8
#include <tvm/relay/pattern_functor.h>
9 10 11 12 13 14 15
#include <unordered_set>

namespace tvm {
namespace relay {


//! brief make sure each Var is bind at most once.
16
class WellFormedChecker : private ExprVisitor, PatternVisitor {
17 18 19 20
  bool well_formed = true;

  std::unordered_set<Var, NodeHash, NodeEqual> s;

21
  void Check(const Var& v) {
22 23 24 25 26 27
    if (s.count(v) != 0) {
      well_formed = false;
    }
    s.insert(v);
  }

28
  void VisitExpr_(const LetNode* l) final {
29 30 31 32 33 34 35
    // we do letrec only for FunctionNode,
    // but shadowing let in let binding is likely programming error, and we should forbidden it.
    Check(l->var);
    CheckWellFormed(l->value);
    CheckWellFormed(l->body);
  }

36 37
  void VisitExpr_(const FunctionNode* f) final {
    for (const Var& param : f->params) {
38
      Check(param);
39 40 41 42
    }
    CheckWellFormed(f->body);
  }

43 44 45 46 47 48 49 50
  void VisitPattern(const Pattern& p) final {
    PatternVisitor::VisitPattern(p);
  }

  void VisitVar(const Var& v) final {
    Check(v);
  }

51
 public:
52
  bool CheckWellFormed(const Expr& e) {
53 54 55 56 57
    this->VisitExpr(e);
    return well_formed;
  }
};

58
bool WellFormed(const Expr& e) {
59 60 61 62 63 64 65 66 67 68 69
  return WellFormedChecker().CheckWellFormed(e);
}

TVM_REGISTER_API("relay._ir_pass.well_formed")
  .set_body([](TVMArgs args, TVMRetValue *ret) {
      Expr e = args[0];
      *ret = WellFormed(e);
    });

}  // namespace relay
}  // namespace tvm