合肥工业大学(HFUT)编译原理实验二(Python实现)

一. 实验二: LL(1)分析法

二.实验目的及要求

实现目的:

  通过完成预测分析法的语法分析程序,了解预测分析法和递归子程序法的区

别和联系。使学生了解语法分析的功能,掌握语法分析程序设计的原理和构造方

法,训练学生掌握开发应用程序的基本方法。有利于提高学生的专业素质,为培

养适应社会多方面需要的能力。

实验要求:

  1、编程时注意编程风格:空行的使用、注释的使用、缩进的使用等。

2、如果遇到错误的表达式,应输出错误提示信息。

3、对下列文法,用 LL1)分析法对任意输入的符号串进行分析:

1E->TG

2G->+TG|—TG

3G->ε

4T->FS

5S->*FS|/FS

6S->ε

7F->(E)

8F->i

三. 实验内容

根据某一文法编制调试 LL 1 )分析程序,以便对任意输入的符号串

进行分析。

u 构造预测分析表,并利用分析表和一个栈来实现对上述程序设计语言的分

析程序。

u 分析法的功能是利用 LL1)控制程序根据显示栈栈顶内容、向前看符号

以及 LL1)分析表,对输入符号串自上而下的分析过程

四. 核心算法流程

五.核心代码

/ /预测分析过程

stack<std::string> stackLL;

    string stackStr{};

    stackLL.push("#");

    stackStr += '#';

    auto pos = v_LL[0].find("->");

    std::string begin = v_LL[0].substr(0, pos);

    stackLL.push(begin);

    stackStr += begin;

    // print to test

    std::cout << "------- stack init ------" << std::endl;

    std::cout << stackLL.top() << std::endl;

    std::cout << inputStr << std::endl;

    // 预测分析

    cout << "步骤\t\t" << "符号栈\t\t" << "输入串\t\t" << "所用产生式" << endl;

    int stepNum = 0;

    int index = 0; // 用来存取输入

    cout << to_string(stepNum) << "\t\t" << stackStr << "\t\t" << inputStr << endl;

    bool flag = true;

    string a = inputStr.substr(index, 1);

    while (flag)

    {

        string stack_top = stackLL.top();

        stackLL.pop();

        stackStr.pop_back();

        auto pair_tmp = pair<string, string>(stack_top, a);

        if (ll1.isInVT(stack_top)) {

            if (stack_top == a) {

                a = inputStr.substr(++index, 1);

            }

            else{

                cout << "ERROR" << endl;

                break;

            }

        }

        else if (stack_top == "#") {

            if (stack_top == a) {

                flag = false;

            }

            else {

                cout << "ERROR" << endl;

                break;

            }

        }

        else if (!ll1.table[pair_tmp].empty()) {

            string right{};

            string s_tmp = ll1.table[pair_tmp];

            auto pos1 = s_tmp.find("->");

            right = s_tmp.substr(pos1+2);

            vector<string> v_tmp{};

            LL1::splitString(v_tmp, right);

            for (int i=int(v_tmp.size()-1); i>=0; i--) {

                if (v_tmp[i] == "$")

                    continue;

                stackLL.push(v_tmp[i]);

                stackStr += v_tmp[i];

            }

        }

        else {

            cout << "ERROR" << endl;

            break;

        }

    }

六. 具体代码

        github仓库链接:https://github.com/1StephenCurry1/Compiler-Design.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值