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实现精确小数计算的完全指南

《Python实现精确小数计算的完全指南》在金融计算、科学实验和工程领域,浮点数精度问题一直是开发者面临的重大挑战,本文将深入解析Python精确小数计算技术体系,感兴趣的小伙伴可以了解一下... 目录引言:小数精度问题的核心挑战一、浮点数精度问题分析1.1 浮点数精度陷阱1.2 浮点数误差来源二、基础解决

Java实现在Word文档中添加文本水印和图片水印的操作指南

《Java实现在Word文档中添加文本水印和图片水印的操作指南》在当今数字时代,文档的自动化处理与安全防护变得尤为重要,无论是为了保护版权、推广品牌,还是为了在文档中加入特定的标识,为Word文档添加... 目录引言Spire.Doc for Java:高效Word文档处理的利器代码实战:使用Java为Wo

Java实现远程执行Shell指令

《Java实现远程执行Shell指令》文章介绍使用JSch在SpringBoot项目中实现远程Shell操作,涵盖环境配置、依赖引入及工具类编写,详解分号和双与号执行多指令的区别... 目录软硬件环境说明编写执行Shell指令的工具类总结jsch(Java Secure Channel)是SSH2的一个纯J

使用Python实现Word文档的自动化对比方案

《使用Python实现Word文档的自动化对比方案》我们经常需要比较两个Word文档的版本差异,无论是合同修订、论文修改还是代码文档更新,人工比对不仅效率低下,还容易遗漏关键改动,下面通过一个实际案例... 目录引言一、使用python-docx库解析文档结构二、使用difflib进行差异比对三、高级对比方

深度解析Python中递归下降解析器的原理与实现

《深度解析Python中递归下降解析器的原理与实现》在编译器设计、配置文件处理和数据转换领域,递归下降解析器是最常用且最直观的解析技术,本文将详细介绍递归下降解析器的原理与实现,感兴趣的小伙伴可以跟随... 目录引言:解析器的核心价值一、递归下降解析器基础1.1 核心概念解析1.2 基本架构二、简单算术表达

QT Creator配置Kit的实现示例

《QTCreator配置Kit的实现示例》本文主要介绍了使用Qt5.12.12与VS2022时,因MSVC编译器版本不匹配及WindowsSDK缺失导致配置错误的问题解决,感兴趣的可以了解一下... 目录0、背景:qt5.12.12+vs2022一、症状:二、原因:(可以跳过,直奔后面的解决方法)三、解决方

MySQL中On duplicate key update的实现示例

《MySQL中Onduplicatekeyupdate的实现示例》ONDUPLICATEKEYUPDATE是一种MySQL的语法,它在插入新数据时,如果遇到唯一键冲突,则会执行更新操作,而不是抛... 目录1/ ON DUPLICATE KEY UPDATE的简介2/ ON DUPLICATE KEY UP

Python中Json和其他类型相互转换的实现示例

《Python中Json和其他类型相互转换的实现示例》本文介绍了在Python中使用json模块实现json数据与dict、object之间的高效转换,包括loads(),load(),dumps()... 项目中经常会用到json格式转为object对象、dict字典格式等。在此做个记录,方便后续用到该方

JWT + 拦截器实现无状态登录系统

《JWT+拦截器实现无状态登录系统》JWT(JSONWebToken)提供了一种无状态的解决方案:用户登录后,服务器返回一个Token,后续请求携带该Token即可完成身份验证,无需服务器存储会话... 目录✅ 引言 一、JWT 是什么? 二、技术选型 三、项目结构 四、核心代码实现4.1 添加依赖(pom

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp