2013-06-22 57 views
0

我想用Flex生成一个简单的扫描仪。但是,当使用下面的代码时,我在第23,24和25行中得到了多个“无法识别的规则”错误。在研究了一些类似的例子之后,我仍然找不到任何格式错误。有人能请我指出正确的方向吗?使用Flex生成扫描仪时出错(无法识别的规则)

%{ 
#include <stdio.h> 
#include "mylang3.tab.h" 
#include <stdlib.h> 
#include <string.h> 
#define OK 234 
#define ILLEGAL 235 
%} 

digit  [0-9] 
letter  [a-zA-Z] 
invalid_id [char|else|if|class|new|return|void|while] 
unsigned_int ({digit}+) 
INTEGER  ((+|-)?{unsigned_int}) 
all_chars [{letter}{digit}_] 
ID    ([({all_chars}{-}{digit})({all_chars})*]{-}{invalid_id}) 
special_char ["\n"|"\""|"\'"|"\0"|"\t"|"\\"] 
CHARACTER '([[:print:]]{-}["']{+}{special_char})' 


%% 
[a-zA-Z]+   printf("I have found a word %s\n", yytext); 
{ID}    printf("I have found an id %s\n", yytext);  //errors 
{INTEGER}   printf("I have found an integer %s\n",yytext); //errors 
{CHARACTER}   printf("I have found a char %s\n",yytext);  //errors 
char|else|if|class|new|return|void|while printf("I have found a reserved word %s\n",yytext); 
"+"|"-"|"*"|"/"|"{"|"}"|"("|")"|"["|"]"  printf("I have found an operator: %s\n", yytext); 
[" " \t\n]+     /* eat up whitespace */ 
.      printf("Unrecognized character: %s\n", yytext); 


%% 

/*int main(int argc, char** argv){ 
    int token; 
    int ok=1; 
    ++argv, --argc; 

    if (argc > 0) 
    yyin = fopen(argv[0], "r"); 
    else 
    yyin = stdin; 
    yylex(); 

    while((token =yylex())!=0){ 
     if(token==ILLEGAL){ printf("Illegal sequence\n"); ok=0; } 
    } 
    if(ok==0) printf("Encountered lexical errors\n"); 
    else printf("No lexical errors found\n"); 
    return 0; 
}*/ 

回答

0

只能使用方括号表示字符,而不能使用字符序列。所以,而不是电子。 G。

all_chars [{letter}{digit}_] 

你得写

all_chars ({letter}|{digit}|_) 

,你不应该混合管道标志和方括号。 [abc]表示与(a | b | c)相同,但[a | b | c]错误。