bison(yacc)中关于calc的一个C++版实现

2024-03-14 23:58
文章标签 c++ 实现 calc yacc bison

本文主要是介绍bison(yacc)中关于calc的一个C++版实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

bison中一个calc的C++版实现,区别于传统的C语言实现,我这边整理了一个可编译的版本用以参考

calc++-driver.h

#ifndef CALCXX_DRIVER_HH
# define CALCXX_DRIVER_HH
# include <string>
# include <map>
# include "calc++-parser.h"// Tell Flex the lexer's prototype ...
# define YY_DECL										\yy::calcxx_parser::token_type						\yylex (yy::calcxx_parser::semantic_type* yylval,	\yy::calcxx_parser::location_type* yylloc,			\calcxx_driver& driver)// ... and declare it for the parser's sake.
YY_DECL;// Conducting the whole scanning and parsing of Calc++.
class calcxx_driver
{
public:calcxx_driver ();virtual ~calcxx_driver ();std::map<std::string, int> variables;int result;// Handling the scanner.void scan_begin ();void scan_end ();bool trace_scanning;// Run the parser.  Return 0 on success.int parse (const std::string& f);std::string file;bool trace_parsing;// Error handling.void error (const yy::location& l, const std::string& m);void error (const std::string& m);
};
#endif // ! CALCXX_DRIVER_HH

calc++-driver.cpp

#include "calc++-driver.h"
#include "calc++-parser.h"calcxx_driver::calcxx_driver (): trace_scanning (false), trace_parsing (false)
{variables["one"] = 1;variables["two"] = 2;
}calcxx_driver::~calcxx_driver ()
{
}int
calcxx_driver::parse (const std::string &f)
{file = f;scan_begin ();yy::calcxx_parser parser (*this);parser.set_debug_level (trace_parsing);int res = parser.parse ();scan_end ();return res;
}void
calcxx_driver::error (const yy::location& l, const std::string& m)
{std::cerr << l << ": " << m << std::endl;
}void
calcxx_driver::error (const std::string& m)
{std::cerr << m << std::endl;
}

calc++-scanner.l

%{ /* -*- C++ -*- */
# include <cstdlib>
# include <cerrno>
# include <climits>
# include <string>
# include "calc++-driver.h"
# include "calc++-parser.h"/* Work around an incompatibility in flex (at least versions2.5.31 through 2.5.33): it generates code that doesnot conform to C89.  See Debian bug 333231<http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>.  */
# undef yywrap
# define yywrap() 1/* By default yylex returns int, we use token_type.Unfortunately yyterminate by default returns 0, which isnot of token_type.  */
#define yyterminate() return token::END
%}%option noyywrap nounput batch debug nounistd never-interactiveid    [a-zA-Z][a-zA-Z_0-9]*
int   [0-9]+
blank [ \t]%{
# define YY_USER_ACTION  yylloc->columns (yyleng);
%}
%%
%{yylloc->step ();
%}
{blank}+   yylloc->step ();
[\n]+      yylloc->lines (yyleng); yylloc->step ();%{typedef yy::calcxx_parser::token token;
%}/* Convert ints to the actual type of tokens.  */
[-+*/]	return yy::calcxx_parser::token_type (yytext[0]);":="	return token::ASSIGN;{int}	{errno = 0;long n = strtol (yytext, NULL, 10);if (! (INT_MIN <= n && n <= INT_MAX && errno != ERANGE))driver.error (*yylloc, "integer is out of range");yylval->ival = n;return token::NUMBER;}{id}	{yylval->sval = new std::string (yytext);return token::IDENTIFIER;}.		driver.error (*yylloc, "invalid character");
%%
void
calcxx_driver::scan_begin ()
{yy_flex_debug = trace_scanning;if (file.empty () || file == "-")yyin = stdin;else if (!(yyin = fopen (file.c_str (), "r"))){error ("cannot open " + file + ": " + strerror(errno));exit (EXIT_FAILURE);}
}void
calcxx_driver::scan_end ()
{fclose (yyin);
}

calc++-parser.y

%skeleton "lalr1.cc" /* -*- C++ -*- */
//%require "2.7"
%defines
%define parser_class_name "calcxx_parser"%code requires {
# include <string>
class calcxx_driver;
}// The parsing context.
%parse-param { calcxx_driver& driver }
%lex-param   { calcxx_driver& driver }%locations
%initial-action
{
// Initialize the initial location.
@$.begin.filename = @$.end.filename = &driver.file;
};%debug
%error-verbose// Symbols.
%union
{int          ival;std::string *sval;
};%code {
# include "calc++-driver.h"
}%token        END      0 "end of file"
%token        ASSIGN     ":="
%token <sval> IDENTIFIER "identifier"
%token <ival> NUMBER     "number"
%type  <ival> exp%printer    { std::cout << *$$; } "identifier"
%destructor { delete $$; } "identifier"%printer    { std::cout << $$; } <ival>%%
%start unit;
unit: assignments exp			{ driver.result = $2; };assignments:/* Nothing.  */				{}| assignments assignment	{};assignment:"identifier" ":=" exp{ driver.variables[*$1] = $3; delete $1; };%left '+' '-';
%left '*' '/';
exp: exp '+' exp	{ $$ = $1 + $3; }| exp '-' exp	{ $$ = $1 - $3; }| exp '*' exp	{ $$ = $1 * $3; }| exp '/' exp	{ $$ = $1 / $3; }| "identifier"	{ $$ = driver.variables[*$1]; delete $1; }| "number"		{ $$ = $1; };
%%void
yy::calcxx_parser::error (const yy::calcxx_parser::location_type& l,const std::string& m)
{driver.error (l, m);
}

main.cpp

#include <iostream>
#include "calc++-driver.h"int
main (int argc, char *argv[])
{calcxx_driver driver;for (int i = 1; i < argc; ++i){if (argv[i] == std::string ("-p"))driver.trace_parsing = true;else if (argv[i] == std::string ("-s"))driver.trace_scanning = true;else if (!driver.parse (argv[i]))std::cout << driver.result << std::endl;}return 0;
}

最后对应的Makefile

all: calc++.execalc++.exe: calc++-driver.o calc++-parser.o calc++-scanner.o main.og++ -o calc++.exe calc++-driver.o calc++-parser.o calc++-scanner.o main.ocalc++-driver.o: calc++-driver.cpp calc++-driver.h calc++-parser.hg++ -c calc++-driver.cppcalc++-parser.o: calc++-parser.cpp calc++-parser.h calc++-driver.hg++ -c calc++-parser.cppcalc++-parser.cpp calc++-parser.h: calc++-parser.ybison --defines=calc++-parser.h -ocalc++-parser.cpp calc++-parser.ycalc++-scanner.o: calc++-scanner.cpp calc++-parser.h calc++-driver.hg++ -c calc++-scanner.cppcalc++-scanner.cpp: calc++-scanner.lflex -ocalc++-scanner.cpp calc++-scanner.lmain.o:.PHONY: clean
clean:-rm *.o calc++-parser.h calc++-parser.cpp calc++-scanner.cpp location.hh position.hh stack.hh calc++.exe

注意:在lexer文件中有这样的选项

%option .. nounistd never-interactive

其目的是避免在VC++中出现的编译错误 Cannot open include file: 'unistd.h'

这篇关于bison(yacc)中关于calc的一个C++版实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/810137

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1