在 lex 程序中有循环模式动作对的方法吗?
is there a way of looping pattern action pair in lex program?
我想知道是否有在 lex 程序的规则部分循环的方法,我可以在其中迭代模式和动作。
像这样:
%{
char *pattern[] = {a,b,c,d,e}
%}
%%
for(i=0,i<5,i++){
(pattern[1]){action[i]}
}
%%
//Some functions
是否可以进行这样的迭代?
我正在寻找一种方法来编写可以识别所有 C 语言关键字的 lex 程序。
我不确定循环将如何帮助您解决这个问题。 (F)lex 已经循环,重复寻找一个标记,直到某个动作 returns(或者达到 EOF 并且默认的 EOF 动作 returns)。
要识别关键字,只需将关键字写成模式即可:
%{
int keywords = 0;
%}
%option noyywrap
%%
/* List of keywords taken from http://port70.net/~nsz/c/c11/n1570.html#6.4.1 */
auto { ++keywords; }
break { ++keywords; }
case { ++keywords; }
char { ++keywords; }
const { ++keywords; }
continue { ++keywords; }
default { ++keywords; }
do { ++keywords; }
/* Etc. */
[[:alpha:]_][[:alnum:]_]* ; /* Ignore other identifiers */
\.?[[:digit:]]([[:alnum:].]|[EePp][+-])* ; /* And pp-numbers */
/* The next one matches too much; it will cause keywords inside comments
* and quoted strings to be accepted. So you still have some work to do. */
[^[:alnum:]]+ ; /* And everything else */
%%
int main(void) {
yylex();
printf("%d keywords found.\n", keywords);
return 0;
}
如果您需要区分关键字,则需要做一些更复杂的事情。但是一个好的文本编辑器应该能让你把关键字列表转换成任何简单的重复动作,比如
auto { return TOKEN_auto; }
我想知道是否有在 lex 程序的规则部分循环的方法,我可以在其中迭代模式和动作。
像这样:
%{
char *pattern[] = {a,b,c,d,e}
%}
%%
for(i=0,i<5,i++){
(pattern[1]){action[i]}
}
%%
//Some functions
是否可以进行这样的迭代?
我正在寻找一种方法来编写可以识别所有 C 语言关键字的 lex 程序。
我不确定循环将如何帮助您解决这个问题。 (F)lex 已经循环,重复寻找一个标记,直到某个动作 returns(或者达到 EOF 并且默认的 EOF 动作 returns)。
要识别关键字,只需将关键字写成模式即可:
%{
int keywords = 0;
%}
%option noyywrap
%%
/* List of keywords taken from http://port70.net/~nsz/c/c11/n1570.html#6.4.1 */
auto { ++keywords; }
break { ++keywords; }
case { ++keywords; }
char { ++keywords; }
const { ++keywords; }
continue { ++keywords; }
default { ++keywords; }
do { ++keywords; }
/* Etc. */
[[:alpha:]_][[:alnum:]_]* ; /* Ignore other identifiers */
\.?[[:digit:]]([[:alnum:].]|[EePp][+-])* ; /* And pp-numbers */
/* The next one matches too much; it will cause keywords inside comments
* and quoted strings to be accepted. So you still have some work to do. */
[^[:alnum:]]+ ; /* And everything else */
%%
int main(void) {
yylex();
printf("%d keywords found.\n", keywords);
return 0;
}
如果您需要区分关键字,则需要做一些更复杂的事情。但是一个好的文本编辑器应该能让你把关键字列表转换成任何简单的重复动作,比如
auto { return TOKEN_auto; }