【问题标题】:Error when using Flex to generate a scanner (unrecognised rule)使用 Flex 生成扫描仪时出错(无法识别的规则)
【发布时间】:2013-06-22 15:01:39
【问题描述】:

我正在尝试使用 Flex 生成一个简单的扫描仪。但是,在使用以下代码时,我在第 23,24 和 25 行收到多个“无法识别的规则”错误。研究了一些类似的示例后,我仍然找不到任何格式错误。有人可以指点我正确的方向吗?

%{ 
#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;
}*/

【问题讨论】:

    标签: flex-lexer lexical-analysis rule


    【解决方案1】:

    方括号只能用于字符,不能用于字符序列。所以代替e。 g.

    all_chars   [{letter}{digit}_]
    

    你必须写

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

    而且您不应该混合使用管道符号和方括号。 [abc] 和 (a|b|c) 意思一样,但是 [a|b|c] 是错误的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-23
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      相关资源
      最近更新 更多