well_formed.cc 1.31 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*!
 *  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>
#include <unordered_set>

namespace tvm {
namespace relay {


//! brief make sure each Var is bind at most once.
class WellFormedChecker : private ExprVisitor {
  bool well_formed = true;

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

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

27
  void VisitExpr_(const LetNode* l) final {
28 29 30 31 32 33 34
    // 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);
  }

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

 public:
43
  bool CheckWellFormed(const Expr& e) {
44 45 46 47 48
    this->VisitExpr(e);
    return well_formed;
  }
};

49
bool WellFormed(const Expr& e) {
50 51 52 53 54 55 56 57 58 59 60
  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