在“ Unix编程环境”一书中,该书依赖于为编写“ hoc”这一章中的一个例子(除了其中一个例子)之外的所有例子编写自己的词法分析器。
我真的很想在第一个示例hoc1中使用lex。当我尝试使用lex编写自己的程序时,直到出现语法错误,程序才会输出响应。
该代码可以在Unix编程环境网站上看到 ...
这似乎为我工作:
$ cat hoc1lex.l
%{
extern int lineno;
#define YYSTYPE double
#include "y.tab.h"
%}
%%
[ \t]
\n                                 { lineno++; return('\n'); }
[0-9]*\.[0-9]*([eE][-+][0-9]*)?    { yylval = atof(yytext); return NUMBER; }
[0-9]+([eE][-+][0-9]*)?            { yylval = atof(yytext); return NUMBER; }
.                                  { return *yytext; }
%%
Run Code Online (Sandbox Code Playgroud)
$ diff -u hoc.y hoc1.y
--- hoc.y   1995-06-12 16:30:21.000000000 -0700
+++ hoc1.y  2011-09-18 18:59:02.000000000 -0700
@@ -1,4 +1,5 @@
 %{
+#include <stdio.h>
 #define    YYSTYPE double  /* data type of yacc stack */
 %}
 %token NUMBER
@@ -19,7 +20,6 @@
 %%
    /* end of grammar */
-#include <stdio.h>
 #include <ctype.h>
 char   *progname;  /* for error messages */
 int    lineno = 1;
@@ -31,6 +31,7 @@
    yyparse();
 }
+#if 0
 yylex()        /* hoc1 */
 {
    int c;
@@ -48,6 +49,7 @@
        lineno++;
    return c;
 }
+#endif /* 0 */
 yyerror(s) /* called for yacc syntax error */
    char *s;
Run Code Online (Sandbox Code Playgroud)
$ cat hoc1.mk
YFLAGS = -d
hoc1:   hoc1.o hoc1lex.o
    cc hoc1.o hoc1lex.o -o hoc1 -lfl
hoc1lex.o:  y.tab.h
Run Code Online (Sandbox Code Playgroud)
$ make -f hoc1.mk
yacc -d hoc1.y 
mv -f y.tab.c hoc1.c
cc    -c -o hoc1.o hoc1.c
lex  -t hoc1lex.l > hoc1lex.c
cc    -c -o hoc1lex.o hoc1lex.c
cc hoc1.o hoc1lex.o -o hoc1 -lfl
rm hoc1lex.c hoc1.c
$ ./hoc1
1.2 + 2.3
    3.5
2.3/1.2
    1.9166667
$ 
Run Code Online (Sandbox Code Playgroud)