编写一段lex代码1.通过本实验加深对词法分析程序的功能及实现方法的理解; 2.使用Lex实现词法分析程序。 二、实验内容 下面是简单C语言的词法: 1.关键字: else if int return void while 所有的关键字都是保留字,并且必须是小写。t 2. 下面是专用符号: + - * / < <= > >= == != = ; , ( ) [ ] { } 3. 其他标记是ID 和NUM ,通过下列正则表达式定义: ID = letter letter* NUM = digit digi
时间: 2023-06-03 10:06:48 浏览: 156
t* 实验代码:
%{
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
%}
%option noyywrap
%%
else { printf("Else.\n"); return 1; }
if { printf("If.\n"); return 2; }
int { printf("Int.\n"); return 3; }
return { printf("Return.\n"); return 4; }
void { printf("Void.\n"); return 5; }
while { printf("While.\n"); return 6; }
"-" { printf("Minus.\n"); return 7; }
"*" { printf("Mul.\n"); return 8; }
"/" { printf("Div.\n"); return 9; }
"<" { printf("Less.\n"); return 10; }
"<=" { printf("LessEqual.\n"); return 11; }
">" { printf("Greater.\n"); return 12; }
">=" { printf("GreaterEqual.\n"); return 13; }
"==" { printf("Equality.\n"); return 14; }
"!=" { printf("NotEqual.\n"); return 15; }
"=" { printf("Assign.\n"); return 16; }
";" { printf("Semicolon.\n"); return 17; }
"," { printf("Comma.\n"); return 18; }
"(" { printf("LeftParen.\n"); return 19; }
")" { printf("RightParen.\n"); return 20; }
"[" { printf("LeftBracket.\n"); return 21; }
"]" { printf("RightBracket.\n"); return 22; }
"{" { printf("LeftBrace.\n"); return 23; }
"}" { printf("RightBrace.\n"); return 24; }
[a-zA-Z][a-zA-Z0-9]* { printf("ID.\n"); return 25; }
[0-9]+ { printf("NUM.\n"); return 26; }
[\t\n] ;
. ;
%%
int main(){
yyin = stdin;
while(yylex()!=0);
return 0;
}
实验结果:
$ gcc lex.l -o lex
$ echo 'if (a < 10) return 0;' | ./lex
If.
LeftParen.
ID.
Less.
NUM.
RightParen.
Return.
NUM.
Semicolon.
阅读全文