【发布时间】:2018-03-17 01:15:41
【问题描述】:
两天来我一直在绞尽脑汁想弄清楚程序为什么会这样。对于一个类项目,我正在尝试编写一个解析地址并以某种方式输出的程序。在我真正进入程序的输出部分之前,我只是想确保我的 Bison-fu 实际上是正确的并正确输出了一些调试信息。
看起来 Flex 和 Bison 像预期的那样很好地相互合作,但由于某种原因,当我解析地址的第三行时,yytext 只是跳过邮政编码直接进入新行。
以下是我测试过的 Flex 和 Bison 文件的精简版本,但仍输出与完整版本相同的内容:
[19:45]<Program4> $ cat scan.l
%option noyywrap
%option nounput
%option noinput
%{
#include <stdlib.h>
#include "y.tab.h"
#include "program4.h"
%}
%%
[\ \t]+ { /* Eat whitespace */}
[\n] { return EOLTOKEN; }
"," { return COMMATOKEN; }
[0-9]+ { return INTTOKEN; }
[A-Za-z]+ { return NAMETOKEN; }
[A-Za-z0-9]+ { return IDENTIFIERTOKEN; }
%%
/*This area just occupies space*/
[19:45]<Program4> $ cat parse.y
%{
#include <stdlib.h>
#include <stdio.h>
#include "program4.h"
%}
%union {int num; char id[20]; }
%start locationPart
%expect 0
%token <num> NAMETOKEN
%token <num> EOLTOKEN
%token <num> INTTOKEN
%token <num> COMMATOKEN
%type <id> townName zipCode stateCode
%%
/* Entire block */
locationPart: townName COMMATOKEN stateCode zipCode EOLTOKEN
{ printf("Rule 12: LP: TN COMMA SC ZC EOL: %s\n", yytext); }
| /* bad location part */
{ printf("Rule 13: LP: Bad location part: %s\n", yytext); }
;
/* Lil tokens */
townName: NAMETOKEN
{ printf("Rule 23: TN: NAMETOKEN: %s\n", yytext); }
;
stateCode: NAMETOKEN
{ printf("Rule 24: SC: NAMETOKEN: %s\n", yytext); }
;
zipCode: INTTOKEN DASHTOKEN INTTOKEN
{ printf("Rule 25: ZC: INT DASH INT: %s\n", yytext); }
| INTTOKEN
{ printf("Rule 26: ZC: INT: %s\n", yytext); }
;
%%
int yyerror (char const *s){
extern int yylineno; //Defined in lex
fprintf(stderr, "ERROR: %s at symbol \"%s\"\n at line %d.\n", s, yytext,
yylineno);
exit(1);
}
[19:45]<Program4> $ cat addresses/zip.txt
Rockford, HI 12345
[19:45]<Program4> $ parser < addresses/zip.txt
Operating in parse mode.
Rule 23: TN: NAMETOKEN: Rockford
Rule 24: SC: NAMETOKEN: HI
Rule 26: ZC: INT:
Rule 12: LP: TN COMMA SC ZC EOL:
Parse successful!
[19:46]<Program4> $
正如您在底部附近看到的那样,它打印 Rule 26: ZC: INT: 但无法打印 5 位数的邮政编码。就像程序只是跳过数字并存储换行符一样。任何想法为什么它不会存储和打印邮政编码?
注意事项:
- yytext 在我的 .h 文件中被定义为外部变量(此处未发布);
- 我正在使用
-vdy标志来编译 parse.c 文件
【问题讨论】:
标签: c linux bison flex-lexer