Skip to content

Commit 925ec37

Browse files
committed
Fix negative number syntax. Add a unary '-' operator.
Closes #63.
1 parent c013b55 commit 925ec37

File tree

4 files changed

+28
-1
lines changed

4 files changed

+28
-1
lines changed

builtin.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,15 @@ static jv f_plus(jv input, jv a, jv b) {
6565
}
6666
}
6767

68+
static jv f_negate(jv input) {
69+
if (jv_get_kind(input) != JV_KIND_NUMBER) {
70+
return type_error(input, "cannot be negated");
71+
}
72+
jv ret = jv_number(-jv_number_value(input));
73+
jv_free(input);
74+
return ret;
75+
}
76+
6877
static jv f_minus(jv input, jv a, jv b) {
6978
jv_free(input);
7079
if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {
@@ -462,6 +471,7 @@ static jv f_error(jv input, jv msg) {
462471

463472
static struct cfunction function_list[] = {
464473
{(cfunction_ptr)f_plus, "_plus", 3},
474+
{(cfunction_ptr)f_negate, "_negate", 1},
465475
{(cfunction_ptr)f_minus, "_minus", 3},
466476
{(cfunction_ptr)f_multiply, "_multiply", 3},
467477
{(cfunction_ptr)f_divide, "_divide", 3},

lexer.l

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ struct lexer_param;
7373
yylval->literal = jv_string_sized(yytext + 1, yyleng - 1); return FORMAT;
7474
}
7575

76-
-?[0-9.]+([eE][+-]?[0-9]+)? {
76+
[0-9.]+([eE][+-]?[0-9]+)? {
7777
yylval->literal = jv_parse_sized(yytext, yyleng); return LITERAL;
7878
}
7979

parser.y

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,10 @@ Exp "+=" Exp {
260260
$$ = gen_update($1, $3, '+');
261261
} |
262262

263+
'-' Exp {
264+
$$ = BLOCK($2, gen_call("_negate", gen_noop()));
265+
} |
266+
263267
Exp '-' Exp {
264268
$$ = gen_binop($1, $3, '-');
265269
} |

testdata

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ null
2121
null
2222
1
2323

24+
25+
-1
26+
null
27+
-1
28+
2429
# FIXME: much more number testing needed
2530

2631
{}
@@ -197,6 +202,14 @@ null
197202
"wtasdf"
198203
2.0
199204

205+
2-1
206+
null
207+
1
208+
209+
2-(-1)
210+
null
211+
3
212+
200213
1e+0+0.001e3
201214
"I wonder what this will be?"
202215
20e-1

0 commit comments

Comments
 (0)