well_formed.cc 2.22 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16 17 18 19
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

20 21 22 23 24
/*!
 *  Copyright (c) 2018 by Contributors
 * \file well_formed.cc
 * \brief check that expression is well formed.
 */
Zhi committed
25
#include <tvm/relay/analysis.h>
26
#include <tvm/relay/expr_functor.h>
27
#include <tvm/relay/pattern_functor.h>
28 29 30 31 32 33 34
#include <unordered_set>

namespace tvm {
namespace relay {


//! brief make sure each Var is bind at most once.
35
class WellFormedChecker : private ExprVisitor, PatternVisitor {
36 37 38 39
  bool well_formed = true;

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

40
  void Check(const Var& v) {
41 42 43 44 45 46
    if (s.count(v) != 0) {
      well_formed = false;
    }
    s.insert(v);
  }

47
  void VisitExpr_(const LetNode* l) final {
48 49 50 51 52 53 54
    // 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);
  }

55 56
  void VisitExpr_(const FunctionNode* f) final {
    for (const Var& param : f->params) {
57
      Check(param);
58 59 60 61
    }
    CheckWellFormed(f->body);
  }

62 63 64 65 66 67 68 69
  void VisitPattern(const Pattern& p) final {
    PatternVisitor::VisitPattern(p);
  }

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

70
 public:
71
  bool CheckWellFormed(const Expr& e) {
72 73 74 75 76
    this->VisitExpr(e);
    return well_formed;
  }
};

77
bool WellFormed(const Expr& e) {
78 79 80
  return WellFormedChecker().CheckWellFormed(e);
}

Zhi committed
81
TVM_REGISTER_API("relay._analysis.well_formed")
82
.set_body_typed(WellFormed);
83 84 85

}  // namespace relay
}  // namespace tvm