chore: add increment/decrement operators and test suite to parser and tokenizer

Implement prefix and postfix ++/-- operators in the tokenizer (Inc/Dec token types) and parser (factor/unary functions) with correct pre/post semantics. Add increment_decrement_test.rc covering all four operator forms. Update Makefile to include the new test file in TESTS, add run-increment-decrement-test target, and fix .PHONY and TARGET dependency on dirs.
This commit is contained in:
2025-11-22 23:17:01 +00:00
parent 82722a757a
commit eb3d29ac8d
12 changed files with 69 additions and 4 deletions
+26
View File
@@ -119,6 +119,17 @@ long factor() {
Symbol *sym = &locals[idx];
if (pc < MAX_TOK && (tokens[pc].type == Inc || tokens[pc].type == Dec)) {
long val = memory[sym->addr];
if (tokens[pc].type == Inc) {
memory[sym->addr]++;
} else {
memory[sym->addr]--;
}
pc++;
return val;
}
if (pc >= MAX_TOK) return 0;
if (tokens[pc].type == '[') {
pc++;
@@ -158,6 +169,21 @@ long factor() {
long unary() {
if (pc >= MAX_TOK) return 0;
if (tokens[pc].type == Inc || tokens[pc].type == Dec) {
int op = tokens[pc++].type;
Token *t = &tokens[pc];
if (t->type != Id) error("Expected identifier after ++/--");
int idx = find_local(t->text, t->val);
if (idx == -1) error("Undefined variable");
pc++;
long addr = locals[idx].addr;
if (op == Inc) {
memory[addr]++;
} else {
memory[addr]--;
}
return memory[addr];
}
if (tokens[pc].type == '*') {
pc++;
int addr = unary();
+2
View File
@@ -77,6 +77,8 @@ void tokenize(char *src) {
if (!strncmp(s, ">=", 2)) { t->type = Ge; s += 2; continue; }
if (!strncmp(s, "&&", 2)) { t->type = And; s += 2; continue; }
if (!strncmp(s, "||", 2)) { t->type = Or; s += 2; continue; }
if (!strncmp(s, "++", 2)) { t->type = Inc; s += 2; continue; }
if (!strncmp(s, "--", 2)) { t->type = Dec; s += 2; continue; }
if (*s == '<') { t->type = Lt; s++; continue; }
if (*s == '>') { t->type = Gt; s++; continue; }
+1 -1
View File
@@ -9,7 +9,7 @@
enum {
Num = 128, Str, Id, Int, Char, Else, If, While, Return, Printf,
Assign, Eq, Ne, Lt, Gt, Le, Ge, Or, And
Assign, Eq, Ne, Lt, Gt, Le, Ge, Or, And, Inc, Dec
};
typedef struct {