[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r451088080



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1384 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+/*! \brief A wrapper structure for capturing the result of parsing
+ * a global definition *before* we add it to the IRModule.
+ *
+ * This enables the parser to parse everything in one pass before
+ * constructing the IRModule.
+ */
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+/*! \brief A wrapper structure for capturing all top-level definitions
+ * when parsing a module.
+ */
+struct Definitions {
+  /*! \brief The set of global functions. */
+  std::vector funcs;
+  /*! \brief The set of type definitions. */
+  std::vector types;
+  // TODO(@jroesch): contain meta-table below
+};
+
+/*! \brief A structure representing the semantic versioning information
+ * for a Relay program.
+ */
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+/*! \brief A reference to a "meta-expression".
+ *
+ * In the text format we allow referencing metadata which
+ * uses a compact serialization that proceeds the main
+ * program body.
+ *
+ * We can reference this table using an expression of
+ * the form `meta[Type][index]`.
+ *
+ * We must later resolve these references to actual in-memory
+ * AST nodes but this requires first parsing the full program
+ * then expanding these temporary AST nodes into their corresponding
+ * nodes.
+ *
+ * For example the nth large constant will be pretty-printed as 
meta[relay.Constant][n]
+ * with its compact binary serialization residing in the metadata section at 
the end
+ * of the program.
+ */
+class MetaRefExprNode : public TempExprNode {
+ public:
+  /*! \brief The type key of the meta expression. */
+  std::string type_key;
+  /*! \brief The index into the type key's table. */
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  // TODO(@jroesch): we probably will need to manually
+  // expand these with a pass.
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor for MetaRefExpr
+   * \param type_key The type key of the object in the meta section.
+   * \param kind The index into that subfield.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+/*! \brief A simple wrapper around a mapping from raw string names
+ * to a TVM variable, type variable or other binder type.
+ */
+template 
+struct Scope {
+  /*! \brief The internal map. */
+  std::unordered_map name_map;
+};
+
+/*! \brief A stack of scopes.
+ *
+ * In order to properly handle scoping we must maintain a scope of stacks.
+ *
+ * A stack allows users to write programs which contain repeated variable
+ * names and to properly handle both nested scopes and removal of variables
+ * when they go out of scope.
+ *
+ * This is the classic approach to lexical scoping.
+ */
+template 
+class ScopeStack {
+ private:
+  std::vector> scope_stack;
+
+ public:
+  /*! \brief Adds a variable binding to the current scope. */
+  void Add(const std::string& name, const T& value

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r451087346



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1384 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+/*! \brief A wrapper structure for capturing the result of parsing
+ * a global definition *before* we add it to the IRModule.
+ *
+ * This enables the parser to parse everything in one pass before
+ * constructing the IRModule.
+ */
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+/*! \brief A wrapper structure for capturing all top-level definitions
+ * when parsing a module.
+ */
+struct Definitions {
+  /*! \brief The set of global functions. */
+  std::vector funcs;
+  /*! \brief The set of type definitions. */
+  std::vector types;
+  // TODO(@jroesch): contain meta-table below
+};
+
+/*! \brief A structure representing the semantic versioning information
+ * for a Relay program.
+ */
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+/*! \brief A reference to a "meta-expression".
+ *
+ * In the text format we allow referencing metadata which
+ * uses a compact serialization that proceeds the main
+ * program body.
+ *
+ * We can reference this table using an expression of
+ * the form `meta[Type][index]`.
+ *
+ * We must later resolve these references to actual in-memory
+ * AST nodes but this requires first parsing the full program
+ * then expanding these temporary AST nodes into their corresponding
+ * nodes.
+ *
+ * For example the nth large constant will be pretty-printed as 
meta[relay.Constant][n]
+ * with its compact binary serialization residing in the metadata section at 
the end
+ * of the program.
+ */
+class MetaRefExprNode : public TempExprNode {
+ public:
+  /*! \brief The type key of the meta expression. */
+  std::string type_key;
+  /*! \brief The index into the type key's table. */
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  // TODO(@jroesch): we probably will need to manually
+  // expand these with a pass.
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor for MetaRefExpr
+   * \param type_key The type key of the object in the meta section.
+   * \param kind The index into that subfield.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+/*! \brief A simple wrapper around a mapping from raw string names
+ * to a TVM variable, type variable or other binder type.
+ */
+template 
+struct Scope {
+  /*! \brief The internal map. */
+  std::unordered_map name_map;
+};
+
+/*! \brief A stack of scopes.
+ *
+ * In order to properly handle scoping we must maintain a scope of stacks.
+ *
+ * A stack allows users to write programs which contain repeated variable
+ * names and to properly handle both nested scopes and removal of variables
+ * when they go out of scope.
+ *
+ * This is the classic approach to lexical scoping.
+ */
+template 
+class ScopeStack {
+ private:
+  std::vector> scope_stack;
+
+ public:
+  /*! \brief Adds a variable binding to the current scope. */
+  void Add(const std::string& name, const T& value

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r451087346



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1384 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+/*! \brief A wrapper structure for capturing the result of parsing
+ * a global definition *before* we add it to the IRModule.
+ *
+ * This enables the parser to parse everything in one pass before
+ * constructing the IRModule.
+ */
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+/*! \brief A wrapper structure for capturing all top-level definitions
+ * when parsing a module.
+ */
+struct Definitions {
+  /*! \brief The set of global functions. */
+  std::vector funcs;
+  /*! \brief The set of type definitions. */
+  std::vector types;
+  // TODO(@jroesch): contain meta-table below
+};
+
+/*! \brief A structure representing the semantic versioning information
+ * for a Relay program.
+ */
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+/*! \brief A reference to a "meta-expression".
+ *
+ * In the text format we allow referencing metadata which
+ * uses a compact serialization that proceeds the main
+ * program body.
+ *
+ * We can reference this table using an expression of
+ * the form `meta[Type][index]`.
+ *
+ * We must later resolve these references to actual in-memory
+ * AST nodes but this requires first parsing the full program
+ * then expanding these temporary AST nodes into their corresponding
+ * nodes.
+ *
+ * For example the nth large constant will be pretty-printed as 
meta[relay.Constant][n]
+ * with its compact binary serialization residing in the metadata section at 
the end
+ * of the program.
+ */
+class MetaRefExprNode : public TempExprNode {
+ public:
+  /*! \brief The type key of the meta expression. */
+  std::string type_key;
+  /*! \brief The index into the type key's table. */
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  // TODO(@jroesch): we probably will need to manually
+  // expand these with a pass.
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor for MetaRefExpr
+   * \param type_key The type key of the object in the meta section.
+   * \param kind The index into that subfield.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+/*! \brief A simple wrapper around a mapping from raw string names
+ * to a TVM variable, type variable or other binder type.
+ */
+template 
+struct Scope {
+  /*! \brief The internal map. */
+  std::unordered_map name_map;
+};
+
+/*! \brief A stack of scopes.
+ *
+ * In order to properly handle scoping we must maintain a scope of stacks.
+ *
+ * A stack allows users to write programs which contain repeated variable
+ * names and to properly handle both nested scopes and removal of variables
+ * when they go out of scope.
+ *
+ * This is the classic approach to lexical scoping.
+ */
+template 
+class ScopeStack {
+ private:
+  std::vector> scope_stack;
+
+ public:
+  /*! \brief Adds a variable binding to the current scope. */
+  void Add(const std::string& name, const T& value

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r451087346



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1384 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+/*! \brief A wrapper structure for capturing the result of parsing
+ * a global definition *before* we add it to the IRModule.
+ *
+ * This enables the parser to parse everything in one pass before
+ * constructing the IRModule.
+ */
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+/*! \brief A wrapper structure for capturing all top-level definitions
+ * when parsing a module.
+ */
+struct Definitions {
+  /*! \brief The set of global functions. */
+  std::vector funcs;
+  /*! \brief The set of type definitions. */
+  std::vector types;
+  // TODO(@jroesch): contain meta-table below
+};
+
+/*! \brief A structure representing the semantic versioning information
+ * for a Relay program.
+ */
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+/*! \brief A reference to a "meta-expression".
+ *
+ * In the text format we allow referencing metadata which
+ * uses a compact serialization that proceeds the main
+ * program body.
+ *
+ * We can reference this table using an expression of
+ * the form `meta[Type][index]`.
+ *
+ * We must later resolve these references to actual in-memory
+ * AST nodes but this requires first parsing the full program
+ * then expanding these temporary AST nodes into their corresponding
+ * nodes.
+ *
+ * For example the nth large constant will be pretty-printed as 
meta[relay.Constant][n]
+ * with its compact binary serialization residing in the metadata section at 
the end
+ * of the program.
+ */
+class MetaRefExprNode : public TempExprNode {
+ public:
+  /*! \brief The type key of the meta expression. */
+  std::string type_key;
+  /*! \brief The index into the type key's table. */
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  // TODO(@jroesch): we probably will need to manually
+  // expand these with a pass.
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor for MetaRefExpr
+   * \param type_key The type key of the object in the meta section.
+   * \param kind The index into that subfield.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+/*! \brief A simple wrapper around a mapping from raw string names
+ * to a TVM variable, type variable or other binder type.
+ */
+template 
+struct Scope {
+  /*! \brief The internal map. */
+  std::unordered_map name_map;
+};
+
+/*! \brief A stack of scopes.
+ *
+ * In order to properly handle scoping we must maintain a scope of stacks.
+ *
+ * A stack allows users to write programs which contain repeated variable
+ * names and to properly handle both nested scopes and removal of variables
+ * when they go out of scope.
+ *
+ * This is the classic approach to lexical scoping.
+ */
+template 
+class ScopeStack {
+ private:
+  std::vector> scope_stack;
+
+ public:
+  /*! \brief Adds a variable binding to the current scope. */
+  void Add(const std::string& name, const T& value

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r451086755



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1384 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+/*! \brief A wrapper structure for capturing the result of parsing
+ * a global definition *before* we add it to the IRModule.
+ *
+ * This enables the parser to parse everything in one pass before
+ * constructing the IRModule.
+ */
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+/*! \brief A wrapper structure for capturing all top-level definitions
+ * when parsing a module.
+ */
+struct Definitions {
+  /*! \brief The set of global functions. */
+  std::vector funcs;
+  /*! \brief The set of type definitions. */
+  std::vector types;
+  // TODO(@jroesch): contain meta-table below
+};
+
+/*! \brief A structure representing the semantic versioning information
+ * for a Relay program.
+ */
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+/*! \brief A reference to a "meta-expression".
+ *
+ * In the text format we allow referencing metadata which
+ * uses a compact serialization that proceeds the main
+ * program body.
+ *
+ * We can reference this table using an expression of
+ * the form `meta[Type][index]`.
+ *
+ * We must later resolve these references to actual in-memory
+ * AST nodes but this requires first parsing the full program
+ * then expanding these temporary AST nodes into their corresponding
+ * nodes.
+ *
+ * For example the nth large constant will be pretty-printed as 
meta[relay.Constant][n]
+ * with its compact binary serialization residing in the metadata section at 
the end
+ * of the program.
+ */
+class MetaRefExprNode : public TempExprNode {
+ public:
+  /*! \brief The type key of the meta expression. */
+  std::string type_key;
+  /*! \brief The index into the type key's table. */
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  // TODO(@jroesch): we probably will need to manually
+  // expand these with a pass.
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor for MetaRefExpr
+   * \param type_key The type key of the object in the meta section.
+   * \param kind The index into that subfield.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+/*! \brief A simple wrapper around a mapping from raw string names
+ * to a TVM variable, type variable or other binder type.
+ */
+template 
+struct Scope {
+  /*! \brief The internal map. */
+  std::unordered_map name_map;
+};
+
+/*! \brief A stack of scopes.
+ *
+ * In order to properly handle scoping we must maintain a scope of stacks.
+ *
+ * A stack allows users to write programs which contain repeated variable
+ * names and to properly handle both nested scopes and removal of variables
+ * when they go out of scope.
+ *
+ * This is the classic approach to lexical scoping.
+ */
+template 
+class ScopeStack {
+ private:
+  std::vector> scope_stack;
+
+ public:
+  /*! \brief Adds a variable binding to the current scope. */
+  void Add(const std::string& name, const T& value

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r451055189



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1384 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+/*! \brief A wrapper structure for capturing the result of parsing
+ * a global definition *before* we add it to the IRModule.
+ *
+ * This enables the parser to parse everything in one pass before
+ * constructing the IRModule.
+ */
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+/*! \brief A wrapper structure for capturing all top-level definitions
+ * when parsing a module.
+ */
+struct Definitions {
+  /*! \brief The set of global functions. */
+  std::vector funcs;
+  /*! \brief The set of type definitions. */
+  std::vector types;
+  // TODO(@jroesch): contain meta-table below
+};
+
+/*! \brief A structure representing the semantic versioning information
+ * for a Relay program.
+ */
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+/*! \brief A reference to a "meta-expression".
+ *
+ * In the text format we allow referencing metadata which
+ * uses a compact serialization that proceeds the main
+ * program body.
+ *
+ * We can reference this table using an expression of
+ * the form `meta[Type][index]`.
+ *
+ * We must later resolve these references to actual in-memory
+ * AST nodes but this requires first parsing the full program
+ * then expanding these temporary AST nodes into their corresponding
+ * nodes.
+ *
+ * For example the nth large constant will be pretty-printed as 
meta[relay.Constant][n]
+ * with its compact binary serialization residing in the metadata section at 
the end
+ * of the program.
+ */
+class MetaRefExprNode : public TempExprNode {
+ public:
+  /*! \brief The type key of the meta expression. */
+  std::string type_key;
+  /*! \brief The index into the type key's table. */
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  // TODO(@jroesch): we probably will need to manually
+  // expand these with a pass.
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor for MetaRefExpr
+   * \param type_key The type key of the object in the meta section.
+   * \param kind The index into that subfield.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+/*! \brief A simple wrapper around a mapping from raw string names
+ * to a TVM variable, type variable or other binder type.
+ */
+template 
+struct Scope {
+  /*! \brief The internal map. */
+  std::unordered_map name_map;
+};
+
+/*! \brief A stack of scopes.
+ *
+ * In order to properly handle scoping we must maintain a scope of stacks.
+ *
+ * A stack allows users to write programs which contain repeated variable
+ * names and to properly handle both nested scopes and removal of variables
+ * when they go out of scope.
+ *
+ * This is the classic approach to lexical scoping.
+ */
+template 
+class ScopeStack {
+ private:
+  std::vector> scope_stack;
+
+ public:
+  /*! \brief Adds a variable binding to the current scope. */
+  void Add(const std::string& name, const T& value

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r451054661



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1384 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+/*! \brief A wrapper structure for capturing the result of parsing
+ * a global definition *before* we add it to the IRModule.
+ *
+ * This enables the parser to parse everything in one pass before
+ * constructing the IRModule.
+ */
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+/*! \brief A wrapper structure for capturing all top-level definitions
+ * when parsing a module.
+ */
+struct Definitions {
+  /*! \brief The set of global functions. */
+  std::vector funcs;
+  /*! \brief The set of type definitions. */
+  std::vector types;
+  // TODO(@jroesch): contain meta-table below
+};
+
+/*! \brief A structure representing the semantic versioning information
+ * for a Relay program.
+ */
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+/*! \brief A reference to a "meta-expression".
+ *
+ * In the text format we allow referencing metadata which
+ * uses a compact serialization that proceeds the main
+ * program body.
+ *
+ * We can reference this table using an expression of
+ * the form `meta[Type][index]`.
+ *
+ * We must later resolve these references to actual in-memory
+ * AST nodes but this requires first parsing the full program
+ * then expanding these temporary AST nodes into their corresponding
+ * nodes.
+ *
+ * For example the nth large constant will be pretty-printed as 
meta[relay.Constant][n]
+ * with its compact binary serialization residing in the metadata section at 
the end
+ * of the program.
+ */
+class MetaRefExprNode : public TempExprNode {
+ public:
+  /*! \brief The type key of the meta expression. */
+  std::string type_key;
+  /*! \brief The index into the type key's table. */
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  // TODO(@jroesch): we probably will need to manually
+  // expand these with a pass.
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor for MetaRefExpr
+   * \param type_key The type key of the object in the meta section.
+   * \param kind The index into that subfield.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+/*! \brief A simple wrapper around a mapping from raw string names
+ * to a TVM variable, type variable or other binder type.
+ */
+template 
+struct Scope {
+  /*! \brief The internal map. */
+  std::unordered_map name_map;
+};
+
+/*! \brief A stack of scopes.
+ *
+ * In order to properly handle scoping we must maintain a scope of stacks.
+ *
+ * A stack allows users to write programs which contain repeated variable
+ * names and to properly handle both nested scopes and removal of variables
+ * when they go out of scope.
+ *
+ * This is the classic approach to lexical scoping.
+ */
+template 
+class ScopeStack {
+ private:
+  std::vector> scope_stack;
+
+ public:
+  /*! \brief Adds a variable binding to the current scope. */
+  void Add(const std::string& name, const T& value

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r451054166



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1384 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+/*! \brief A wrapper structure for capturing the result of parsing
+ * a global definition *before* we add it to the IRModule.
+ *
+ * This enables the parser to parse everything in one pass before
+ * constructing the IRModule.
+ */
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+/*! \brief A wrapper structure for capturing all top-level definitions
+ * when parsing a module.
+ */
+struct Definitions {
+  /*! \brief The set of global functions. */
+  std::vector funcs;
+  /*! \brief The set of type definitions. */
+  std::vector types;
+  // TODO(@jroesch): contain meta-table below
+};
+
+/*! \brief A structure representing the semantic versioning information
+ * for a Relay program.
+ */
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+/*! \brief A reference to a "meta-expression".
+ *
+ * In the text format we allow referencing metadata which
+ * uses a compact serialization that proceeds the main
+ * program body.
+ *
+ * We can reference this table using an expression of
+ * the form `meta[Type][index]`.
+ *
+ * We must later resolve these references to actual in-memory
+ * AST nodes but this requires first parsing the full program
+ * then expanding these temporary AST nodes into their corresponding
+ * nodes.
+ *
+ * For example the nth large constant will be pretty-printed as 
meta[relay.Constant][n]
+ * with its compact binary serialization residing in the metadata section at 
the end
+ * of the program.
+ */
+class MetaRefExprNode : public TempExprNode {
+ public:
+  /*! \brief The type key of the meta expression. */
+  std::string type_key;
+  /*! \brief The index into the type key's table. */
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  // TODO(@jroesch): we probably will need to manually
+  // expand these with a pass.
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor for MetaRefExpr
+   * \param type_key The type key of the object in the meta section.
+   * \param kind The index into that subfield.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+/*! \brief A simple wrapper around a mapping from raw string names
+ * to a TVM variable, type variable or other binder type.
+ */
+template 
+struct Scope {
+  /*! \brief The internal map. */
+  std::unordered_map name_map;
+};
+
+/*! \brief A stack of scopes.
+ *
+ * In order to properly handle scoping we must maintain a scope of stacks.
+ *
+ * A stack allows users to write programs which contain repeated variable
+ * names and to properly handle both nested scopes and removal of variables
+ * when they go out of scope.
+ *
+ * This is the classic approach to lexical scoping.
+ */
+template 
+class ScopeStack {
+ private:
+  std::vector> scope_stack;
+
+ public:
+  /*! \brief Adds a variable binding to the current scope. */
+  void Add(const std::string& name, const T& value

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r450743817



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1103 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+// adtConsDefnList: adtConsDefn (',' adtConsDefn)* ','? ;
+// adtConsDefn: constructorName ('(' typeExpr (',' typeExpr)* ')')? ;
+// matchClauseList: matchClause (',' matchClause)* ','? ;
+// matchClause: pattern '=>' ('{' expr '}' | expr) ;
+// // complete or incomplete match, respectively
+// matchType : 'match' | 'match?' ;
+
+// patternList: '(' pattern (',' pattern)* ')';
+// pattern
+//   : '_' # wildcardPattern
+//   | localVar (':' typeExpr)?# varPattern
+//   | constructorName patternList?# constructorPattern
+//   | patternList # tuplePattern
+//   ;
+
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+struct Definitions {
+  std::vector funcs;
+  std::vector types;
+};
+
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+class MetaRefExpr;
+class MetaRefExprNode : public TempExprNode {
+ public:
+  std::string type_key;
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor
+   * \param expr The original relay expression.
+   * \param kind The annotation kind.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template
+struct Scope {
+  std::unordered_map name_map;
+  Scope() : name_map() {}
+};
+
+template
+struct ScopeStack {
+  std::vector> scope_stack;
+
+  void Add(const std::string& name, const T& value) {
+if (!this->scope_stack.size()) {
+  LOG(FATAL) << "internal issue";
+}
+this->scope_stack.back().name_map.insert({ name, value });
+  }
+
+  T Lookup(const std::string& name) {
+for (auto scope = this->scope_stack.rbegin(); scope != 
this->scope_stack.rend(); scope++) {
+  auto it = scope->name_map.find(name);
+  if (it != scope->name_map.end()) {
+return it->second;
+  }
+}
+return T();
+  }
+
+  void PushStack() {
+this->scope_stack.push_back(Scope());
+  }
+
+  void PopStack() {
+this->scope_stack.pop_back();
+  }
+};
+
+template
+struct InternTable {
+  std::unordered_map table;
+  void Add(const std::string& name, const T& t) {
+auto it = table.find(name);
+if (it != table.end()) {
+  LOG(FATAL) << "duplicate name";
+} else {
+  table.insert({ name, t});
+}
+  }
+
+  T Get(const std::string& name) {
+auto it = table.find(name);
+if (it != table.end()) {
+  return it->second;
+} else {
+  return T();
+}
+  }
+};
+
+struct Parser {
+  /*! \brief The diagnostic context used for error reporting. */
+  DiagnosticContext diag_ctx;
+
+  /*! \brief The current position in the token stream. */
+  int pos;
+
+  /*! \brief The token stream for the parser. */
+  std::vector tokens;
+
+  /*! \brief The configured operator table. */
+  OperatorTable op_table;
+
+  /*! \brief Configure the whitespace mode, right now we ignore all 
whitespace. 

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-07 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r450743403



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1103 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+// adtConsDefnList: adtConsDefn (',' adtConsDefn)* ','? ;
+// adtConsDefn: constructorName ('(' typeExpr (',' typeExpr)* ')')? ;
+// matchClauseList: matchClause (',' matchClause)* ','? ;
+// matchClause: pattern '=>' ('{' expr '}' | expr) ;
+// // complete or incomplete match, respectively
+// matchType : 'match' | 'match?' ;
+
+// patternList: '(' pattern (',' pattern)* ')';
+// pattern
+//   : '_' # wildcardPattern
+//   | localVar (':' typeExpr)?# varPattern
+//   | constructorName patternList?# constructorPattern
+//   | patternList # tuplePattern
+//   ;
+
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+struct Definitions {
+  std::vector funcs;
+  std::vector types;
+};
+
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+class MetaRefExpr;
+class MetaRefExprNode : public TempExprNode {
+ public:
+  std::string type_key;
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor
+   * \param expr The original relay expression.
+   * \param kind The annotation kind.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template
+struct Scope {
+  std::unordered_map name_map;
+  Scope() : name_map() {}
+};
+
+template
+struct ScopeStack {
+  std::vector> scope_stack;
+
+  void Add(const std::string& name, const T& value) {
+if (!this->scope_stack.size()) {
+  LOG(FATAL) << "internal issue";
+}
+this->scope_stack.back().name_map.insert({ name, value });
+  }
+
+  T Lookup(const std::string& name) {
+for (auto scope = this->scope_stack.rbegin(); scope != 
this->scope_stack.rend(); scope++) {
+  auto it = scope->name_map.find(name);
+  if (it != scope->name_map.end()) {
+return it->second;
+  }
+}
+return T();
+  }
+
+  void PushStack() {
+this->scope_stack.push_back(Scope());
+  }
+
+  void PopStack() {
+this->scope_stack.pop_back();
+  }
+};
+
+template
+struct InternTable {
+  std::unordered_map table;
+  void Add(const std::string& name, const T& t) {
+auto it = table.find(name);
+if (it != table.end()) {
+  LOG(FATAL) << "duplicate name";
+} else {
+  table.insert({ name, t});
+}
+  }
+
+  T Get(const std::string& name) {
+auto it = table.find(name);
+if (it != table.end()) {
+  return it->second;
+} else {
+  return T();
+}
+  }
+};
+
+struct Parser {
+  /*! \brief The diagnostic context used for error reporting. */
+  DiagnosticContext diag_ctx;
+
+  /*! \brief The current position in the token stream. */
+  int pos;
+
+  /*! \brief The token stream for the parser. */
+  std::vector tokens;
+
+  /*! \brief The configured operator table. */
+  OperatorTable op_table;
+
+  /*! \brief Configure the whitespace mode, right now we ignore all 
whitespace. 

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-01 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r448252018



##
File path: src/parser/tokenizer.h
##
@@ -0,0 +1,460 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.h
+ * \brief A parser for TVM IR.
+ */
+#ifndef TVM_PARSER_TOKENIZER_H_
+#define TVM_PARSER_TOKENIZER_H_
+
+#include 
+#include 
+#include 
+
+#include "./token.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace runtime;
+
+bool IsDigit(char c) {
+return '0' <= c && c <= '9';
+}
+
+bool IsWhitespace(char c) {
+return ' ' == c || c == '\t' || c == '\n';
+}
+
+bool IsNumeric(char c) {
+return (IsDigit(c) || c == '.' || c == 'e' || c == '-' || c == '+' || c == 
'E') && !IsWhitespace(c);
+}
+
+bool IsIdentLetter(char c) {
+return '_' == c || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
+}
+
+bool IsIdent(char c) {
+return IsIdentLetter(c) || IsDigit(c);
+}
+
+static std::unordered_map KEYWORD_TABLE = {
+{ "let", TokenType::Let },
+{ "fn", TokenType::Fn },
+{ "def", TokenType::Defn },
+{ "if", TokenType::If },
+{ "else", TokenType::Else },
+{ "type", TokenType::TypeDef },
+{ "match", TokenType::Match }
+};
+
+struct Tokenizer {
+int pos;
+int col;
+int line;
+char next_char;
+const std::string& source;
+std::vector tokens;
+
+char Next() {
+char c = this->source.at(this->pos);
+if (c == '\n') {
+this->line += 1;
+this->col = 1;
+} else {
+this->col += 1;
+}
+pos += 1;
+return c;
+}
+
+bool More() {
+return this->pos < this->source.size();
+}
+
+char Peek() {
+CHECK(pos < this->source.size());
+return this->source.at(this->pos);
+}
+
+Token NewToken(TokenType token_type, ObjectRef data = ObjectRef()) {
+return Token(this->line, this->col, token_type, data);
+}
+
+enum CommentParserState {
+Proceed,
+Forward,
+Backward,
+};
+
+void MatchComment(std::string& buffer) {
+// We only invoke this after we have matched the first start
+// token assume, we are proceeding the parse forward with
+// nesting = 1.
+//
+// When we are done we should be at nesting zero and be
+// in the stop state.
+CommentParserState state = CommentParserState::Proceed;
+int nesting = 1;
+
+while (true) {
+switch (state) {
+case CommentParserState::Proceed: {
+if (Peek() == '/') {
+state = CommentParserState::Forward;
+} else if (Peek() == '*') {
+state = CommentParserState::Backward;
+}
+buffer += Next();
+continue;
+}
+case CommentParserState::Forward: {
+if (Peek() == '*') {
+nesting += 1;
+buffer += Next();
+}
+state = CommentParserState::Proceed;
+continue;
+}
+case CommentParserState::Backward: {
+if (Peek() == '/') {
+nesting -= 1;
+if (nesting == 0) {
+Next();
+buffer.pop_back();
+return;
+} else {
+buffer += Next();
+state = CommentParserState::Proceed;
+};
+}
+continue;
+}
+}
+}
+}
+
+Token ParseNumber(bool is_pos, std::string number) {
+CHECK(number.size() > 0)
+<< "an empty string is an invalid number";
+
+try {
+auto token = NewToken(TokenType::Integer);
+size_t index = 0;
+int value = std::stoi(number, &index);
+if (number.size() > index) {
+throw std::invalid_argument(

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-01 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r448250952



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1103 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+// adtConsDefnList: adtConsDefn (',' adtConsDefn)* ','? ;
+// adtConsDefn: constructorName ('(' typeExpr (',' typeExpr)* ')')? ;
+// matchClauseList: matchClause (',' matchClause)* ','? ;
+// matchClause: pattern '=>' ('{' expr '}' | expr) ;
+// // complete or incomplete match, respectively
+// matchType : 'match' | 'match?' ;
+
+// patternList: '(' pattern (',' pattern)* ')';
+// pattern
+//   : '_' # wildcardPattern
+//   | localVar (':' typeExpr)?# varPattern
+//   | constructorName patternList?# constructorPattern
+//   | patternList # tuplePattern
+//   ;
+
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+struct Definitions {
+  std::vector funcs;
+  std::vector types;
+};
+
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+class MetaRefExpr;
+class MetaRefExprNode : public TempExprNode {
+ public:
+  std::string type_key;
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor
+   * \param expr The original relay expression.
+   * \param kind The annotation kind.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template
+struct Scope {
+  std::unordered_map name_map;
+  Scope() : name_map() {}
+};
+
+template
+struct ScopeStack {
+  std::vector> scope_stack;
+
+  void Add(const std::string& name, const T& value) {
+if (!this->scope_stack.size()) {
+  LOG(FATAL) << "internal issue";
+}
+this->scope_stack.back().name_map.insert({ name, value });
+  }
+
+  T Lookup(const std::string& name) {
+for (auto scope = this->scope_stack.rbegin(); scope != 
this->scope_stack.rend(); scope++) {
+  auto it = scope->name_map.find(name);
+  if (it != scope->name_map.end()) {
+return it->second;
+  }
+}
+return T();
+  }
+
+  void PushStack() {
+this->scope_stack.push_back(Scope());
+  }
+
+  void PopStack() {
+this->scope_stack.pop_back();
+  }
+};
+
+template
+struct InternTable {
+  std::unordered_map table;
+  void Add(const std::string& name, const T& t) {
+auto it = table.find(name);
+if (it != table.end()) {
+  LOG(FATAL) << "duplicate name";
+} else {
+  table.insert({ name, t});
+}
+  }
+
+  T Get(const std::string& name) {
+auto it = table.find(name);
+if (it != table.end()) {
+  return it->second;
+} else {
+  return T();
+}
+  }
+};
+
+struct Parser {
+  /*! \brief The diagnostic context used for error reporting. */
+  DiagnosticContext diag_ctx;
+
+  /*! \brief The current position in the token stream. */
+  int pos;
+
+  /*! \brief The token stream for the parser. */
+  std::vector tokens;
+
+  /*! \brief The configured operator table. */
+  OperatorTable op_table;
+
+  /*! \brief Configure the whitespace mode, right now we ignore all 
whitespace. 

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-01 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r448249840



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1103 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+// adtConsDefnList: adtConsDefn (',' adtConsDefn)* ','? ;
+// adtConsDefn: constructorName ('(' typeExpr (',' typeExpr)* ')')? ;
+// matchClauseList: matchClause (',' matchClause)* ','? ;
+// matchClause: pattern '=>' ('{' expr '}' | expr) ;
+// // complete or incomplete match, respectively
+// matchType : 'match' | 'match?' ;
+
+// patternList: '(' pattern (',' pattern)* ')';
+// pattern
+//   : '_' # wildcardPattern
+//   | localVar (':' typeExpr)?# varPattern
+//   | constructorName patternList?# constructorPattern
+//   | patternList # tuplePattern
+//   ;
+
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+struct Definitions {
+  std::vector funcs;
+  std::vector types;
+};
+
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+class MetaRefExpr;
+class MetaRefExprNode : public TempExprNode {
+ public:
+  std::string type_key;
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor
+   * \param expr The original relay expression.
+   * \param kind The annotation kind.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template
+struct Scope {
+  std::unordered_map name_map;
+  Scope() : name_map() {}
+};
+
+template
+struct ScopeStack {
+  std::vector> scope_stack;
+
+  void Add(const std::string& name, const T& value) {
+if (!this->scope_stack.size()) {
+  LOG(FATAL) << "internal issue";
+}
+this->scope_stack.back().name_map.insert({ name, value });
+  }
+
+  T Lookup(const std::string& name) {
+for (auto scope = this->scope_stack.rbegin(); scope != 
this->scope_stack.rend(); scope++) {
+  auto it = scope->name_map.find(name);
+  if (it != scope->name_map.end()) {
+return it->second;
+  }
+}
+return T();
+  }
+
+  void PushStack() {
+this->scope_stack.push_back(Scope());
+  }
+
+  void PopStack() {
+this->scope_stack.pop_back();
+  }
+};
+
+template
+struct InternTable {
+  std::unordered_map table;
+  void Add(const std::string& name, const T& t) {
+auto it = table.find(name);
+if (it != table.end()) {
+  LOG(FATAL) << "duplicate name";
+} else {
+  table.insert({ name, t});
+}
+  }
+
+  T Get(const std::string& name) {
+auto it = table.find(name);
+if (it != table.end()) {
+  return it->second;
+} else {
+  return T();
+}
+  }
+};
+
+struct Parser {
+  /*! \brief The diagnostic context used for error reporting. */
+  DiagnosticContext diag_ctx;
+
+  /*! \brief The current position in the token stream. */
+  int pos;
+
+  /*! \brief The token stream for the parser. */
+  std::vector tokens;
+
+  /*! \brief The configured operator table. */
+  OperatorTable op_table;
+
+  /*! \brief Configure the whitespace mode, right now we ignore all 
whitespace. 

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-01 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r448250340



##
File path: src/parser/tokenizer.h
##
@@ -0,0 +1,460 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.h
+ * \brief A parser for TVM IR.
+ */
+#ifndef TVM_PARSER_TOKENIZER_H_
+#define TVM_PARSER_TOKENIZER_H_
+
+#include 
+#include 
+#include 
+
+#include "./token.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace runtime;
+
+bool IsDigit(char c) {
+return '0' <= c && c <= '9';
+}
+
+bool IsWhitespace(char c) {
+return ' ' == c || c == '\t' || c == '\n';
+}
+
+bool IsNumeric(char c) {
+return (IsDigit(c) || c == '.' || c == 'e' || c == '-' || c == '+' || c == 
'E') && !IsWhitespace(c);
+}
+
+bool IsIdentLetter(char c) {
+return '_' == c || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
+}
+
+bool IsIdent(char c) {
+return IsIdentLetter(c) || IsDigit(c);
+}
+
+static std::unordered_map KEYWORD_TABLE = {
+{ "let", TokenType::Let },
+{ "fn", TokenType::Fn },
+{ "def", TokenType::Defn },
+{ "if", TokenType::If },
+{ "else", TokenType::Else },
+{ "type", TokenType::TypeDef },
+{ "match", TokenType::Match }
+};
+
+struct Tokenizer {
+int pos;
+int col;
+int line;
+char next_char;
+const std::string& source;
+std::vector tokens;
+
+char Next() {
+char c = this->source.at(this->pos);
+if (c == '\n') {
+this->line += 1;
+this->col = 1;
+} else {
+this->col += 1;
+}
+pos += 1;
+return c;
+}
+
+bool More() {
+return this->pos < this->source.size();
+}
+
+char Peek() {
+CHECK(pos < this->source.size());
+return this->source.at(this->pos);
+}
+
+Token NewToken(TokenType token_type, ObjectRef data = ObjectRef()) {
+return Token(this->line, this->col, token_type, data);
+}
+
+enum CommentParserState {
+Proceed,
+Forward,
+Backward,
+};
+
+void MatchComment(std::string& buffer) {
+// We only invoke this after we have matched the first start
+// token assume, we are proceeding the parse forward with
+// nesting = 1.
+//
+// When we are done we should be at nesting zero and be
+// in the stop state.
+CommentParserState state = CommentParserState::Proceed;
+int nesting = 1;
+
+while (true) {
+switch (state) {
+case CommentParserState::Proceed: {
+if (Peek() == '/') {
+state = CommentParserState::Forward;
+} else if (Peek() == '*') {
+state = CommentParserState::Backward;
+}
+buffer += Next();
+continue;
+}
+case CommentParserState::Forward: {
+if (Peek() == '*') {
+nesting += 1;
+buffer += Next();
+}
+state = CommentParserState::Proceed;
+continue;
+}
+case CommentParserState::Backward: {
+if (Peek() == '/') {
+nesting -= 1;
+if (nesting == 0) {
+Next();
+buffer.pop_back();
+return;
+} else {
+buffer += Next();
+state = CommentParserState::Proceed;
+};
+}
+continue;
+}
+}
+}
+}
+
+Token ParseNumber(bool is_pos, std::string number) {
+CHECK(number.size() > 0)
+<< "an empty string is an invalid number";
+
+try {
+auto token = NewToken(TokenType::Integer);
+size_t index = 0;
+int value = std::stoi(number, &index);
+if (number.size() > index) {
+throw std::invalid_argument(

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-01 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r448250021



##
File path: tests/python/relay/test_ir_parser.py
##
@@ -76,6 +76,7 @@ def graph_equal(lhs, rhs):
 
 def roundtrip(expr):
 x = relay.fromtext(expr.astext())
+import pdb; pdb.set_trace()

Review comment:
   more debugging for last failing test case will remove when I'm done
   





This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org




[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-01 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r448249240



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1103 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+// adtConsDefnList: adtConsDefn (',' adtConsDefn)* ','? ;
+// adtConsDefn: constructorName ('(' typeExpr (',' typeExpr)* ')')? ;
+// matchClauseList: matchClause (',' matchClause)* ','? ;
+// matchClause: pattern '=>' ('{' expr '}' | expr) ;
+// // complete or incomplete match, respectively
+// matchType : 'match' | 'match?' ;
+
+// patternList: '(' pattern (',' pattern)* ')';
+// pattern
+//   : '_' # wildcardPattern
+//   | localVar (':' typeExpr)?# varPattern
+//   | constructorName patternList?# constructorPattern
+//   | patternList # tuplePattern
+//   ;
+
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+struct Definitions {
+  std::vector funcs;
+  std::vector types;
+};
+
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+class MetaRefExpr;
+class MetaRefExprNode : public TempExprNode {
+ public:
+  std::string type_key;
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor
+   * \param expr The original relay expression.
+   * \param kind The annotation kind.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template
+struct Scope {
+  std::unordered_map name_map;
+  Scope() : name_map() {}
+};
+
+template
+struct ScopeStack {
+  std::vector> scope_stack;
+
+  void Add(const std::string& name, const T& value) {
+if (!this->scope_stack.size()) {
+  LOG(FATAL) << "internal issue";
+}
+this->scope_stack.back().name_map.insert({ name, value });
+  }
+
+  T Lookup(const std::string& name) {
+for (auto scope = this->scope_stack.rbegin(); scope != 
this->scope_stack.rend(); scope++) {
+  auto it = scope->name_map.find(name);
+  if (it != scope->name_map.end()) {
+return it->second;
+  }
+}
+return T();
+  }
+
+  void PushStack() {
+this->scope_stack.push_back(Scope());
+  }
+
+  void PopStack() {
+this->scope_stack.pop_back();
+  }
+};
+
+template
+struct InternTable {
+  std::unordered_map table;
+  void Add(const std::string& name, const T& t) {
+auto it = table.find(name);
+if (it != table.end()) {
+  LOG(FATAL) << "duplicate name";
+} else {
+  table.insert({ name, t});
+}
+  }
+
+  T Get(const std::string& name) {
+auto it = table.find(name);
+if (it != table.end()) {
+  return it->second;
+} else {
+  return T();
+}
+  }
+};
+
+struct Parser {
+  /*! \brief The diagnostic context used for error reporting. */
+  DiagnosticContext diag_ctx;
+
+  /*! \brief The current position in the token stream. */
+  int pos;
+
+  /*! \brief The token stream for the parser. */
+  std::vector tokens;
+
+  /*! \brief The configured operator table. */
+  OperatorTable op_table;
+
+  /*! \brief Configure the whitespace mode, right now we ignore all 
whitespace. 

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-01 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r448248019



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1103 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+// adtConsDefnList: adtConsDefn (',' adtConsDefn)* ','? ;
+// adtConsDefn: constructorName ('(' typeExpr (',' typeExpr)* ')')? ;
+// matchClauseList: matchClause (',' matchClause)* ','? ;
+// matchClause: pattern '=>' ('{' expr '}' | expr) ;
+// // complete or incomplete match, respectively
+// matchType : 'match' | 'match?' ;
+
+// patternList: '(' pattern (',' pattern)* ')';
+// pattern
+//   : '_' # wildcardPattern
+//   | localVar (':' typeExpr)?# varPattern
+//   | constructorName patternList?# constructorPattern
+//   | patternList # tuplePattern
+//   ;
+
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+struct Definitions {
+  std::vector funcs;
+  std::vector types;
+};
+
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+class MetaRefExpr;
+class MetaRefExprNode : public TempExprNode {
+ public:
+  std::string type_key;
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor
+   * \param expr The original relay expression.
+   * \param kind The annotation kind.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template
+struct Scope {
+  std::unordered_map name_map;
+  Scope() : name_map() {}
+};
+
+template
+struct ScopeStack {
+  std::vector> scope_stack;
+
+  void Add(const std::string& name, const T& value) {
+if (!this->scope_stack.size()) {
+  LOG(FATAL) << "internal issue";
+}
+this->scope_stack.back().name_map.insert({ name, value });
+  }
+
+  T Lookup(const std::string& name) {
+for (auto scope = this->scope_stack.rbegin(); scope != 
this->scope_stack.rend(); scope++) {
+  auto it = scope->name_map.find(name);
+  if (it != scope->name_map.end()) {
+return it->second;
+  }
+}
+return T();
+  }
+
+  void PushStack() {
+this->scope_stack.push_back(Scope());
+  }
+
+  void PopStack() {
+this->scope_stack.pop_back();
+  }
+};
+
+template
+struct InternTable {
+  std::unordered_map table;
+  void Add(const std::string& name, const T& t) {
+auto it = table.find(name);
+if (it != table.end()) {
+  LOG(FATAL) << "duplicate name";
+} else {
+  table.insert({ name, t});
+}
+  }
+
+  T Get(const std::string& name) {
+auto it = table.find(name);
+if (it != table.end()) {
+  return it->second;
+} else {
+  return T();
+}
+  }
+};
+

Review comment:
   I added a preamble to the class, the code below has *a lot* of comments 
esp. compared to the rest of TVM. I explained the high level bits but 
unfortunately to really understand the parser one will probably need to read 
the parsing code. 





This is an automated message from the Apache Git Service.
To respond to the message, plea

[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-01 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r448220277



##
File path: src/parser/op_table.h
##
@@ -0,0 +1,93 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file token.h
+ * \brief A operator table for parsing.
+ *
+ * Provides symbolic token sequences to map to TVM operators, with a given 
associativity and arity.
+ */
+
+#ifndef TVM_PARSER_OP_TABLE_H_
+#define TVM_PARSER_OP_TABLE_H_
+
+#include 
+#include 
+#include 
+#include 
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+
+struct Rule {
+  std::vector tokens;
+  int precedence;
+  int arity;
+  tvm::Op op;
+  bool left_assoc;
+
+  Rule() : tokens(), precedence(0), arity(0 ), op(tvm::Op()), 
left_assoc(false) {}
+
+  Rule(std::vector tokens, tvm::Op op, int precedence, int arity = 
2, bool left_assoc = false)
+  : tokens(tokens), precedence(precedence), arity(arity), op(op), 
left_assoc(false) {}
+
+  Rule(const Rule& rule) {
+this->tokens = rule.tokens;
+this->op = rule.op;
+this->precedence = rule.precedence;
+this->arity = rule.arity;
+this->left_assoc = rule.left_assoc;
+  }
+};
+
+struct OperatorTable {
+  std::vector rules;
+  std::unordered_map this_is_a_hack;

Review comment:
   This was to codify that I need a better solution here, ideally I need 
some kind of `std::trie` but I don't really want to implement a prefix tree for 
this relatively simple use case. 





This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org




[GitHub] [incubator-tvm] jroesch commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0

2020-07-01 Thread GitBox


jroesch commented on a change in pull request #5932:
URL: https://github.com/apache/incubator-tvm/pull/5932#discussion_r448218064



##
File path: src/parser/parser.cc
##
@@ -0,0 +1,1103 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file parser.cc
+ * \brief A parser for TVM IR.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "./diagnostic.h"
+#include "./op_table.h"
+#include "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+// adtConsDefnList: adtConsDefn (',' adtConsDefn)* ','? ;
+// adtConsDefn: constructorName ('(' typeExpr (',' typeExpr)* ')')? ;
+// matchClauseList: matchClause (',' matchClause)* ','? ;
+// matchClause: pattern '=>' ('{' expr '}' | expr) ;
+// // complete or incomplete match, respectively
+// matchType : 'match' | 'match?' ;
+
+// patternList: '(' pattern (',' pattern)* ')';
+// pattern
+//   : '_' # wildcardPattern
+//   | localVar (':' typeExpr)?# varPattern
+//   | constructorName patternList?# constructorPattern
+//   | patternList # tuplePattern
+//   ;
+
+struct GlobalFunc {
+  GlobalVar global;
+  Function function;
+  GlobalFunc() : global(), function() {}
+  GlobalFunc(GlobalVar global, Function function) : global(global), 
function(function) {}
+  GlobalFunc(const GlobalFunc& gfunc) {
+this->global = gfunc.global;
+this->function = gfunc.function;
+  }
+};
+
+struct Definitions {
+  std::vector funcs;
+  std::vector types;
+};
+
+struct SemVer {
+  int major;
+  int minor;
+  int patch;
+};
+
+class MetaRefExpr;
+class MetaRefExprNode : public TempExprNode {
+ public:
+  std::string type_key;
+  uint64_t node_index;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {}
+
+  Expr Realize() const final { return Expr(); }
+
+  static constexpr const char* _type_key = "relay.MetaRefExpr";
+  TVM_DECLARE_FINAL_OBJECT_INFO(MetaRefExprNode, TempExprNode);
+};
+
+class MetaRefExpr : public TempExpr {
+ public:
+  /*!
+   * \brief The constructor
+   * \param expr The original relay expression.
+   * \param kind The annotation kind.
+   */
+  TVM_DLL MetaRefExpr(std::string type_key, uint64_t node_index);
+
+  TVM_DEFINE_OBJECT_REF_METHODS(MetaRefExpr, TempExpr, MetaRefExprNode);
+};
+
+MetaRefExpr::MetaRefExpr(std::string type_key, uint64_t node_index) {
+  auto rnode = make_object();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template
+struct Scope {
+  std::unordered_map name_map;
+  Scope() : name_map() {}
+};
+
+template
+struct ScopeStack {
+  std::vector> scope_stack;
+
+  void Add(const std::string& name, const T& value) {
+if (!this->scope_stack.size()) {
+  LOG(FATAL) << "internal issue";
+}
+this->scope_stack.back().name_map.insert({ name, value });
+  }
+
+  T Lookup(const std::string& name) {
+for (auto scope = this->scope_stack.rbegin(); scope != 
this->scope_stack.rend(); scope++) {
+  auto it = scope->name_map.find(name);
+  if (it != scope->name_map.end()) {
+return it->second;
+  }
+}
+return T();
+  }
+
+  void PushStack() {
+this->scope_stack.push_back(Scope());
+  }
+
+  void PopStack() {
+this->scope_stack.pop_back();
+  }
+};
+
+template
+struct InternTable {
+  std::unordered_map table;
+  void Add(const std::string& name, const T& t) {
+auto it = table.find(name);
+if (it != table.end()) {
+  LOG(FATAL) << "duplicate name";
+} else {
+  table.insert({ name, t});
+}
+  }
+
+  T Get(const std::string& name) {
+auto it = table.find(name);
+if (it != table.end()) {
+  return it->second;
+} else {
+  return T();
+}
+  }
+};
+
+struct Parser {
+  /*! \brief The diagnostic context used for error reporting. */
+  DiagnosticContext diag_ctx;
+
+  /*! \brief The current position in the token stream. */
+  int pos;
+
+  /*! \brief The token stream for the parser. */
+  std::vector tokens;
+
+  /*! \brief The configured operator table. */
+  OperatorTable op_table;
+
+  /*! \brief Configure the whitespace mode, right now we ignore all 
whitespace.