lundi 16 janvier 2023

What are the potential drawbacks of using the Facade design pattern in C?

I've been writing a compiler for some time now as a passion project. As it stands, the compiler is written fully in C++. I employ the visitor pattern for things like type checking, code generation, debug printing, etc. I've realized over time, I don't need such a complex system to represent the various AST nodes. Whenever I want to add another AST node, it requires adding tons of boilerplate code and methods to "visit" this node.

I'm playing around with the idea of rewriting the front end of the compiler largely in C where I'll still use the C++ LLVM-IR API in the back end to simplify things. I think that OOP might add some unnecessary complexities to how I'm representing AST nodes, so I'm toying with the Facade pattern in C:

typedef enum {
  AST_NUM,
  AST_EXPR
} NodeType;

typedef struct AstNumNode AstNumNode;
typedef struct AstExprNode AstExprNode;

typedef struct AstNode {
  NodeType type;
  union {
    AstNumNode* num;
    AstExprNode* expr;
  } actual;
} AstNode;

struct AstExprNode {
  AstNode* left;
  AstNode* right;
};

struct AstNumNode {
  int value;
};

Of course, I'll still have to write methods such as:

void ast_node_print(AstNode* node, int depth); // switch on node->type and select one of the below methods based on that type
void ast_num_print(AstNumNode* node, int depth);
void ast_expr_print(AstExprNode* node, int depth);

which I view as much simpler than the visitor pattern.

However, when I'm creating these nodes, it can be a bit tedious to do the following:

AstNode* numNode = malloc(sizeof(AstNode));
numNode->type = AST_NUM;
numNode->actual.num = malloc(sizeof(AstNumNode));
numNode->actual.num->value = 10;

The last drawback I can see is space. Each AstNode will take up the same amount of space, regardless of what "sub-node" it wraps, because of the union. When compiling large programs, I can see this becoming a problem.

All in all, I'm having trouble weighing the advantages and drawbacks of doing it this way, so any help and guidance is much appreciated!

Aucun commentaire:

Enregistrer un commentaire