| 1 |
/* |
| 2 |
* string1.lex: Handling strings by using input() |
| 3 |
*/ |
| 4 |
|
| 5 |
%{ |
| 6 |
#include <ctype.h> |
| 7 |
#include <malloc.h> |
| 8 |
|
| 9 |
#define ALLOC_SIZE 32 /* for (re)allocating the buffer */ |
| 10 |
|
| 11 |
#define isodigit(x) ((x) >= '0' && (x) <= '7') |
| 12 |
#define hextoint(x) (isdigit((x)) ? (x) - '0' : ((x) - 'A') + 10) |
| 13 |
|
| 14 |
void yyerror(char *message) |
| 15 |
{ |
| 16 |
printf("\nError: %s\n",message); |
| 17 |
} |
| 18 |
|
| 19 |
%} |
| 20 |
|
| 21 |
%% |
| 22 |
|
| 23 |
\" { |
| 24 |
int inch,count,max_size; |
| 25 |
char *buffer; |
| 26 |
int temp; |
| 27 |
|
| 28 |
buffer = malloc(ALLOC_SIZE); |
| 29 |
max_size = ALLOC_SIZE; |
| 30 |
inch = input(); |
| 31 |
count = 0; |
| 32 |
while(inch != EOF && inch != '"' && inch != '\n'){ |
| 33 |
if(inch == '\\'){ |
| 34 |
inch = input(); |
| 35 |
switch(inch){ |
| 36 |
case '\n': inch = input(); break; |
| 37 |
case 'b' : inch = '\b'; break; |
| 38 |
case 't' : inch = '\t'; break; |
| 39 |
case 'n' : inch = '\n'; break; |
| 40 |
case 'v' : inch = '\v'; break; |
| 41 |
case 'f' : inch = '\f'; break; |
| 42 |
case 'r' : inch = '\r'; break; |
| 43 |
case 'X' : |
| 44 |
case 'x' : inch = input(); |
| 45 |
if(isxdigit(inch)){ |
| 46 |
temp = hextoint(toupper(inch)); |
| 47 |
inch = input(); |
| 48 |
if(isxdigit(inch)){ |
| 49 |
temp = (temp << 4) + hextoint(toupper(inch)); |
| 50 |
} else { |
| 51 |
unput(inch); |
| 52 |
} |
| 53 |
inch = temp; |
| 54 |
} else { |
| 55 |
unput(inch); |
| 56 |
inch = 'x'; |
| 57 |
} |
| 58 |
break; |
| 59 |
default: |
| 60 |
if(isodigit(inch)){ |
| 61 |
temp = inch - '0'; |
| 62 |
inch = input(); |
| 63 |
if(isodigit(inch)){ |
| 64 |
temp = (temp << 3) + (inch - '0'); |
| 65 |
} else { |
| 66 |
unput(inch); |
| 67 |
goto done; |
| 68 |
} |
| 69 |
inch = input(); |
| 70 |
if(isodigit(inch)){ |
| 71 |
temp = (temp << 3) + (inch - '0'); |
| 72 |
} else { |
| 73 |
unput(inch); |
| 74 |
} |
| 75 |
done: |
| 76 |
inch = temp; |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
buffer[count++] = inch; |
| 81 |
if(count >= max_size){ |
| 82 |
buffer = realloc(buffer,max_size + ALLOC_SIZE); |
| 83 |
max_size += ALLOC_SIZE; |
| 84 |
} |
| 85 |
inch = input(); |
| 86 |
} |
| 87 |
if(inch == EOF || inch == '\n'){ |
| 88 |
yyerror("Unterminated string."); |
| 89 |
} |
| 90 |
buffer[count] = '\0'; |
| 91 |
printf("String = \"%s\"\n",buffer); |
| 92 |
free(buffer); |
| 93 |
} |
| 94 |
. |
| 95 |
\n |
| 96 |
%% |
| 97 |
|
| 98 |
|