fix unary precedence

This commit is contained in:
tovjemam 2024-10-13 21:42:01 +02:00
parent 704979f9bb
commit ea9b427363

View File

@ -119,32 +119,15 @@ static struct expr_node *parse_base(struct lexer *lex) {
return NULL; return NULL;
} }
static struct expr_node* parse_unary(struct lexer *lex) { static struct expr_node* parse_unary(struct lexer* lex);
if (accept(lex, TOK_MINUS)) {
struct expr_node *node, *inner;
if (!(inner = parse_base(lex)))
return NULL;
if (!(node = node_create_neg(inner))) {
node_free(inner);
return NULL;
}
return node;
}
accept(lex, TOK_PLUS);
return parse_base(lex);
}
static struct expr_node* parse_factor(struct lexer* lex) { static struct expr_node* parse_factor(struct lexer* lex) {
struct expr_node* node, * new_node, * inner; struct expr_node* node, * new_node, * inner;
if (!(node = parse_unary(lex))) if (!(node = parse_base(lex)))
return NULL; return NULL;
while (accept(lex, TOK_POWER)) { if (accept(lex, TOK_POWER)) {
if (!(inner = parse_unary(lex))) { if (!(inner = parse_unary(lex))) {
node_free(node); node_free(node);
return NULL; return NULL;
@ -156,16 +139,35 @@ static struct expr_node *parse_factor(struct lexer *lex) {
return NULL; return NULL;
} }
node = new_node; return new_node;
} }
return node; return node;
} }
static struct expr_node* parse_unary(struct lexer *lex) {
if (accept(lex, TOK_MINUS)) {
struct expr_node *node, *inner;
if (!(inner = parse_factor(lex)))
return NULL;
if (!(node = node_create_neg(inner))) {
node_free(inner);
return NULL;
}
return node;
}
accept(lex, TOK_PLUS);
return parse_factor(lex);
}
static struct expr_node *parse_term(struct lexer *lex) { static struct expr_node *parse_term(struct lexer *lex) {
struct expr_node *node, *new_node, *inner; struct expr_node *node, *new_node, *inner;
if (!(node = parse_factor(lex))) if (!(node = parse_unary(lex)))
return NULL; return NULL;
while (1) { while (1) {
@ -178,7 +180,7 @@ static struct expr_node *parse_term(struct lexer *lex) {
else else
break; break;
if (!(inner = parse_factor(lex))) { if (!(inner = parse_unary(lex))) {
node_free(node); node_free(node);
return NULL; return NULL;
} }