c++使用flex+bison进行语法分析生成AST

本文介绍如何利用flex和bison结合C++14来实现一个C编译器,该编译器能够将源代码转换为MIPS32汇编。虽然存在打印格式问题,但提供了参考实现和测试用例,方便读者自行改进。
摘要由CSDN通过智能技术生成

参考

项目

  • 目录

在这里插入图片描述

  • 你问我为啥后缀是yy, ll,hh? 我也不知道,但是能编译通过!

这里只用提及Makefileast.hh

  1. Makefile
a.out: gt.ll gt.yy ast.hh
	bison -d gt.yy -v --debug
	flex -o gt.lex.c gt.ll
	g++ -g  -o $@ gt.yy.tab.c gt.lex.c main.cpp # -g是为了调试

test:
	./a.out ./tests/t1

clean: 
	rm ./a.out gt.lex.c gt.yy.tab.c gt.yy.tab.h
  1. ast.hh
    请自行忽略掉糟糕的打印格式.
#include <iostream>
#include <vector>

class NStatement;
class NExpression;
class NVariableDeclaration;

typedef std::vector<NStatement *> StatementList;
typedef std::vector<NExpression *> ExpressionList;

class Node
{
public:
    virtual ~Node() {}
    virtual void debug() {}
};

class NExpression : public Node
{
};

class NStatement : public Node
{
};

class NInteger : public NExpression
{

public:
    long long value;
    NInteger(long long value) : value(value) {}

    void debug()
    {

        std::cout << "Int_value= " << value << "\t";
    }
};

class NDouble : public NExpression
{
public:
    double value;
    NDouble(double value) : value(value) {}
    void debug()
    {
        std::cout << "Double_value= " << value << "\t";
    }
};

class NIdentifier : public NExpression
{
public:
    std::string name;
    NIdentifier(const std::string &name) : name(name) {}
    void debug()
  
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值