summaryrefslogtreecommitdiff
path: root/parse.c
diff options
context:
space:
mode:
Diffstat (limited to 'parse.c')
-rw-r--r--parse.c32
1 files changed, 22 insertions, 10 deletions
diff --git a/parse.c b/parse.c
index d2e1bcd..e059eb5 100644
--- a/parse.c
+++ b/parse.c
@@ -1,34 +1,39 @@
#include "parse.h"
#include "Token.h"
+#include "Scope.h"
#include <stdio.h>
+#include <stdlib.h>
static void *unexpected(const Token *tok, int n);
static const Token *expression(const Token *tok);
static const Token *keyword_fn(const Token *tok);
-static const Token *keyword_var(const Token *tok);
-static const Token *keyword_const(const Token *tok);
+static const Token *keyword_var(Scope *scope, const Token *tok);
+static const Token *keyword_const(Scope *scope, const Token *tok);
int parse(const Token *tok)
{
+ Scope *scope = scope_create(NULL);
+ if (scope == NULL)
+ return 1;
while (tok != NULL && tok->type != TOK_NONE) {
switch (tok->type) {
case TOK_KW_FN:
tok = keyword_fn(tok);
break;
case TOK_KW_VAR:
- tok = keyword_var(tok);
+ tok = keyword_var(scope, tok);
break;
case TOK_KW_CONST:
- tok = keyword_const(tok);
+ tok = keyword_const(scope, tok);
break;
default:
unexpected(tok, -1);
- return 1;
+ return free(scope), 1;
}
if (tok == NULL)
- return 1;
+ return free(scope), 1;
}
- return 0;
+ return free(scope), 0;
}
/* write unexpected token error to stderr before returning NULL,
@@ -81,7 +86,7 @@ static const Token *keyword_fn(const Token *tok)
}
/* mutable variable declaration */
-static const Token *keyword_var(const Token *tok)
+static const Token *keyword_var(Scope *scope, const Token *tok)
{
tok += 1;
if (tok->type != TOK_WORD)
@@ -90,8 +95,11 @@ static const Token *keyword_var(const Token *tok)
(void)name;
tok += 1;
/* no initialization */
- if (tok->type == TOK_SEMICOLON)
+ if (tok->type == TOK_SEMICOLON) {
+ if (scope_insert(scope, name->s, 0))
+ return NULL;
return tok + 1;
+ }
if (tok->type != TOK_ASSIGN)
return unexpected(tok, 11);
tok = expression(tok + 1);
@@ -99,11 +107,13 @@ static const Token *keyword_var(const Token *tok)
return NULL;
if (tok->type != TOK_SEMICOLON)
return unexpected(tok, 12);
+ if (scope_insert(scope, name->s, 0))
+ return NULL;
return tok + 1;
}
/* constant variable declaration */
-static const Token *keyword_const(const Token *tok)
+static const Token *keyword_const(Scope *scope, const Token *tok)
{
tok += 1;
if (tok->type != TOK_WORD)
@@ -118,5 +128,7 @@ static const Token *keyword_const(const Token *tok)
return NULL;
if (tok->type != TOK_SEMICOLON)
return unexpected(tok, 12);
+ if (scope_insert(scope, name->s, 0))
+ return NULL;
return tok + 1;
}