tvm-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From GitBox <...@apache.org>
Subject [GitHub] [incubator-tvm] electriclilies commented on a change in pull request #5932: [Frontend][Relay] Add Parser 2.0
Date Wed, 01 Jul 2020 01:14:42 GMT

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



##########
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 <fstream>
+#include <tvm/runtime/object.h>
+#include <tvm/runtime/container.h>
+
+#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<std::string, TokenType> 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<Token> 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("floating point");
+            }
+            value = is_pos ? value : -value;
+            token->data = tvm::Integer(value);
+            return token;
+        } catch (const std::invalid_argument& ia) {
+            auto token = NewToken(TokenType::Float);
+
+            if (number.back() == 'f') {
+                number.pop_back();
+            }
+
+            double value = stod(number);
+            value = is_pos ? value : -value;
+            token->data = tvm::FloatImm(DataType::Float(64), value);
+            return token;
+        }
+    }
+
+    inline Token TokenizeOnce() {
+        auto next = Peek();
+        if (next == '\n') {
+            auto token = NewToken(TokenType::Newline);
+            Next();
+            return token;
+        } else if (this->Peek() == '\r' && this->Peek() == '\n') {

Review comment:
       This is weird to me -- why are you getting this->Peek() when you already put it
in next? Also, a character can't be '/r' and '/n' at the same time so it's dead code

##########
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 <tvm/ir/module.h>
+#include <tvm/relay/expr.h>
+#include <tvm/relay/function.h>
+#include <tvm/runtime/object.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/node/reflection.h>
+
+#include <fstream>
+
+#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<GlobalFunc> funcs;
+  std::vector<TypeData> 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<MetaRefExprNode>();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template<typename T>
+struct Scope {
+  std::unordered_map<std::string, T> name_map;
+  Scope() : name_map() {}
+};
+
+template<typename T>
+struct ScopeStack {
+  std::vector<Scope<T>> 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<T>());
+  }
+
+  void PopStack() {
+    this->scope_stack.pop_back();
+  }
+};
+
+template<typename T>
+struct InternTable {
+  std::unordered_map<std::string, T> 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:
       More doc in this file would be helpful in general, I'm having trouble seeing how all
the classes fit together

##########
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 <tvm/ir/module.h>
+#include <tvm/relay/expr.h>
+#include <tvm/relay/function.h>
+#include <tvm/runtime/object.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/node/reflection.h>
+
+#include <fstream>
+
+#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<GlobalFunc> funcs;
+  std::vector<TypeData> 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<MetaRefExprNode>();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template<typename T>
+struct Scope {
+  std::unordered_map<std::string, T> name_map;
+  Scope() : name_map() {}
+};
+
+template<typename T>
+struct ScopeStack {
+  std::vector<Scope<T>> 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<T>());
+  }
+
+  void PopStack() {
+    this->scope_stack.pop_back();
+  }
+};
+
+template<typename T>
+struct InternTable {
+  std::unordered_map<std::string, T> 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<Token> tokens;
+
+  /*! \brief The configured operator table. */
+  OperatorTable op_table;
+
+  /*! \brief Configure the whitespace mode, right now we ignore all whitespace. */
+  bool ignore_whitespace;
+
+  /*! \brief A global mapping for GlobalVar. */
+  InternTable<GlobalVar> global_names;
+
+  /*! \brief A global mapping for type definitions. */
+  InternTable<GlobalTypeVar> type_names;
+
+  /*! \brief A mapping from graph variable to expression, i.e., `%0 = expr`. */
+  std::unordered_map<int, Expr> graph_ctx;
+
+  /*! \brief The set of type scopes used for generics. */
+  ScopeStack<TypeVar> type_scopes;
+
+  /*! \brief The set of expression scopes used for lexical scope. */
+  ScopeStack<Var> expr_scopes;
+
+  Parser(std::vector<Token> tokens, OperatorTable op_table, Source source)
+      : diag_ctx(source), pos(0), tokens(tokens), op_table(op_table), ignore_whitespace(true)
{}
+
+  void DisplayNextN(int n) {
+    std::cout << "remaining tokens: " << std::endl;
+    auto bound = std::min(pos + n, (int)tokens.size());
+    for (int i = 0; i < bound - pos; i++) {
+      std::cout << tokens[pos + i] << std::endl;
+    }
+  }
+
+  Token Peek() {
+    // For now we ignore all whitespace tokens and comments.
+    // We can tweak this behavior later to enable white space sensitivity in the parser.
+    while (pos < tokens.size() &&
+           ignore_whitespace && (tokens.at(pos)->token_type == TokenType::Whitespace
||
+                                 tokens.at(pos)->token_type == TokenType::Newline ||
+                                 tokens.at(pos)->token_type == TokenType::LineComment
||
+                                 tokens.at(pos)->token_type == TokenType::Comment)) {
+      // std::cout << "pos: " << pos << std::endl;
+      // std::cout << "tokens: " << tokens.size() << std::endl;
+      pos++;
+    }
+
+    if (pos < tokens.size()) {
+      return Token(this->tokens.at(pos));
+    } else {
+      return Token::Null();
+    }
+  }
+
+  // Allow lookahead into the token stream.
+  Token Lookahead(int n) {
+    CHECK_LE(1, n)

Review comment:
        CHECK_GT(n, 1) equivalent and clearer, but ensures that n > 1, in direct contradiction
to the error message on next line.. 

##########
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 <tvm/ir/module.h>
+#include <tvm/relay/expr.h>
+#include <tvm/relay/function.h>
+#include <tvm/runtime/object.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/node/reflection.h>
+
+#include <fstream>
+
+#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<GlobalFunc> funcs;
+  std::vector<TypeData> 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<MetaRefExprNode>();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template<typename T>
+struct Scope {
+  std::unordered_map<std::string, T> name_map;
+  Scope() : name_map() {}
+};
+
+template<typename T>
+struct ScopeStack {
+  std::vector<Scope<T>> 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<T>());
+  }
+
+  void PopStack() {
+    this->scope_stack.pop_back();
+  }
+};
+
+template<typename T>
+struct InternTable {
+  std::unordered_map<std::string, T> 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<Token> tokens;
+
+  /*! \brief The configured operator table. */
+  OperatorTable op_table;
+
+  /*! \brief Configure the whitespace mode, right now we ignore all whitespace. */
+  bool ignore_whitespace;
+
+  /*! \brief A global mapping for GlobalVar. */
+  InternTable<GlobalVar> global_names;
+
+  /*! \brief A global mapping for type definitions. */
+  InternTable<GlobalTypeVar> type_names;
+
+  /*! \brief A mapping from graph variable to expression, i.e., `%0 = expr`. */
+  std::unordered_map<int, Expr> graph_ctx;
+
+  /*! \brief The set of type scopes used for generics. */
+  ScopeStack<TypeVar> type_scopes;
+
+  /*! \brief The set of expression scopes used for lexical scope. */
+  ScopeStack<Var> expr_scopes;
+
+  Parser(std::vector<Token> tokens, OperatorTable op_table, Source source)
+      : diag_ctx(source), pos(0), tokens(tokens), op_table(op_table), ignore_whitespace(true)
{}
+
+  void DisplayNextN(int n) {
+    std::cout << "remaining tokens: " << std::endl;
+    auto bound = std::min(pos + n, (int)tokens.size());
+    for (int i = 0; i < bound - pos; i++) {
+      std::cout << tokens[pos + i] << std::endl;
+    }
+  }
+
+  Token Peek() {
+    // For now we ignore all whitespace tokens and comments.
+    // We can tweak this behavior later to enable white space sensitivity in the parser.
+    while (pos < tokens.size() &&
+           ignore_whitespace && (tokens.at(pos)->token_type == TokenType::Whitespace
||
+                                 tokens.at(pos)->token_type == TokenType::Newline ||
+                                 tokens.at(pos)->token_type == TokenType::LineComment
||
+                                 tokens.at(pos)->token_type == TokenType::Comment)) {
+      // std::cout << "pos: " << pos << std::endl;
+      // std::cout << "tokens: " << tokens.size() << std::endl;
+      pos++;
+    }
+
+    if (pos < tokens.size()) {
+      return Token(this->tokens.at(pos));
+    } else {
+      return Token::Null();
+    }
+  }
+
+  // Allow lookahead into the token stream.
+  Token Lookahead(int n) {

Review comment:
       Why does this fn have arguments? You prevent lookahead of more than 1, so the only
arguments that work are args <= 0, which just return Peek() and doesn't update pos, or
1

##########
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 <tvm/ir/module.h>
+#include <tvm/relay/expr.h>
+#include <tvm/relay/function.h>
+#include <tvm/runtime/object.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/node/reflection.h>
+
+#include <fstream>
+
+#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<GlobalFunc> funcs;
+  std::vector<TypeData> 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<MetaRefExprNode>();
+  rnode->type_key = type_key;
+  rnode->node_index = node_index;
+  data_ = std::move(rnode);
+}
+
+template<typename T>
+struct Scope {
+  std::unordered_map<std::string, T> name_map;
+  Scope() : name_map() {}
+};
+
+template<typename T>
+struct ScopeStack {
+  std::vector<Scope<T>> 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<T>());
+  }
+
+  void PopStack() {
+    this->scope_stack.pop_back();
+  }
+};
+
+template<typename T>
+struct InternTable {
+  std::unordered_map<std::string, T> 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<Token> tokens;
+
+  /*! \brief The configured operator table. */
+  OperatorTable op_table;
+
+  /*! \brief Configure the whitespace mode, right now we ignore all whitespace. */
+  bool ignore_whitespace;
+
+  /*! \brief A global mapping for GlobalVar. */
+  InternTable<GlobalVar> global_names;
+
+  /*! \brief A global mapping for type definitions. */
+  InternTable<GlobalTypeVar> type_names;
+
+  /*! \brief A mapping from graph variable to expression, i.e., `%0 = expr`. */
+  std::unordered_map<int, Expr> graph_ctx;
+
+  /*! \brief The set of type scopes used for generics. */
+  ScopeStack<TypeVar> type_scopes;
+
+  /*! \brief The set of expression scopes used for lexical scope. */
+  ScopeStack<Var> expr_scopes;
+
+  Parser(std::vector<Token> tokens, OperatorTable op_table, Source source)
+      : diag_ctx(source), pos(0), tokens(tokens), op_table(op_table), ignore_whitespace(true)
{}
+
+  void DisplayNextN(int n) {
+    std::cout << "remaining tokens: " << std::endl;
+    auto bound = std::min(pos + n, (int)tokens.size());
+    for (int i = 0; i < bound - pos; i++) {
+      std::cout << tokens[pos + i] << std::endl;
+    }
+  }
+
+  Token Peek() {
+    // For now we ignore all whitespace tokens and comments.
+    // We can tweak this behavior later to enable white space sensitivity in the parser.
+    while (pos < tokens.size() &&
+           ignore_whitespace && (tokens.at(pos)->token_type == TokenType::Whitespace
||
+                                 tokens.at(pos)->token_type == TokenType::Newline ||
+                                 tokens.at(pos)->token_type == TokenType::LineComment
||
+                                 tokens.at(pos)->token_type == TokenType::Comment)) {
+      // std::cout << "pos: " << pos << std::endl;
+      // std::cout << "tokens: " << tokens.size() << std::endl;
+      pos++;
+    }
+
+    if (pos < tokens.size()) {
+      return Token(this->tokens.at(pos));
+    } else {
+      return Token::Null();
+    }
+  }
+
+  // Allow lookahead into the token stream.
+  Token Lookahead(int n) {
+    CHECK_LE(1, n)
+      << "lookahead by > 1 is invalid";
+
+    auto old_pos = pos;
+    for (int i = 0; i < n - 1; i++) {

Review comment:
       If n = 1, i < (n -1) becomes i < 0 -- so the loop won't execute when i = 1. Change
to i < n or i <= n-1




----------------------------------------------------------------
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:
users@infra.apache.org



Mime
View raw message