Flex:尝试使用 Flex 生成 C++ 词法分析器; "unrecognized rule" 错误

Flex: trying to generate a C++ lexer using Flex; "unrecognized rule" error

我正在尝试使用 flex 生成词法分析器。这是我的定义文件 lexer.l:

%{
#include <iostream>

using namespace std;

//#define YY_DECL extern "C" int yylex()
%}

staffType "grand" | "treble" | "bass" | "alto" | "tenor"
upperRomans "I" | "II" | "III" | "IV" | "V" | "VI" | "VII"
lowerRomans "i" | "ii" | "iii" | "iv" | "v" | "vi" | "vii"
quality "dim" | "halfdim" | "aug" | "maj" | "min"

%%

[ \t\n]+ { ; // Ignore arbitrary whitespace. }
{staffType} { cout << "Staff" << endl; }
{upperRomans} { cout << "Upper roman" << endl; }
{lowerRomans} { cout << "Lower roman" << endl; }
"doublebar" { cout << "End of line" << endl; }
. { cout << "Parse error" << endl; }

%%

int main(int, char**) {
    // lex through the input
    yylex();
}

然而,在调用之后:

flex lexer.l

我得到:

lexer.l:18: unrecognized rule
lexer.l:19: unrecognized rule
lexer.l:20: unrecognized rule

我的 flex 版本是 flex 2.5.35 Apple(flex-31)

我做错了什么?

问题出在您的模式中不同标记之间的空格。必须是:

[...]
staffType "grand"|"treble"|"bass"|"alto"|"tenor"
upperRomans "I"|"II"|"III"|"IV"|"V"|"VI"|"VII"
lowerRomans "i"|"ii"|"iii"|"iv"|"v"|"vi"|"vii"
quality "dim"|"halfdim"|"aug"|"maj"|"min"
[...]

写在manpage of flex.

PATTERNS
The patterns in the input are written using an extended set of regular expressions. These are:

[...]
r|s either an r or an s