最简单的flex & bison例子

y.tab.h

?
/* A Bison parser, made by GNU Bison 2.3.  */
  
/* Skeleton interface for Bison's Yacc-like parsers in C
  
    Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
    Free Software Foundation, Inc.
  
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2, or (at your option)
    any later version.
  
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
  
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.  */
  
/* As a special exception, you may create a larger work that contains
    part or all of the Bison parser skeleton and distribute that work
    under terms of your choice, so long as that work isn't itself a
    parser generator using the skeleton or a modified version thereof
    as a parser skeleton.  Alternatively, if you modify or redistribute
    the parser skeleton itself, you may (at your option) remove this
    special exception, which will cause the skeleton and the resulting
    Bison output files to be licensed under the GNU General Public
    License without this special exception.
  
    This special exception was added by the Free Software Foundation in
    version 2.2 of Bison.  */
  
/* Tokens.  */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
    /* Put the tokens into the symbol table, so that GDB and other debuggers
       know about them.  */
    enum yytokentype {
      DIGIT = 258,
      LOWERCASELETTER = 259,
      UPPERCASELETTER = 260,
      OTHER = 261,
      STOP = 262
    };
#endif
/* Tokens.  */
#define DIGIT 258
#define LOWERCASELETTER 259
#define UPPERCASELETTER 260
#define OTHER 261
#define STOP 262
  
  
  
  
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef int YYSTYPE;
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
# define YYSTYPE_IS_TRIVIAL 1
#endif
  
extern YYSTYPE yylval;

token.l

?
/*
  * Copyright (c) 2009-2010, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are met:
  *
  * * Redistributions of source code must retain the above copyright notice,
  *   this list of conditions and the following disclaimer.
  *
  * * Redistributions in binary form must reproduce the above copyright notice,
  *   this list of conditions and the following disclaimer in the documentation
  *   and/or other materials provided with the distribution.
  *
  * * Neither the name of Oracle nor the names of its contributors
  *   may be used to endorse or promote products derived from this software without
  *   specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
  
%{
#include "y.tab.h"
%}
%%
"q"   return STOP;
"Q"   return STOP;
[0-9] return DIGIT;
[a-z] return LOWERCASELETTER;
[A-Z] return UPPERCASELETTER;
.     return OTHER;
%%

token.y

 

?
/*
  * Copyright (c) 2009-2010, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are met:
  *
  * * Redistributions of source code must retain the above copyright notice,
  *   this list of conditions and the following disclaimer.
  *
  * * Redistributions in binary form must reproduce the above copyright notice,
  *   this list of conditions and the following disclaimer in the documentation
  *   and/or other materials provided with the distribution.
  *
  * * Neither the name of Oracle nor the names of its contributors
  *   may be used to endorse or promote products derived from this software without
  *   specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
  
%{
#include <stdio.h>
%}
  
%token DIGIT LOWERCASELETTER UPPERCASELETTER OTHER STOP
  
%%
start :
     | start something
     ;
  
something : DIGIT { printf ( "DIGIT\n" );}
     | LOWERCASELETTER { printf ( "LOWERCASELETTER\n" );}
     | UPPERCASELETTER { printf ( "UPPERCASELETTER\n" );}
     | OTHER { printf ( "OTHER\n" );}
     | STOP { exit (0);}
     ;
%%
  
main()
{
     // Intro
     printf ( "Type something followed by Return. Type 'q' or 'Q' to end.\n" );
     printf ( "\n" );
     // Start the parser
     return (yyparse());
}
  
yyerror(s)
char *s;
{
     printf ( "yacc error: %s\n" , s);
}
  
yywrap()
{
     return (0);
}

运行命令:flex token.l

会得到文件:lex.yy.c

运行命令:bison token.y

会得到文件: token.tab.c

运行命令:gcc *

会得到文件 a.out

完成

&lt;think&gt;嗯,用户想知道如何在Windows环境下配置使用FlexBison。首先,我需要回忆一下之前看到的引用内容。引用[1]提到MSBuild配置,但用户可能不需要这个,他们可能更关心环境变量设置。引用[2][4]都提到了在系统变量Path中添加win_flexwin_bison的路径,这应该是关键步骤。引用[3]提到了官网下载GCC、BisonFlex,但可能用户更倾向于使用预编译的Windows版本,比如win-flex-bison。 首先,用户可能需要下载工具。有两种方法:一种是直接下载win-flex-bison,另一种是从GNU官网下载然后配置。根据引用[2][4],推荐使用win-flex-bison,因为这样更方便,不需要自己编译。然后,安装后需要配置环境变量,把安装目录下的bin文件夹路径添加到系统变量Path中。步骤应该是:下载解压,找到bin路径,添加到Path,然后验证安装。 然后,使用部分需要示例。用户可能需要一个简单的例子,比如计算器,来测试FlexBison是否正常工作。需要编写lex.lparse.y文件,然后用flexbison生成C代码,最后用gcc编译。引用中的例子可能不够详细,但用户需要具体的步骤,比如命令行的执行顺序:flex lex.l生成lex.yy.c,bison -d parse.y生成parse.tab.cparse.tab.h,然后gcc编译链接。 需要注意的地方是,用户可能没有安装gcc,所以需要提醒他们安装MinGW或者其他的C编译器。另外,路径中如果有空格需要用引号括起来,或者建议路径不要有空格。还有,在测试例子的时候,要确保输入文件正确,比如input.txt,并指导用户如何运行生成的可执行文件。 可能的问题包括环境变量未生效,这时候需要提醒用户重启命令行或者编辑器。另外,如果flexbison命令找不到,可能是路径配置错误,需要检查Path是否正确。还有,编译时的链接错误,可能需要检查库是否正确安装,或者是否遗漏了-lfl等选项。 最后,生成相关问题的时候,要考虑用户接下来可能会问的问题,比如如何处理语法冲突,如何调试,或者如何集成到IDE中。因此,相关问题可以包括这些方面。&lt;/think&gt;### 分步指南:Windows环境下配置使用Flex/Bison #### 一、工具安装与环境配置 1. **下载win-flex-bison工具包** - 访问[Github win-flex-bison发布页](https://github.com/lexxmark/winflexbison/releases),下载最新版本的`win-flex-bison-2.5.24.zip`[^2][^4] - 解压到无空格路径的文件夹,例如:`C:\devtools\win_flex_bison` 2. **配置系统环境变量** - 右键&ldquo;此电脑&rdquo; &rarr; 属性 &rarr; 高级系统设置 &rarr; 环境变量 - 在**系统变量**中找到`Path` &rarr; 编辑 &rarr; 新建 &rarr; 添加路径`C:\devtools\win_flex_bison`[^4] - 验证安装:打开CMD执行 ```bash win_flex --version win_bison --version ``` #### 二、开发环境准备 1. **安装C编译器** - 推荐使用MinGW-w64([下载地址](http://mingw-w64.org/doku.php)) - 安装时勾选`gcc-core``gcc-g++`组件 2. **项目目录结构示例** ```bash myproject/ ├── lexer.l # Flex词法规则 ├── parser.y # Bison语法规则 └── main.c # 主程序 ``` #### 三、实际使用示例(实现计算器) 1. **编写lexer.l词法分析器** ```lex %{ #include &quot;parser.tab.h&quot; %} %% [0-9]+ { yylval = atoi(yytext); return NUMBER; } &quot;+&quot; { return ADD; } &quot;-&quot; { return SUB; } &quot;*&quot; { return MUL; } &quot;/&quot; { return DIV; } \n { return EOL; } [ \t] ; /* 忽略空白 */ %% ``` 2. **编写parser.y语法分析器** ```bison %{ #include &lt;stdio.h&gt; int yylex(); void yyerror(char *s); %} %token NUMBER ADD SUB MUL DIV EOL %% calc: | calc line ; line: EOL | exp EOL { printf(&quot;Result: %d\n&quot;, $1); } ; exp: NUMBER { $$ = $1; } | exp ADD exp { $$ = $1 + $3; } | exp SUB exp { $$ = $1 - $3; } | exp MUL exp { $$ = $1 * $3; } | exp DIV exp { $$ = $1 / $3; } ; %% void yyerror(char *s) { fprintf(stderr, &quot;Error: %s\n&quot;, s); } int main() { yyparse(); return 0; } ``` 3. **编译与运行** ```bash win_bison -d parser.y # 生成parser.tab.cparser.tab.h win_flex lexer.l # 生成lex.yy.c gcc -o calculator *.c # 编译生成可执行文件 ./calculator &lt; input.txt # 测试输入文件 ``` #### 四、常见问题处理 1. **&quot;flex: command not found&quot;** - 检查环境变量是否包含win_flex_bison路径 - 确认CMD窗口在配置后重新启动 2. **undefined reference to `yylex&#39;** - 确保lexer.l包含`#include &quot;parser.tab.h&quot;` - 检查bison生成的token定义是否匹配 3. **提高兼容性** - 在lexer.l开头添加`%option noyywrap` - 使用`win_flex --noyywrap`参数生成代码[^4]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值