-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.c
More file actions
518 lines (439 loc) · 15 KB
/
parser.c
File metadata and controls
518 lines (439 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/*
* Parser - Recursive Descent Parser for PL/0
*
* Implements a recursive descent parser based on the PL/0 EBNF grammar.
* Performs semantic analysis (symbol table management) and code generation
* in a single pass. This is the classic approach used in Wirth's textbook.
*
* EBNF Grammar:
* program = parser_block "." ;
* parser_block = [ "const" ident "=" number {"," ident "=" number} ";"]
* [ "var" ident {"," ident} ";"]
* { "procedure" ident ";" parser_block ";" } parser_statement ;
* parser_statement = [ ident ":=" parser_expression | "call" ident
* | "?" ident | "!" parser_expression
* | "begin" parser_statement {";" parser_statement } "end"
* | "if" parser_condition "then" parser_statement
* | "while" parser_condition "do" parser_statement ];
* parser_condition = "odd" parser_expression |
* parser_expression ("="|"#"|"<"|"<="|">"|">=") parser_expression ;
* parser_expression = ["+"|"-"] parser_term { ("+"|"-") parser_term};
* parser_term = parser_factor {("*"|"/") parser_factor};
* parser_factor = ident | number | "(" parser_expression ")" ;
*/
#include "pl0.h"
/*
* Emit an instruction to the code array.
*/
static void emit(Parser *parser, Opcode op, int value)
{
if (parser->code->code_count >= MAX_CODE_SIZE) {
fprintf(stderr, "Error: code segment overflow\n");
parser->error_count++;
return;
}
parser->code->code[parser->code->code_count].op = op;
parser->code->code[parser->code->code_count].value = value;
parser->code->code_count++;
}
/*
* Report a parser error with location.
*/
static void error(Parser *parser, const char *message)
{
fprintf(stderr, "Error at line %d: %s\n",
parser->lexer->current.line, message);
parser->error_count++;
}
/*
* Check if current token matches expected type. If so, advance to next token.
* Returns 1 on match, 0 otherwise.
*/
static int match(Parser *parser, TokenType expected)
{
if (parser->lexer->current.type == expected) {
lexer_next(parser->lexer);
return 1;
}
return 0;
}
/*
* Require a token - reports error if not present but still advances.
*/
static void require(Parser *parser, TokenType expected, const char *what)
{
if (!match(parser, expected)) {
fprintf(stderr, "Error at line %d: expected %s, got %d\n",
parser->lexer->current.line, what,
parser->lexer->current.type);
parser->error_count++;
lexer_next(parser->lexer); /* Advance past the bad token */
}
}
/*
* Initialize parser with all required context.
*/
void parser_init(Parser *parser, Lexer *lexer, SymbolTable *symbols, Code *code)
{
parser->lexer = lexer;
parser->symbols = symbols;
parser->code = code;
parser->level = 0;
parser->data_addr = 3; /* 0: return addr, 1: static link, 2: first local */
parser->proc_count = 0;
parser->error_count = 0;
}
/*
* program = parser_block "." ;
*
* A PL/0 program is simply a parser_block followed by a period.
*/
void parser_program(Parser *parser)
{
parser_block(parser);
require(parser, T_PERIOD, ".");
/* Emit HALT instruction */
emit(parser, OP_HALT, 0);
}
/*
* parser_block = [ "const" ident "=" number {"," ident "=" number} ";"]
* [ "var" ident {"," ident} ";"]
* { "procedure" ident ";" parser_block ";" } parser_statement ;
*
* Handles declarations (constants, variables, procedures) and then
* parses the main parser_statement.
*/
void parser_block(Parser *parser)
{
/* const ident = number {, ident = number } ; */
if (match(parser, T_CONST)) {
do {
require(parser, T_IDENT, "identifier");
char name[MAX_IDENT_LEN];
strncpy(name, parser->lexer->current.ident, MAX_IDENT_LEN - 1);
name[MAX_IDENT_LEN - 1] = '\0';
require(parser, T_EQ, "=");
require(parser, T_NUMBER, "number");
int value = parser->lexer->current.value;
/* Add constant to symbol table */
symbol_add(parser->symbols, name, SYM_CONST, value, parser->level);
} while (match(parser, T_COMMA));
require(parser, T_SEMICOLON, ";");
}
/* var ident {, ident } ; */
if (match(parser, T_VAR)) {
do {
/* Save identifier BEFORE requiring it (since require advances) */
char name[MAX_IDENT_LEN];
if (parser->lexer->current.type == T_IDENT) {
strncpy(name, parser->lexer->current.ident, MAX_IDENT_LEN - 1);
name[MAX_IDENT_LEN - 1] = '\0';
} else {
name[0] = '\0';
}
require(parser, T_IDENT, "identifier");
/* Add variable to symbol table with its address */
symbol_add(parser->symbols, name, SYM_VAR, parser->data_addr, parser->level);
parser->data_addr++;
} while (match(parser, T_COMMA));
require(parser, T_SEMICOLON, ";");
}
/* { procedure ident ; parser_block ; } */
while (match(parser, T_PROCEDURE)) {
require(parser, T_IDENT, "procedure name");
char name[MAX_IDENT_LEN];
strncpy(name, parser->lexer->current.ident, MAX_IDENT_LEN - 1);
name[MAX_IDENT_LEN - 1] = '\0';
/* Record position for jump around procedure */
int proc_start = parser->code->code_count;
emit(parser, OP_JMP, 0); /* Will patch later */
/* Procedure address is AFTER the JMP instruction */
int proc_addr = parser->code->code_count;
/* Enter new scope - note procedure does not increase data_addr */
symbol_add(parser->symbols, name, SYM_PROC, proc_addr, parser->level);
require(parser, T_SEMICOLON, ";");
parser->level++;
parser_block(parser);
parser->level--;
/* Return from procedure */
emit(parser, OP_RET, 0);
/* Patch jump over procedure */
parser->code->code[proc_start].value = parser->code->code_count;
require(parser, T_SEMICOLON, ";");
}
/* Statement follows */
parser_statement(parser);
}
/*
* parser_statement = [ ident ":=" parser_expression
* | "call" ident
* | "?" ident
* | "!" parser_expression
* | "begin" parser_statement {";" parser_statement } "end"
* | "if" parser_condition "then" parser_statement
* | "while" parser_condition "do" parser_statement ];
*/
void parser_statement(Parser *parser)
{
/* ident := parser_expression (assignment) */
if (parser->lexer->current.type == T_IDENT) {
char name[MAX_IDENT_LEN];
strncpy(name, parser->lexer->current.ident, MAX_IDENT_LEN - 1);
name[MAX_IDENT_LEN - 1] = '\0';
lexer_next(parser->lexer); /* consume identifier */
Symbol *sym = symbol_lookup(parser->symbols, name);
if (sym == NULL) {
error(parser, "Undefined identifier");
}
require(parser, T_ASSIGN, ":=");
parser_expression(parser);
if (sym != NULL && sym->type == SYM_VAR) {
emit(parser, OP_STORE, sym->value);
}
return;
}
/* call ident */
if (match(parser, T_CALL)) {
require(parser, T_IDENT, "procedure name");
char name[MAX_IDENT_LEN];
strncpy(name, parser->lexer->current.ident, MAX_IDENT_LEN - 1);
name[MAX_IDENT_LEN - 1] = '\0';
Symbol *sym = symbol_lookup(parser->symbols, name);
if (sym != NULL && sym->type == SYM_PROC) {
emit(parser, OP_CALL, sym->value);
} else {
error(parser, "Undefined procedure");
}
return;
}
/* ? ident (read input) */
if (match(parser, T_READ)) {
require(parser, T_IDENT, "variable name");
char name[MAX_IDENT_LEN];
strncpy(name, parser->lexer->current.ident, MAX_IDENT_LEN - 1);
name[MAX_IDENT_LEN - 1] = '\0';
Symbol *sym = symbol_lookup(parser->symbols, name);
if (sym != NULL && sym->type == SYM_VAR) {
/* Input is read at runtime - emit code to read */
emit(parser, OP_READ, sym->value);
} else {
error(parser, "Undefined variable");
}
return;
}
/* ! parser_expression (write output) */
if (match(parser, T_WRITE)) {
parser_expression(parser);
emit(parser, OP_WRITE, 0);
return;
}
/* begin parser_statement { ; parser_statement } end */
if (match(parser, T_BEGIN)) {
parser_statement(parser);
while (match(parser, T_SEMICOLON)) {
parser_statement(parser);
}
require(parser, T_END, "end");
return;
}
/* if parser_condition then parser_statement [else parser_statement] */
if (match(parser, T_IF)) {
parser_condition(parser);
require(parser, T_THEN, "then");
/* Jump to else or past if */
int jz_pos = parser->code->code_count;
emit(parser, OP_JZ, 0);
parser_statement(parser);
/* Check for else */
if (match(parser, T_ELSE)) {
/* Jump past else block after then block */
int jmp_pos = parser->code->code_count;
emit(parser, OP_JMP, 0);
/* Patch the first jump to here (else start) */
parser->code->code[jz_pos].value = parser->code->code_count;
parser_statement(parser);
/* Patch the jump over else */
parser->code->code[jmp_pos].value = parser->code->code_count;
} else {
/* Patch the jump to here (past then block, no else) */
parser->code->code[jz_pos].value = parser->code->code_count;
}
return;
}
/* while parser_condition do parser_statement */
if (match(parser, T_WHILE)) {
int loop_start = parser->code->code_count;
parser_condition(parser);
require(parser, T_DO, "do");
int jz_pos = parser->code->code_count;
emit(parser, OP_JZ, 0);
parser_statement(parser);
/* Jump back to loop start */
emit(parser, OP_JMP, loop_start);
/* Patch the parser_conditional jump to exit loop */
parser->code->code[jz_pos].value = parser->code->code_count;
return;
}
}
/*
* parser_condition = "odd" parser_expression |
* parser_expression ("="|"#"|"<"|"<="|">"|">=") parser_expression ;
*/
void parser_condition(Parser *parser)
{
/* odd parser_expression */
if (match(parser, T_ODD)) {
parser_expression(parser);
emit(parser, OP_ODD, 0);
return;
}
/* parser_expression rel-op parser_expression */
parser_expression(parser);
TokenType relop = parser->lexer->current.type;
/* Check for valid operator before consuming */
if (relop != T_EQ && relop != T_NEQ && relop != T_LT &&
relop != T_LTE && relop != T_GT && relop != T_GTE) {
error(parser, "Expected relational operator");
return;
}
lexer_next(parser->lexer); /* consume operator */
parser_expression(parser);
/* Emit the relational operator AFTER both expressions */
switch (relop) {
case T_EQ:
emit(parser, OP_EQ, 0);
break;
case T_NEQ:
emit(parser, OP_NEQ, 0);
break;
case T_LT:
emit(parser, OP_LT, 0);
break;
case T_LTE:
emit(parser, OP_LTE, 0);
break;
case T_GT:
emit(parser, OP_GT, 0);
break;
case T_GTE:
emit(parser, OP_GTE, 0);
break;
default:
break; /* Should not reach here - already validated */
}
}
/*
* parser_expression = ["+"|"-"] parser_term { ("+"|"-") parser_term} ;
*/
void parser_expression(Parser *parser)
{
/* Optional unary + or - */
int unary_minus = 0;
if (match(parser, T_PLUS)) {
/* Unary plus - no-op */
} else if (match(parser, T_MINUS)) {
unary_minus = 1;
}
parser_term(parser);
/* Handle leading unary minus */
if (unary_minus) {
emit(parser, OP_CONST, 0);
emit(parser, OP_SUB, 0);
}
/* { ("+"|"-") parser_term } */
while (parser->lexer->current.type == T_PLUS ||
parser->lexer->current.type == T_MINUS) {
TokenType op = parser->lexer->current.type;
lexer_next(parser->lexer);
parser_term(parser);
if (op == T_PLUS) {
emit(parser, OP_ADD, 0);
} else {
emit(parser, OP_SUB, 0);
}
}
}
/*
* parser_term = parser_factor {("*"|"/") parser_factor} ;
*/
void parser_term(Parser *parser)
{
parser_factor(parser);
/* { ("*"|"/") parser_factor } */
while (parser->lexer->current.type == T_MUL ||
parser->lexer->current.type == T_DIV) {
TokenType op = parser->lexer->current.type;
lexer_next(parser->lexer);
parser_factor(parser);
if (op == T_MUL) {
emit(parser, OP_MUL, 0);
} else {
emit(parser, OP_DIV, 0);
}
}
}
/*
* parser_factor = ident | number | "(" parser_expression ")" ;
*/
void parser_factor(Parser *parser)
{
/* ident - could be constant or variable */
if (parser->lexer->current.type == T_IDENT) {
char name[MAX_IDENT_LEN];
strncpy(name, parser->lexer->current.ident, MAX_IDENT_LEN - 1);
name[MAX_IDENT_LEN - 1] = '\0';
lexer_next(parser->lexer);
Symbol *sym = symbol_lookup(parser->symbols, name);
if (sym == NULL) {
error(parser, "Undefined identifier");
return;
}
if (sym->type == SYM_CONST) {
/* Push constant value */
emit(parser, OP_CONST, sym->value);
} else if (sym->type == SYM_VAR) {
/* Load variable value */
emit(parser, OP_LOAD, sym->value);
} else {
error(parser, "Cannot use procedure in parser_expression");
}
return;
}
/* number - push constant */
if (parser->lexer->current.type == T_NUMBER) {
int value = parser->lexer->current.value;
lexer_next(parser->lexer);
emit(parser, OP_CONST, value);
return;
}
/* ( parser_expression ) */
if (match(parser, T_LPAREN)) {
parser_expression(parser);
require(parser, T_RPAREN, ")");
return;
}
error(parser, "Expected identifier, number, or (");
}
/* ============================================================================
* Main Compile Entry Point
* ============================================================================ */
int compile(const char *source, Code *code, SymbolTable *symbols)
{
Lexer lexer;
Parser parser;
/* Initialize code buffer */
code->code_count = 0;
/* Initialize symbol table */
symbol_init(symbols);
/* Initialize lexer */
lexer_init(&lexer, source);
/* Initialize parser */
parser_init(&parser, &lexer, symbols, code);
/* Parse program */
parser_program(&parser);
if (parser.error_count > 0) {
fprintf(stderr, "Compilation failed with %d error(s)\n", parser.error_count);
return -1;
}
return code->code_count;
}