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



##########
File path: src/parser/parser.cc
##########
@@ -0,0 +1,968 @@
+/*
+ * 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 "./tokenizer.h"
+
+namespace tvm {
+namespace parser {
+
+using namespace relay;
+using Expr = relay::Expr;
+
+// expr
+//   // operators
+//   : '(' expr ')'                             # paren
+//   // function application
+//   | expr '(' callList ')'                    # call
+//   | '-' expr                                 # neg
+//   | expr op=('*'|'/') expr                   # binOp
+//   | expr op=('+'|'-') expr                   # binOp
+//   | expr op=('<'|'>'|'<='|'>=') expr         # binOp
+//   | expr op=('=='|'!=') expr                 # binOp
+//   // function definition
+//   | func                                     # funcExpr
+//   // tuples and tensors
+//   | '(' ')'                                  # tuple
+//   | '(' expr ',' ')'                         # tuple
+//   | '(' expr (',' expr)+ ')'                 # tuple
+//   | '[' (expr (',' expr)*)? ']'              # tensor
+//   | 'if' '(' expr ')' body 'else' body       # ifElse
+//   | matchType expr '{' matchClauseList? '}'  # match
+//   | expr '.' NAT                             # projection
+//   // sequencing
+//   | 'let' var '=' expr ';' expr              # let
+//   // sugar for let %_ = expr; expr
+//   | expr ';;' expr                           # let
+//   | graphVar '=' expr ';' expr               # graph
+//   | ident                                    # identExpr
+//   | scalar                                   # scalarExpr
+//   | meta                                     # metaExpr
+//   | QUOTED_STRING                            # stringExpr
+//   ;
+
+// func: 'fn' typeParamList? '(' argList ')' ('->' typeExpr)? body ;
+// defn
+//   : 'def' globalVar typeParamList? '(' argList ')' ('->' typeExpr)? body  # 
funcDefn
+//   | 'extern' 'type' generalIdent typeParamList?                           # 
externAdtDefn
+//   | 'type' generalIdent typeParamList? '{' adtConsDefnList? '}'           # 
adtDefn
+//   ;
+
+// constructorName: CNAME ;
+
+// 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
+//   ;
+
+// adtCons: constructorName adtConsParamList? ;
+// adtConsParamList: '(' adtConsParam (',' adtConsParam)* ')' ;
+// adtConsParam: localVar | constructorName ;
+
+// argList
+//   : varList             # argNoAttr
+//   | (var ',')* attrSeq  # argWithAttr
+//   ;
+
+// varList: (var (',' var)*)? ;
+// var: localVar (':' typeExpr)? ;
+
+// attrSeq: attr (',' attr)* ;
+// attr: CNAME '=' expr ;
+
+// typeExpr
+//   : '(' ')'                                                                
# tupleType
+//   | '(' typeExpr ')'                                                       
# typeParen
+//   | '(' typeExpr ',' ')'                                                   
# tupleType
+//   | '(' typeExpr (',' typeExpr)+ ')'                                       
# tupleType
+//   | generalIdent typeParamList                                             
# typeCallType
+//   | generalIdent                                                           
# typeIdentType
+//   | 'Tensor' '[' shapeList ',' typeExpr ']'                                
# tensorType
+//   | 'fn' typeParamList? '(' (typeExpr (',' typeExpr)*)? ')' '->' typeExpr  
# funcType
+//   | '_'                                                                    
# incompleteType
+//   ;
+
+// typeParamList: '[' typeExpr (',' typeExpr)* ']' ;
+
+// shapeList
+//   : '(' ')'
+//   | '(' shape (',' shape)+ ')'
+//   | shape
+//   ;
+
+// meta : 'meta' '[' CNAME ']' '[' NAT ']';
+
+// shape
+//   : meta           # metaShape
+//   | '(' shape ')'  # parensShape
+//   | NAT            # intShape
+//   ;
+
+
+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);
+}
+
+struct Rule {
+  std::vector<TokenType> 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<TokenType> 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<Rule> rules;
+  std::unordered_map<std::string, Rule> this_is_a_hack;
+
+  OperatorTable(std::vector<Rule> rules) : rules(rules), this_is_a_hack() {
+    for (auto rule : rules) {
+      std::stringstream key;
+      for (auto token : rule.tokens) {
+        key << ToString(token);
+      }
+      this->this_is_a_hack.insert({ key.str(), rule });
+    }
+  }
+};
+
+struct Scope {
+  std::unordered_map<std::string, Var> name_map;
+  Scope() : name_map() {}
+};
+
+struct Parser {
+  int pos;
+  std::vector<Token> tokens;
+  OperatorTable op_table;
+  bool ignore_whitespace;
+
+  std::unordered_map<int, Expr> graph_ctx;
+  std::vector<Scope> scopes = { Scope() };
+
+  Parser(std::vector<Token> tokens, OperatorTable op_table)
+      : pos(0), tokens(tokens), op_table(op_table) {
+        // DisplayNextN(100);
+  }
+
+  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++) {
+      Peek();
+      pos++;
+    }
+
+    auto tok = Peek();
+    pos = old_pos;
+    return tok;
+  }
+
+  void Consume(const TokenType& token) {
+    if (tokens[pos]->token_type != token) {
+      throw std::runtime_error(
+          "expected a " + ToString(token) + " found " + 
ToString(Peek()->token_type) + " at " +
+          std::to_string(tokens[pos]->line) + ":" + 
std::to_string(tokens[pos]->column));
+    }
+    pos++;
+  }
+
+  Token Match(const TokenType& token_type) {
+    auto tok = Peek();
+    Consume(token_type);
+    return tok;
+  }
+
+  bool WhenMatch(const TokenType& token_type) {
+    if (Peek()->token_type == token_type) {
+      Consume(token_type);
+      return true;
+    } else {
+      return false;
+    }
+  }
+
+  void AddGraphBinding(const Token& token, const Expr& expr) {
+    auto graph_no = token.ToNumber();
+    this->graph_ctx.insert({graph_no, expr});
+  }
+
+  Expr LookupGraphBinding(const Token& token) {
+    auto graph_no = token.ToNumber();
+    return this->graph_ctx.at(graph_no);
+  }
+
+  Var BindVar(std::string name, relay::Type type_annotation) {
+    auto var = Var(name, type_annotation);
+    this->scopes.back().name_map.insert({name, var});
+    return var;
+  }
+
+  Var LookupVarByString(const std::string& var) {
+    for (auto scope = this->scopes.rbegin(); scope != this->scopes.rend(); 
scope++) {
+      auto it = scope->name_map.find(var);
+      if (it != scope->name_map.end()) {
+        return it->second;
+      }
+    }
+    LOG(FATAL) << "foo";
+    return Var();
+  }
+
+  void PushScope() {
+    this->scopes.push_back(Scope());
+  }
+
+  void PopScope(int n) {

Review comment:
       rename to `PopScopes`




----------------------------------------------------------------
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


Reply via email to