-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcdecl.c
More file actions
536 lines (441 loc) · 10.6 KB
/
cdecl.c
File metadata and controls
536 lines (441 loc) · 10.6 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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
/**
* @file cdecl.c
* @author Aliaksiej Artamonaŭ <aliaksiej.artamonau@gmail.com>
* @date Sun Jul 25 16:07:11 2010
*
* @brief A program that descrypts C type declarations. Implemented as
* an exercise for "Expert C Programming" book.
*
* Not very intelligent (most of incorrect declarations are accepted with no
* errors) program pronouncing C declarations.
*/
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdarg.h>
#include <stdbool.h>
/// Maximum length of the token that can be handled.
#define MAX_TOKEN_LEN 64
/// Maximum number of tokens that can be handled.
#define MAX_TOKENS 128
/// Defines possible tokens types.
enum token_type_t {
TYPE, /**< type declaration */
SPECIFIER, /**< type specifier */
IDENTIFIER, /**< identifier */
ARRAY, /**< array */
POINTER, /**< pointer */
LBRACE, /**< left brace */
RBRACE, /**< right brace */
END, /**< declaration finishied */
};
/**
* Transforms #token_type_t to its string representation.
*
* @param type type
*
* @return A string corresponding to a type.
*/
const char *
token_to_str(enum token_type_t type)
{
static char *strs[] = { "TYPE",
"SPECIFIER",
"IDENTIFIER",
"ARRAY",
"POINTER",
"LBRACE",
"RBRACE",
"END" };
return strs[type];
}
/// Number of additional place should be allocated by
/// #token_t::info::size to store possible @e struct or
/// @e enum prefix.
#define STRUCT_ENUM_ADDENDUM 7
/// Token;
struct token_t {
enum token_type_t type; /**< type of the token */
union {
char name[STRUCT_ENUM_ADDENDUM + MAX_TOKEN_LEN + 1]; /**< string
representation
of the token */
int size; /**< if ::type is #ARRAY then it's the size
* of array (or -1 in case size has not been
* specified) */
} info;
};
static int line = 1; /**< current line being processed */
static int position = 0; /**< current position in the line */
static struct token_t token; /**< current token */
static struct token_t stack[MAX_TOKENS]; /**< stack of tokens to the left from
* curent one*/
static int head = 0; /**< head of the #stack */
static bool verbose = false; /**< behave verbosely */
/**
* Prints a message about fatal condition and exits with #EXIT_FAILURE exit
* code.
*
* @param format Printf-like format string.
*/
void
fatal(const char *format, ...)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
exit(EXIT_FAILURE);
}
/**
* A variant of fatal() function that additionaly prints current line and
* position.
*
* @param format Printf-like format string.
*/
#define fatal_pos(format, ...) \
fatal("Line: %d, Position: %d: " format, line, position, #__VA_ARGS__)
/**
* Pushes a token to the #stack.
*
* @param token token
*/
static void
stack_push(const struct token_t *token)
{
if (head >= MAX_TOKENS) {
fatal("Too long declaration. Can't proceed.\n");
}
stack[head++] = *token;
}
/**
* Pops a token from the #stack.
*
*
* @return token
*/
static struct token_t
stack_pop(void)
{
/* can be a programming error actually */
if (head == 0) {
fatal("Stack underflow. Invalid declaration.\n");
}
return stack[--head];
}
/**
* Determines whether #stack is empty.
*
*
* @retval true Stack is empty.
* @retval false Stack is not empty.
*/
static bool
stack_is_empty(void)
{
return head == 0;
}
/**
* Wrapper for getchar() function which keeps #line and #position consistent.
*
*
* @retval EOF No input left.
* @retval char A character that had been read.
*/
int
_getchar()
{
int c = getchar();
if (c != EOF) {
++position;
if (c == '\n') {
++line;
position = 0;
}
}
return c;
}
/**
* Wrapper for #ungetc function which keeps #position and #line consistent.
*
* @param c Character to return to stdin. It's not a good idea for it to be
* '\n' as then #line and #position would contain incorrect values.
*/
void
_ungetchar(int c)
{
if (ungetc(c, stdin) != c) {
fatal("Unrecoverable IO error occurred.\n");
}
--position;
}
/**
* Skip all the space characters in stdin.
*
*/
void
skip_spaces(void)
{
int c;
while ((c = getchar()) != EOF) {
if (!isspace(c)) {
_ungetchar(c);
return;
}
}
fatal_pos("Unexpected end of file\n");
}
/**
* Reads identifier from @e stdin.
*
* @param[out] id A place to store the result. At most #MAX_TOKEN_LEN + 1 bytes
* will be used.
*
* @return A pointer to #id parameter.
*/
char *
get_id(char *id)
{
int i = 0;
char *p = id;
/* it's guaranteed by the caller that the first character in stdin is a
* letter */
while (1) {
int c = _getchar();
if (c == EOF) {
fatal_pos("Unexpected end of file\n");
} else if (isalnum(c) || c == '_') {
if (i++ >= MAX_TOKEN_LEN) {
fatal_pos("Too long token occured. Can't proceed.\n");
}
*p++ = c;
} else {
_ungetchar(c);
*p = '\0';
return id;
}
}
}
/**
* Skips all the input until specifies character is occured.
*
* @param c A character to wait for.
*/
void
skip_to_char(char end)
{
while (1) {
int c = _getchar();
if (c == EOF) {
fatal_pos("Unexpected end of file\n");
} else if (c == end) {
return;
}
}
}
/**
* If #verbose is @e true then dumps an information about current token to
* @e stderr.
*
*/
static void
dump_token(void)
{
if (verbose) {
fprintf(stderr, "token: %s", token_to_str(token.type));
switch (token.type) {
case TYPE:
case SPECIFIER:
case IDENTIFIER:
fprintf(stderr, ", %s\n", token.info.name);
break;
default:
/* just new line */
fprintf(stderr, "\n");
}
}
}
/**
* Reads token from @e stdin and stores it in #token.
*
*/
void
get_token()
{
skip_spaces();
int c = getchar();
++position;
if (c == EOF) {
fatal_pos("Unexpected end of file\n");
} else if (c == ';') {
token.type = END;
} else if (isalpha(c)) {
/* alias */
char *name = token.info.name;
/* some type, specifier or declarator starts here */
_ungetchar(c);
get_id(name);
if (strcmp(name, "int") == 0 ||
strcmp(name, "char") == 0 ||
strcmp(name, "void") == 0 ||
strcmp(name, "signed") == 0 ||
strcmp(name, "unsigned") == 0 ||
strcmp(name, "short") == 0 ||
strcmp(name, "long") == 0 ||
strcmp(name, "float") == 0 ||
strcmp(name, "double") == 0)
{
token.type = TYPE;
} else if (strcmp(name, "struct") == 0 ||
strcmp(name, "enum") == 0) {
token.type = TYPE;
skip_spaces();
/* if structure or enum is defined in place then just skip the
* definition */
int tmp = _getchar();
if (tmp == '{') {
skip_to_char('}');
} else {
size_t len = strlen(name);
name[len] = ' ';
_ungetchar(tmp);
get_id(name + len + 1);
}
} else if (strcmp(name, "const") == 0 ||
strcmp(name, "volatile") == 0)
{
token.type = SPECIFIER;
} else {
token.type = IDENTIFIER;
}
} else if (c == '[') {
skip_to_char(']');
token.type = ARRAY;
/* for now all arrays are without size */
token.info.size = -1;
} else if (c == '(') {
token.type = LBRACE;
} else if (c == ')') {
token.type = RBRACE;
} else if (c == '*') {
token.type = POINTER;
} else {
fatal_pos("Unexpected token encountered\n");
}
dump_token();
}
/**
* Pronounces single token.
*
* @param token A token to pronounce.
*/
static void
pronounce_token(const struct token_t *token)
{
switch (token->type) {
case TYPE:
printf("%s ", token->info.name);
break;
case SPECIFIER:
if (strcmp(token->info.name, "const") == 0) {
printf("read-only ");
} else {
printf("%s ", token->info.name);
}
break;
case ARRAY:
printf("array of ");
break;
case POINTER:
printf("pointer to ");
break;
case LBRACE:
printf("function returning ");
break;
case RBRACE:
case END:
/* just keeping silence */
break;
default:
assert(0);
}
}
/**
* Tries to "pronounce" @e C declaration read from @e stdin in
* human-understandable form.
*
*/
static void
pronounce(void)
{
do {
get_token();
stack_push(&token);
} while (token.type != IDENTIFIER);
/* popping identifier */
stack_pop();
printf("%s is ", token.info.name);
/* whether input to the right of identifier is finished */
bool right_finished = false;
bool left_finished = false;
while (true) {
/* right pass */
if (!right_finished) {
do {
get_token();
pronounce_token(&token);
/* skiping function argument */
if (token.type == LBRACE) {
do {
get_token();
} while (token.type != RBRACE);
/* faking token type to proceed to the right */
token.type = LBRACE;
}
} while (token.type != END &&
token.type != RBRACE);
/* we reached the end of input */
if (token.type == END) {
right_finished = true;
}
}
/* left pass */
if (!left_finished) {
struct token_t left_token;
do {
left_token = stack_pop();
/* left brace should not be pronounced as "function" */
if (left_token.type != LBRACE) {
pronounce_token(&left_token);
}
} while (!stack_is_empty() &&
left_token.type != LBRACE);
if (stack_is_empty()) {
left_finished = true;
}
}
if (left_finished && right_finished) {
break;
}
}
printf("\n");
}
int
main(int argc, char *argv[])
{
if (argc > 2) {
fatal("%s: wrong number of arguments given\n", argv[0]);
}
if (argc == 2) {
if (strcmp(argv[1], "--verbose") == 0 ||
strcmp(argv[1], "-v") == 0) {
verbose = true;
} else {
fatal("%s: invalid argument (%s)\n", argv[0], argv[1]);
}
}
pronounce();
return EXIT_SUCCESS;
}