Skip to content

Instantly share code, notes, and snippets.

@LeslieZhu
Created January 2, 2014 18:46
Show Gist options
  • Save LeslieZhu/8224306 to your computer and use it in GitHub Desktop.
Save LeslieZhu/8224306 to your computer and use it in GitHub Desktop.
Lex输入文件,将C语言中注释之外的保留字转换为大写。习题2.23
%option noyywrap
types auto|enum|unsigned|void|float|short|volatile|char|signed|const|int|double|long
control break|return|case|for|while|goto|continue|if|do|switch|else
other extern|sizeof|static|default|struct|typedef|register|union
keywords {types}|{control}|{other}
prefix [ \,\;\{\}\(\)\t\n\#]
suffix [ \,\;\{\}\(\)\t\n\:\*]
/*
prefix [^a-zA-Z0-9_]
suffix [^a-zA-Z0-9_]
*/
/*
%{
int inComment = 0;
%}
*/
%%
"/*" ECHO;{
register int c,prev_c;
//inComment = 1;
for ( ; ; ){
while ( (c = input()) != '*' && c != EOF ){
printf("%c",c);
}
if ( c == '*' ){
printf("%c",c);
prev_c = c;
while ( prev_c == '*' && (c = input()) != '/' ){
printf("%c",c);
prev_c = c;
break;
}
if ( c == '/' ){
printf("/");
//inComment = 0;
break; /* found the end */
}
}
if ( c == EOF ){
error( "EOF in comment" );
break;
}
}
}
"//" ECHO;{
register int c;
//inComment = 1;
for ( ; ; ){
while ( (c = input()) != '\n' && c != EOF ){
printf("%c",c);
}
if(c == '\n'){
printf("\n");
//inComment = 0;
break;
}
if ( c == EOF ) {
error( "EOF in comment" );
break;
}
}
}
{prefix}{keywords}/{suffix} |
^{keywords}/{suffix} {
while(*yytext != '\0'){
printf("%c",toupper(*yytext++));
}
}
%%
void main(){
yylex();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment