c-repl/src/include/parser.h

81 lines
1.5 KiB
C
Raw Normal View History

2023-10-27 17:07:58 +02:00
#ifndef DEF_PARSER_H
#define DEF_PARSER_H
2023-10-27 17:16:41 +02:00
#include <vector>
2023-10-27 17:07:58 +02:00
#include "tokenize.h"
using namespace std;
/** Grammar:
Prog -> Instruction; Prog | \epsilon
Instruction -> Statement | ExprStatement | Expr
Statement -> // Rien pour l'instant, mais "for", "if" etc
ExprStatement ->
| Type Identifier = Expr // AssignedDeclaration
| Type Identifier // Declaration
Expr ->
| T
2023-10-27 17:16:41 +02:00
| T + Expr
| T - Expr
2023-10-27 17:07:58 +02:00
T ->
| F
| F * T
| F / T
| F % T
U ->
2023-10-27 17:16:41 +02:00
| F
| - U
| + U
F ->
2023-10-27 17:07:58 +02:00
| (Expr)
| Identifier
| Number
| Identifier = Expr // Assignment
*/
enum class NodeType {
Prog, // -> Instruction; Prog
AssignedDeclaration, // -> Type Identifier = Expr
Declaration, // -> Type Identifier
2023-10-27 17:16:41 +02:00
Plus, // -> T + Expr
Minus, // -> T - Expr
2023-10-27 17:07:58 +02:00
Mult, // -> F * T
Div, // -> F / T
Mod, // -> F % T
UnaryMinus, // -> -F
UnaryPlus, // -> +F
Parenthesis, // -> (Expr)
2023-10-27 17:16:41 +02:00
Assignment // -> Identifier = Expr
2023-10-27 17:07:58 +02:00
};
2023-10-27 17:53:58 +02:00
struct Node;
2023-10-27 17:16:41 +02:00
struct InnerNode {
2023-10-27 17:07:58 +02:00
NodeType type;
2023-10-27 17:16:41 +02:00
vector<Node> children;
2023-10-27 17:07:58 +02:00
};
// A Leaf is always corresponding to a Token
2023-10-27 17:16:41 +02:00
struct Node {
bool is_leaf;
2023-10-27 17:07:58 +02:00
union {
2023-10-27 17:16:41 +02:00
InnerNode node;
2023-10-27 17:07:58 +02:00
Token leaf;
};
2023-10-27 17:53:58 +02:00
Node() : is_leaf(true), leaf{} {}
// Explicitly define the destructor
~Node() {
if (!is_leaf) node.~InnerNode();
}
2023-10-27 17:07:58 +02:00
};
#endif