1 Commits
5 changed files with 79 additions and 2 deletions
+2 -1
View File
@@ -39,8 +39,9 @@ void RunFile(const char* path) {
char* contents = GetFileContents(path);
TokenList* tokens = ScanTokens(contents);
free(contents);
printf("TOKENS:\n");
Print(tokens);
printf("TREE:\n");
printf("EXPRESSION TREE:\n");
Expr* tree = GenerateExpressionTree(tokens);
PrintExpressionTree(tree);
printf("\n");
+33 -1
View File
@@ -1,5 +1,6 @@
#include "parser.h"
#include "expr.h"
#include "statement.h"
#include "token.h"
#include <stdio.h>
@@ -10,6 +11,9 @@ Expr* Term(void);
Expr* Factor(void);
Expr* Unary(void);
Expr* Primary(void);
Stmt* Statement(void);
Stmt* PrintStatement(void);
Stmt* ExpressionStatement(void);
int Match(int, ...);
int Check(TokenType);
int ParserAtEnd(void);
@@ -32,6 +36,34 @@ Expr* Expression() {
return Equality();
}
Stmt* Statement(void) {
if (Match(1, PRINT)) return PrintStatement();
return ExpressionStatement();
}
Stmt* PrintStatement(void) {
Expr* value = Expression();
if (!Match(1, Semicolon)) fprintf(stderr, "Expected ';' after value\n");
AdvanceParser();
return CreateStatement(value, STMT_Print);
}
Stmt* ExpressionStatement(void) {
Expr* expr = Expression();
if (!Match(1, Semicolon)) fprintf(stderr, "Expected ';' after expression\n");
AdvanceParser();
return CreateStatement(expr, STMT_Expression);
}
Stmt* ExpressionStatement(void);
Expr* Equality() {
Expr* expr = Comparison();
@@ -146,7 +178,7 @@ Expr* Primary() {
return temp;
}
printf("Bad expression\n");
fprintf(stderr, "Bad expression, this should be unreachable.\n");
return NULL;
}
+1
View File
@@ -4,6 +4,7 @@
#include "expr.h"
#include "scanner.h"
#include "token.h"
#include "statement.h"
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
+21
View File
@@ -0,0 +1,21 @@
#include "statement.h"
Stmt* CreateStatement(Expr* expression, StatementType type) {
Stmt* stmt = calloc(1, sizeof(Stmt));
if (!stmt) {
fprintf(stderr, "Failed to calloc space for Statement. %s.\n", strerror(errno));
return NULL;
}
stmt->expression = expression;
stmt->type = type;
return stmt;
}
void FreeStatement(Stmt* stmt) {
if (!stmt) return;
free(stmt);
}
+22
View File
@@ -0,0 +1,22 @@
#ifndef STATEMENT_H
#define STATEMENT_H
#include "expr.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
typedef enum {
STMT_Expression,
STMT_Print
} StatementType;
typedef struct stmt {
StatementType type;
Expr* expression;
} Stmt;
Stmt* CreateStatement(Expr*, StatementType);
void FreeStatement(Stmt*);
#endif