Added negative numbers.

This commit is contained in:
Jacob Signorovitch 2024-12-21 10:33:36 -05:00
parent 905acacd07
commit e3afe52ab7
3 changed files with 26 additions and 0 deletions

View File

@ -32,6 +32,11 @@ ASTNumData exec_call(AST* ast) {
ASTNumData n2 = exec_expr(calldata->argv[1]); ASTNumData n2 = exec_expr(calldata->argv[1]);
return n1 + n2; return n1 + n2;
} else if (!strcmp(calldata->to, "-") && calldata->argc == 2) {
ASTNumData n1 = exec_expr(calldata->argv[0]);
ASTNumData n2 = exec_expr(calldata->argv[1]);
return n1 - n2;
} }
return -1000; return -1000;
} }

View File

@ -22,6 +22,7 @@
%define parse.error verbose %define parse.error verbose
%token<fval> NUM %token<fval> NUM
%token NEG
%token<strval> CALL %token<strval> CALL
%token PLUS %token PLUS
%token NL %token NL
@ -36,11 +37,30 @@ input:
exp: exp:
NUM { $$ = ast_init(AST_TYPE_NUM, ast_num_data_init($1)); } NUM { $$ = ast_init(AST_TYPE_NUM, ast_num_data_init($1)); }
| NEG NUM { $$ = ast_init(AST_TYPE_NUM, ast_num_data_init(-$2)); }
| NUM PLUS NUM { | NUM PLUS NUM {
AST** argv = calloc(2, sizeof(AST*)); AST** argv = calloc(2, sizeof(AST*));
argv[0] = ast_init(AST_TYPE_NUM, ast_num_data_init($1)); argv[0] = ast_init(AST_TYPE_NUM, ast_num_data_init($1));
argv[1] = ast_init(AST_TYPE_NUM, ast_num_data_init($3)); argv[1] = ast_init(AST_TYPE_NUM, ast_num_data_init($3));
$$ = ast_init(AST_TYPE_CALL, ast_call_data_init("+", 2, argv)); $$ = ast_init(AST_TYPE_CALL, ast_call_data_init("+", 2, argv));
} }
| NEG NUM PLUS NUM {
AST** argv = calloc(2, sizeof(AST*));
argv[0] = ast_init(AST_TYPE_NUM, ast_num_data_init(-$2));
argv[1] = ast_init(AST_TYPE_NUM, ast_num_data_init($4));
$$ = ast_init(AST_TYPE_CALL, ast_call_data_init("+", 2, argv));
}
| NUM NEG NUM {
AST** argv = calloc(2, sizeof(AST*));
argv[0] = ast_init(AST_TYPE_NUM, ast_num_data_init($1));
argv[1] = ast_init(AST_TYPE_NUM, ast_num_data_init($3));
$$ = ast_init(AST_TYPE_CALL, ast_call_data_init("-", 2, argv));
}
| NEG NUM NEG NUM {
AST** argv = calloc(2, sizeof(AST*));
argv[0] = ast_init(AST_TYPE_NUM, ast_num_data_init(-$2));
argv[1] = ast_init(AST_TYPE_NUM, ast_num_data_init($4));
$$ = ast_init(AST_TYPE_CALL, ast_call_data_init("-", 2, argv));
}
%% %%

View File

@ -65,6 +65,7 @@ int yylex() {
switch (c) { switch (c) {
case '+': return PLUS; case '+': return PLUS;
case '\n': return NL; case '\n': return NL;
case '-': return NEG;
default: return CALL; default: return CALL;
} }