-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathScan.c
525 lines (443 loc) · 11.8 KB
/
Scan.c
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
519
520
521
522
523
524
525
/*********************************************************************
* NAME: Benjamin Fowler
* NUMBER: 02251132
* SUBJECT: Modern Compiler Construction
* INSTRUCTOR: Dr Wayne Kelly
*********************************************************************
* MODULE: Scan.c
* PURPOSE: Implements the Scan module.
* DATE STARTED: 5th March, 2000.
* LAST EDITED: 10th May, 2000.
*
* REVISION HISTORY:
*
* 5th March: Wrote declarations, some work on implementation.
* 6th March: Wrote scanner, fixed some bugs.
* 8th March: Added refinement: minimial perfect hashing for
* parsing of reserved words. This should make
* the efficiency of scanning reserved words more
* more acceptable.
* Enable by #defining FAST_RESERVED_WORDS
* 23rd March: Moved declarations/definitions of printToken()
* to Util.[ch]
* 1st April: Fixed a scanner bug in Assignment 1 relating to
* comment parsing.
* 10th May: Fixed a bug where the EchoSource option wasn't
* working.
*********************************************************************/
#include "Globals.h"
#include "Scan.h"
#include "Util.h"
/* Uncomment this to enable fast reserved word scanning */
/* #define FAST_RESERVED_WORDS */
/* Definitions relevant to the operation to the scanner */
#define BUFFERLENGTH 256
char lineText[BUFFERLENGTH]; /* text of the current line */
char tokenString[MAXTOKENLEN+1]; /* lexeme of the current token */
int lineIndex = 0; /* current position in this line */
int lineSize = 0; /* size of the current line, in chars */
/* Here are the various state that the lexer DFSA can be in */
typedef enum
{
START, INNUM, INID, INDIV, INCOMMENT, INCOMMENT2, INNE, INLT, INGT,
INEQ, ERRORSTATE, DONE
} LexerState;
/*
* Here are the language reserved words, together with their corresponding
* tokens.
*/
char reservedWords[MAXRESERVED][7] =
{ "int", "void", "if", "else", "return", "while" };
TokenType reservedWordsTokens[MAXRESERVED] =
{ INT, VOID, IF, ELSE, RETURN, WHILE };
/***********************************************************************
The following code is automatically generated by the gperf(1)
minimal perfect hash function generator tool.
***********************************************************************/
/* C code produced by gperf version 2.7 */
/* Command-line: /tmp/n2251132/gperf-2.7/src/gperf -t gperfinput.txt */
struct fastReservedWords { char *name; TokenType tok; };
#define TOTAL_KEYWORDS 6
#define MIN_WORD_LENGTH 2
#define MAX_WORD_LENGTH 6
#define MIN_HASH_VALUE 2
#define MAX_HASH_VALUE 9
/* maximum key range = 8, duplicates = 0 */
#ifdef __GNUC__
__inline
#endif
static unsigned int
hash (str, len)
register const char *str;
register unsigned int len;
{
static unsigned char asso_values[] =
{
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
5, 0, 0,10,10, 0,10,10,10,10,
0,10,10,10, 0,10, 0,10, 0, 0,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10
};
return len + asso_values[(unsigned char)str[len - 1]] + asso_values[(unsigned char)str[0]];
}
#ifdef __GNUC__
__inline
#endif
struct fastReservedWords *
in_word_set (str, len)
register const char *str;
register unsigned int len;
{
static struct fastReservedWords wordlist[] =
{
{"", 0}, {"", 0},
{"if", IF},
{"int", INT},
{"else", ELSE},
{"while", WHILE},
{"return", RETURN},
{"", 0}, {"", 0},
{"void", VOID}
};
if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
{
register int key = hash (str, len);
if (key <= MAX_HASH_VALUE && key >= 0)
{
register const char *s = wordlist[key].name;
if (*str == *s && !strcmp (str + 1, s + 1))
return &wordlist[key];
}
}
return 0;
}
/**** END OF AUTO-GENERATED CODE ***************************************/
/*
* NAME: LookupReservedWord()
* PURPOSE: Looks up identifiers to check to see if they're reserved words.
*
* If the routine finds a match, the corresponding token is returned, else
* the token "ID" is returned instead.
*/
TokenType LookupReservedWord(char *lexeme)
{
#ifdef FAST_RESERVED_WORDS
struct fastReservedWords *rWord;
rWord = in_word_set(lexeme, strlen(lexeme));
if (rWord)
return (rWord->tok);
else
return ID;
#else
int i;
for (i=0; i<MAXRESERVED; ++i)
{
if (!strcmp(lexeme, reservedWords[i]))
return reservedWordsTokens[i];
}
return ID;
#endif
}
/*
* NANE: getNextChar()
* PURPOSE: Returns the next character from the source file.
*
* The reader will note that this code, and the "lookahead" mechanism
* bears a remarkable resemblence to that of Louden's in "Compiler
* Construction: Principles and Practice".
*
* Louden's code is as good as it gets, so I'd be wasting my time
* reinventing the wheel. Therefore, some snippets of code are
* borrowed from Louden.
*/
static char getNextChar()
{
/* Have we run out of characters? */
if (lineIndex >= lineSize)
{
++lineno;
/* get a new line and return a character */
if (fgets(lineText, BUFFERLENGTH-1, source))
{
lineSize = strlen(lineText);
lineIndex = 0;
/*
* If EchoSource is TRUE, we need to display source lines to
* standard output.
*/
if (EchoSource)
fprintf(listing, "SOURCE: %5d: %s", lineno, lineText);
return lineText[lineIndex++];
}
else
return EOF;
}
return lineText[lineIndex++];
}
static void ungetNextChar()
{
--lineIndex;
}
/*
* NAME: getToken()
* PURPOSE: Returns the next token in the source file.
*
* This stuff here is mostly my code. It tokenises valid C- source
* files (rather than Tiny C, like Louden's) and sports a minor
* refinement, in that is uses an automatically-generated minimal
* perfect hash function to determine if identifiers are reserved
* words.
*/
TokenType getToken(void)
{
int tokenIndex = 0; /* index into tokenString */
TokenType currentToken; /* token to be returned */
LexerState state = START; /* FSA state */
int save; /* save char to tokenString? */
int c; /* character under examination */
while (state != DONE)
{
c = getNextChar();
save = TRUE; /* save this character into lexeme by default */
switch(state)
{
case START:
if (isdigit(c))
state = INNUM;
else if (isalpha(c))
state = INID;
else if (c == '/')
state = INDIV;
else if (c == '!')
state = INNE;
else if (c == '<')
state = INLT;
else if (c == '>')
state = INGT;
else if (c == '=')
state = INEQ;
else if ((c == '\n') || (c == '\t') || (c == ' '))
save = FALSE;
else
{
/*
* We can only now have one-character symbols. The state
* machine has to return a symbol, or ERROR.
*/
state = DONE; /* It's almost time for us to bail out */
switch (c)
{
case EOF:
save = FALSE;
currentToken = ENDOFFILE;
break;
case '+':
currentToken = PLUS;
break;
case '-':
currentToken = MINUS;
break;
case '*':
currentToken = TIMES;
break;
case ';':
currentToken = SEMI;
break;
case ',':
currentToken = COMMA;
break;
case '[':
currentToken = LSQUARE;
break;
case ']':
currentToken = RSQUARE;
break;
case '(':
currentToken = LPAREN;
break;
case ')':
currentToken = RPAREN;
break;
case '{':
currentToken = LBRACE;
break;
case '}':
currentToken = RBRACE;
break;
default:
currentToken = ERROR;
break;
} /* switch(c) */
} /* if..then..else */
break;
case INNE:
state = DONE;
if (c == '=')
currentToken = NE;
else
{
/* back up in the input */
ungetNextChar();
save = FALSE;
currentToken = ERROR;
}
break;
case INLT:
state = DONE;
if (c == '=')
currentToken = LTE;
else
{
/*
* Ok, we haven't scanned a <= symbol: put the next char
* back for the next token
*/
ungetNextChar();
save = FALSE;
currentToken = LT;
}
break;
case INGT:
state = DONE;
if (c == '=')
currentToken = GTE;
else
{
/*
* Ok, we haven't scanned a >= symbol: put the next char
* back for the next token
*/
ungetNextChar();
save = FALSE;
currentToken = GT;
}
break;
case INEQ:
state = DONE;
if (c == '=')
currentToken = EQ;
else
{
/*
* Ok, we haven't scanned a <= symbol: put the next char
* back for the next token
*/
ungetNextChar();
save = FALSE;
currentToken = ASSIGN;
}
break;
case INDIV:
if (c == '*')
{
save = FALSE;
state = INCOMMENT;
tokenIndex -=1; /* remove "/" from tokenString */
}
else
{
ungetNextChar();
save = FALSE;
state = DONE;
currentToken = DIVIDE;
}
break;
case INCOMMENT:
save = FALSE;
if (c == '*')
state = INCOMMENT2;
/*
* This next bit of code fixes a bug where the scanner goes into
* an infinite loop if an EOF is encountered inside a comment
*/
else if (c == EOF)
state = ERROR;
break;
case INCOMMENT2:
save = FALSE;
if (c == '/')
state = START;
/*
* BUG FIX: if we're in state INCOMMENT2 and we encounter an
* asterisk, we want to remain in INCOMMENT2 - this becomes
* important when 2 or more astericks are immediately followed
* by a slash....
*/
else if (c == '*')
state = INCOMMENT2; /* no change */
else
state = INCOMMENT;
break;
case INID:
if (!isalpha(c))
{
/* back up */
ungetNextChar();
save = FALSE;
state = DONE;
currentToken = ID;
}
break;
case INNUM:
if (!isdigit(c))
{
/* back up */
ungetNextChar();
save = FALSE;
state = DONE;
currentToken = NUM;
}
break;
case DONE:
default:
fprintf(listing, "<<<SCANNER BUG>>: state = %d\n", state);
state = DONE;
currentToken = ERROR;
break;
} /* switch(state) */
/* Append a character onto the tokenString (if it was asked for) */
if ((save) && (tokenIndex <= MAXTOKENLEN))
tokenString[tokenIndex++] = c;
if (state == DONE)
{
/* null-terminate the string */
tokenString[tokenIndex] = '\0';
if (currentToken == ID)
currentToken = LookupReservedWord(tokenString);
}
} /* while (state != DONE) */
/*
* If we've enabled the TraceScan option, output a detailed trace
* of the lexical scanner's actions.
*/
if (TraceScan)
{
fprintf(listing, "SCAN: %5d: ", lineno);
printToken(currentToken, tokenString);
fprintf(listing, "\n");
}
return currentToken;
}
/* END OF FILE */