Joos1W Compiler Framework
All Classes Functions Typedefs Pages
Decl.h
1 #pragma once
2 
3 #include "ast/AstNode.h"
4 #include "diagnostics/Location.h"
5 
6 namespace ast {
7 
8 /**
9  * @brief Represents a variable declaration with: a name, a type and an
10  * optional initializer.
11  */
12 class TypedDecl : public Decl {
13 public:
14  TypedDecl(BumpAllocator& alloc, SourceRange location, Type* type,
15  string_view name, Expr* init, ScopeID const* scope) noexcept
16  : Decl{alloc, name},
17  type_{type},
18  init_{init},
19  location_{location},
20  scope_{scope} {}
21 
22  Type const* type() const { return type_; }
23  Type* mut_type() const { return type_; }
24  utils::Generator<ast::AstNode const*> children() const override final {
25  co_yield type_;
26  }
27  bool hasInit() const { return init_ != nullptr; }
28  Expr const* init() const { return init_; }
29  Expr* mut_init() { return init_; }
30  SourceRange location() const override { return location_; }
31  ScopeID const* scope() const { return scope_; }
32 
33 private:
34  Type* type_;
35  Expr* init_;
36  SourceRange location_;
37  ScopeID const* const scope_;
38 };
39 
40 /**
41  * @brief Represents a scoped (i.e., local) typed variable declaration.
42  */
43 class VarDecl : public TypedDecl {
44 public:
45  VarDecl(BumpAllocator& alloc, SourceRange location, Type* type,
46  string_view name, Expr* init, ScopeID const* scope) noexcept
47  : TypedDecl{alloc, location, type, name, init, scope} {}
48 
49  std::ostream& print(std::ostream& os, int indentation = 0) const override;
50  int printDotNode(DotPrinter& dp) const override;
51  virtual bool hasCanonicalName() const override { return false; }
52 };
53 
54 /**
55  * @brief Represents a typed declaration with access modifiers.
56  */
57 class FieldDecl final : public TypedDecl {
58 public:
59  FieldDecl(BumpAllocator& alloc, SourceRange location, Modifiers modifiers,
60  Type* type, string_view name, Expr* init,
61  ScopeID const* scope) noexcept
62  : TypedDecl{alloc, location, type, name, init, scope},
63  modifiers_{modifiers} {};
64 
65  std::ostream& print(std::ostream& os, int indentation = 0) const override;
66  int printDotNode(DotPrinter& dp) const override;
67  bool hasCanonicalName() const override { return modifiers_.isStatic(); }
68  auto modifiers() const { return modifiers_; }
69  void setParent(DeclContext* parent) override {
70  Decl::setParent(parent);
71  auto parentDecl = dyn_cast<Decl>(parent);
72  assert(parentDecl && "Parent must be a Decl");
73  if(modifiers_.isStatic()) {
74  canonicalName_ = parentDecl->getCanonicalName();
75  canonicalName_ += ".";
76  canonicalName_ += name();
77  }
78  }
79 
80 private:
81  Modifiers modifiers_;
82 };
83 
84 } // namespace ast