7

我们刚刚开始使用 flex 为项目构建词法分析器,但我们不知道如何让它工作。我复制了教程中给出的示例代码,并尝试使用 tut 文件作为参数运行 flex++,但是每次我都收到一个错误。例如

输入文件(calc.l)

%name Scanner
%define IOSTREAM

DIGIT   [0-9]
DIGIT1  [1-9]

%%

"+"               { cout << "operator <" << yytext[0] << ">" << endl; }
"-"               { cout << "operator <" << yytext[0] << ">" << endl; }
"="               { cout << "operator <" << yytext[0] << ">" << endl; }
{DIGIT1}{DIGIT}*  { cout << "  number <" << yytext    << ">" << endl; }
.                 { cout << " UNKNOWN <" << yytext[0] << ">" << endl; }

%%

int main(int argc, char ** argv)
{
    Scanner scanner;
    scanner.yylex();
    return 0;
}

有了这段代码,我得到了

flex++ calc.l
calc.l:1: bad character: % calc.l:1: 未知错误处理部分1
calc.l:1: 未知错误处理部分1
calc.l:1: 未知错误处理部分1
calc.l :2: 无法识别的 '%' 指令

谁能帮我理解我在这里做错了什么?干杯

4

2 回答 2

3

您可以尝试以下方法:

  • 添加%{ ... %}到文件的前几行
  • 添加#include <iostream>using namespace std; (而不是尝试定义扫描仪)
  • 在规则部分%option noyywrap上方添加
  • 仅使用yylex() (而不是尝试调用不存在的 Scanner 的方法)

以您的示例为例,它可能看起来像这样:

%{
#include <iostream>
using namespace std;
%}

DIGIT   [0-9]
DIGIT1  [1-9]

/* read only one input file */
%option noyywrap

%%
"+"               { cout << "operator <" << yytext[0] << ">" << endl; }
"-"               { cout << "operator <" << yytext[0] << ">" << endl; }
"="               { cout << "operator <" << yytext[0] << ">" << endl; }
{DIGIT1}{DIGIT}*  { cout << "  number <" << yytext    << ">" << endl; }
.                 { cout << " UNKNOWN <" << yytext[0] << ">" << endl; }
%%

int main(int argc, char** argv)
{
    yylex();
    return 0;
}
于 2013-03-14T16:26:26.863 回答
0

您使用的 flex++ 版本是什么?我使用“功能:快速词法分析器生成器 C/C++ V2.3.8-7 (flex++),基于 2.3.8 并由 coetmeur@icdc.fr 为 c++ 修改”(-? 选项)并且您的 cacl.c 得到了完美处理..

对于 Win32,这个版本的 Flex++/Bison++ 在这里

于 2013-08-28T08:05:34.383 回答