Joos1W Compiler Framework
All Classes Functions Typedefs Pages
ParseTreeVisitor.cc
1 #include "parsetree/ParseTreeVisitor.h"
2 
3 #include "ast/AST.h"
4 #include "parsetree/ParseTree.h"
5 #include <utils/Error.h>
6 
7 namespace parsetree {
8 
9 using pty = Node::Type;
10 using ptv = ParseTreeVisitor;
11 
12 ast::CompilationUnit* ptv::visitCompilationUnit(Node* node) {
13  // Check the node we're visiting
14  check_node_type(node, pty::CompilationUnit);
15  check_num_children(node, 3, 3);
16  // $1: Visit the package declaration
17  auto package = visitPackageDeclaration(node);
18  // $2: Visit the import declarations
19  ast::pmr_vector<ast::ImportDeclaration> imports;
20  visitListPattern<pty::ImportDeclarationList, ast::ImportDeclaration, true>(
21  node->child(1), imports);
22  // $3: Visit the body, if it is not null
23  if(auto body = node->child(2)) {
24  if(body->get_node_type() == pty::ClassDeclaration) {
25  ast::ClassDecl* class_body = visitClassDeclaration(body);
26  return sem.BuildCompilationUnit(
27  package, imports, class_body->location(), class_body);
28  } else if(body->get_node_type() == pty::InterfaceDeclaration) {
29  ast::InterfaceDecl* intf_body = visitInterfaceDeclaration(body);
30  return sem.BuildCompilationUnit(
31  package, imports, intf_body->location(), intf_body);
32  }
33  }
34  return nullptr;
35 }
36 
37 ast::ReferenceType* ptv::visitPackageDeclaration(Node* node) {
38  if(node->child(0) == nullptr) return sem.BuildUnresolvedType(node->location());
39  node = node->child(0);
40  check_node_type(node, pty::PackageDeclaration);
41  check_num_children(node, 1, 1);
42  return visitReferenceType(node->child(0));
43 }
44 
45 template <>
46 ast::ImportDeclaration ptv::visit<pty::ImportDeclarationList>(Node* node) {
47  check_num_children(node, 1, 1);
48  auto id = visitReferenceType(node->child(0));
49  if(node->get_node_type() == pty::SingleTypeImportDeclaration) {
50  return ast::ImportDeclaration{id, false};
51  } else if(node->get_node_type() == pty::TypeImportOnDemandDeclaration) {
52  return ast::ImportDeclaration{id, true};
53  }
54  throw utils::FatalError("Import called on a node that is not a Import");
55 }
56 
57 } // namespace parsetree