《编译原理》LR来实现-简单算数表达式语法分析器设计

  1. LR来实现-简单算数表达式语法分析器设计

【问题描述】

1.设计简单算数表达式语法分析器算法;(LR来实现)

2.编写代码并上机调试运行通过。

【输入形式】

简单算数表达式

【输出形式】

正确/错误

【样例输入】

x+y*(3*a+7)-b/5
x+y*(3*a+7-b/5

【样例输出】

true
false

【样例说明】
【评分标准】

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <list>

using namespace std;

// 判断某个非终结符的FIRST集是否含空
bool contain_null(char m, map<char, string> FIRST) {
    string p = FIRST[m];
    for (size_t i = 0; i < p.length(); i++) {
        if (p[i] == 'k') return true;
    }
    return false;
}

// 打印map
template<class T>
void Printmap(T a, T b) {
    for (; a != b; a++) cout << (*a).first << ":" << (*a).second << endl;
}

// 判断是不是终结符
bool isTerminal(char p) {
    if (p == '*' || p == '(' || p == ')' || p == '+' || p == '^' || p == 'k' || p == '+' || p == '/' || p == '-' || p == 'i') {
        return true;
    }
    else {
        return false;
    }
}

// 找某个非终结符是哪个产生式左边的符号
int find_next(char p, vector<string> production) {
    for (vector<string>::iterator i = production.begin(); i != production.end(); i++) {
        if ((*i)[0] == p) return i - production.begin();
    }
}

// 找某行产生式每个子产生式出现的第一个位置
vector<int> find_firstright(string s) {
    vector<int> p;
    for (size_t i = 0; i < s.length(); i++) {
        if (s[i] == '>' || s[i] == '|') p.push_back(i + 1);
    }
    return p;
}

// 求某个非终结符的FIRST集
string solveFirst(string s, vector<string> production, map<char, string>& FIRST) {
    vector<int> fr = find_firstright(s);
    string result;
    for (auto i = fr.begin(); i != fr.end(); i++) {
        if (!isTerminal(s[*i])) {
            int p = find_next(s[*i], production);
            FIRST[s[*i]] = solveFirst(production[p], production, FIRST);
            result += FIRST[s[*i]];
            for (size_t j = *i; j < s.size(); j++) {
                if (contain_null(s[j], FIRST)) {
                    if (s[j] == '|') break;
                    j++;
                    if (isTerminal(s[j])) {
                        result += s[j];
                        break;
                    }
                    p = find_next(s[j], production);
                    FIRST[s[j]] = solveFirst(production[p], production, FIRST);
                    result += FIRST[s[j]];
                }
            }
        }
        else {
            result += s[*i];
        }
    }
    return result;
}

// 求非终结符在其他产生式后面的非终结符,或判断是不是其它产生式的末尾
vector<string> find_follow(char p, vector<string> production) {
    vector<string> follow;
    string follow1, follow2;
    for (auto i = production.begin(); i != production.end(); i++) {
        for (size_t j = 0; j < (*i).length(); j++) {
            if ((*i)[j] == p) {
                if ((j == (*i).length() - 1) || (*i)[j + 1] == '|') follow1 += (*i)[0];
                else follow2 += (*i)[j + 1];
            }
        }
    }
    follow.push_back(follow1);
    follow.push_back(follow2);
    return follow;
}

// 求非终结符的FOLLOW集
void solveFollow(int pos, vector<string> production, map<char, string> FIRST, map<char, string>& FOLLOW, bool flag) {
    string result;
    if (pos == 0) result += "#";
    vector<string> m = find_follow(production[pos][0], production);
    for (size_t i = 0; i < m[0].length(); i++) {
        vector<string> p = find_follow(m[0][i], production);
        if ((FOLLOW.count(m[0][i]) == 0) && (flag == 0) || p[0].find(production[pos][0]) == string::npos && flag == 1) {
            int x = find_next(m[0][i], production);
            solveFollow(x, production, FIRST, FOLLOW, 1);
        }
        result += FOLLOW[m[0][i]];
    }
    for (size_t i = 0; i < m[1].length(); i++) {
        if (isTerminal(m[1][i])) result += m[1][i];
        else {
            if (contain_null(m[1][i], FIRST)) {
                if (FOLLOW.count(m[1][i]) == 0) {
                    int x = find_next(m[1][i], production);
                    solveFollow(x, production, FIRST, FOLLOW, 1);
                }
                result += FOLLOW[m[1][i]];
                string p = FIRST[m[1][i]];
                for (size_t i = 0; i < p.length(); i++) {
                    if (p[i] != 'k') result += p[i];
                }
            }
            else {
                result += FIRST[m[1][i]];
            }
        }
    }
    sort(result.begin(), result.end());
    result.erase(unique(result.begin(), result.end()), result.end());
    if (FOLLOW.count(production[pos][0]) == 0) FOLLOW.insert(make_pair(production[pos][0], result));
    else FOLLOW[production[pos][0]] = result;
}

// 求每个产生式的SELECT集
vector<string> solveselect(int x, vector<string> production, map<char, string> FIRST, map<char, string> FOLLOW) {
    vector<string> r;
    vector<int> p = find_firstright(production[x]);
    for (size_t i = 0; i < p.size(); i++) {
        string select;
        if (isTerminal(production[x][p[i]]) && production[x][p[i]] != 'k') select = production[x][p[i]];
        else {
            if ((FIRST[production[x][p[i]]].find('k') == string::npos) && production[x][p[i]] != 'k') select = FIRST[production[x][p[i]]];
            else {
                for (size_t j = p[i]; j < production[x].size(); j++) {
                    if (isTerminal(production[x][j]) && production[x][p[i]] != 'k') {
                        select += production[x][j];
                        break;
                    }
                    else {
                        if (FIRST[production[x].at(j)].find('k') != string::npos)
                        {
                            select += FIRST[production[x][j]];
                        }
                        else {
                            if ((production[x][j] == '|') || j == production[x].length() - 1) {
                                select += FOLLOW[production[x][0]];
                                break;
                            }
                        }
                    }
                }
            }
        }
        select.erase(remove(select.begin(), select.end(), 'k'), select.end());
        r.push_back(select);
    }
    return r;
}

// 根据当前终结符和式子行数判断当前应该选哪个产生式
int run_LL(char b, int a, vector<string> slect, string t, list<pair<int, int>>& f, bool m) {
    unsigned int i;
    int flag = 0;
    for (i = 0; i < slect.size(); i++) {
        for (size_t j = 0; j < slect[i].length(); j++) {
            if (slect[i][j] == b) {
                flag = 1;
                break;
            }
        }
        if (flag == 1) break;
    }
    if (flag == 0) {
        i = -1;
        return i;
    }
    if (!f.empty()) f.pop_front();
    vector<int> p = find_firstright(t);
    if (m == 0) {
        for (size_t j = p[i]; j < t.length(); j++) {
            if (t[j] == '|') break;
            f.push_back(make_pair(a, j)); // 保存的是行数和接下来元素的位置
        }
    }
    int h = t.length() - 1;
    for (size_t j = p[i]; j < t.length(); j++) { // 找这个子产生式的结尾
        if (t[j] == '|') {
            h = j;
            break;
        }
    }
    if (m == 1) {
        if (h == t.length() - 1) {
            for (size_t j = (int)t.length() - 1; j >= p[i]; j--) {
                f.push_front(make_pair(a, j));
            }
        }
        else {
            for (int j = h - 1; j >= p[i]; j--) {
                f.push_front(make_pair(a, j));
            }
        }
    }
    return i; // 返回:这行选择了什么产生式子
}

int main() {
    string m;
    vector<char> px;
    map<int, vector<string>> SELECT;
    map<char, string> FIRST;
    map<char, string> FOLLOW;
    vector<string> production = { "E->TG",
                                  "G->+TG|-TG|k",
                                  "T->FH",
                                  "H->*FH|/FH|k",
                                  "F->i|(E)" };
    int kuohao = 0;
    // 找出所有出现过的终结符
    for (size_t i = 0; i < production.size(); i++) {
        for (size_t j = 0; j < production[i].length(); j++) {
            if (isTerminal(production[i][j])) px.push_back(production[i][j]);
        }
    }
    sort(px.begin(), px.end());
    px.erase(unique(px.begin(), px.end()), px.end());
    // 求FIRST, FOLLOW和SELECT集
    for (auto i = production.begin(); i != production.end(); i++) {
        string p = solveFirst(*i, production, FIRST);
        sort(p.begin(), p.end());
        p.erase(unique(p.begin(), p.end()), p.end());
        FIRST.insert(make_pair((*i)[0], p));
    }
    for (size_t i = 0; i < production.size(); i++) solveFollow(i, production, FIRST, FOLLOW, 0);
    for (size_t i = 0; i < production.size(); i++) {
        SELECT.insert(make_pair(i, solveselect(i, production, FIRST, FOLLOW)));
    }
    // 实际测试
    int flag = 0;
    int run = 0;
    string test;
    cin >> test;
    for (size_t i = 0; i < test.length(); i++) {
        if ((test[i] >= '0' && test[i] <= '9') || (test[i] >= 'a' && test[i] <= 'z')) test[i] = 'i';
        if (test[i] == '(') kuohao += 1;
        if (test[i] == ')') kuohao -= 1;
    }
    for (size_t i = 0; i < test.length(); i++) {
        auto t = find(px.begin(), px.end(), test[i]);
        if (t == px.end()) {
            cout << "False" << endl;
            return 0;
        }
    }
    unsigned int time = 0;
    list<pair<int, int>> f;
    bool tst = 0;
    while (time < test.length()) {
        int c = -2;
        if (time == test.length()) {
            flag = 0;
            break;
        }
        c = run_LL(test[time], run, SELECT[run], production[run], f, tst); // time当前要推导出的终结符,run是当前选用产生式的行
        if (c == -1) {
            cout << "False" << endl;
            flag = 1;
            return -1;
        }
        if ((production[f.front().first][f.front().second] == test[time]) || production[f.front().first][f.front().second] == 'k') {
            int a, b;
            do {
                a = f.front().first;
                b = f.front().second;
                if (production[a][b] != 'k') {
                    time++;
                }
                if (time == test.length()) break;
                f.pop_front();
                if (f.empty()) {
                    if (time == test.length()) {
                        flag = 0;
                        cout << "True" << endl;
                    }
                    else {
                        cout << "False" << endl;
                        return -1;
                    }
                }
            } while (isTerminal(production[f.front().first][f.front().second])); // 考虑到空产生式,可能出现连续多个终结符在一起的情况,要把所有终结符都出队,然后对非终结符找下一个产生式
            if (time == test.length()) {
                flag = 0;
                break;
            }
            run = find_next(production[f.front().first][f.front().second], production);
            continue;
        }
        else {
            run = find_next(production[f.front().first][f.front().second], production);
        }
        tst = 1;
    }
    if (kuohao != 0) {
        cout << "False" << endl;
        return 0;
    }
    if (flag == 0) {
        cout << "True" << endl;
    }
    return 0;
}



毕业论文引言 随着计算机技术的发展与普及,计算机已经成为各行业最基本的工具之一,迅速进入千家万户。因此,掌握计算机应用的基本技能成为新世纪人才不可缺少的基本素质之一。为使计算机能正常工作, 除了构成计算机各个组成部分的物理设备外, 一般说来, 还必须要有指挥计算机“做什么”和“如何做”的“程序”。程序及其有关文档构成计算机软件, 其中用以书写计算机软件的语言称为计算机程序设计语言。 1 计算机程序设计语言简介 计算机程序设计语言是计算机可以识别的语言,用于描述解决问题的方法,供计算机阅读和执行,通常简称为编程语言,是一组用来定义计算机程序的语法规则。它是一种被标准化的交流技巧,用来向计算机发出指令。一种计算机语言让程序员能够准确地定义计算机所需要使用的数据,并精确地定义在不同情况下所应当采取的行动。使用程序设计语言往往使程序员能够比使用机器语言更准确地表达他们所想表达的目的。对那些从事计算机科学的人来说,懂得程序设计语言是十分重要的,因为所有的程序都需要程序设计语言才能完成,而计算机的工作是用程序来控制的,离开了程序,计算机将一事无成。 2 开发背景及意义 现有计算器不能计算表达式,这是一个缺陷,为此,开发了一个能直接计算表达式的计算器,这为计算提高了更大的方便,可以大幅度提高计算效率。 第二章 第三章 第一节 递归下降法的描述 3.1.1实现思想 它的主要原理是,对每个非终极符按其产生式结构构造相应语法分析子程序,其中终极符产生匹配命令,而非终极符则产生过程调用命令。因为文法递归相应子程序也递归,所以称这种方法为递归子程序下降法或递归下降法。其中子程序的结构与产生式结构几乎是一致的。文法中每个非终结符对应一个递归过程(子程序),每个过程的功能是识别由该非终结符推出的串,当某非终结符的产生式有多个候选式时能够按LL(1)形式可唯一地确定选择某个候选式进行推导。 3.1.2算法的特点 递归下降法是语法分析中最易懂的一种方法。递归下降法要满足的条件:假设A的全部产生式为Aα1|α2|……|αn ,则必须满足如下条件才能保证可以唯一的选择合适的产生式 predict(Aαi)∩predict(Aαj)=Φ,当i≠j. 3.1.3构造递归下降语法分析程序 采用了递归子程序方法进行语法分析,对文法中的每个非终极符号按其产生式结构产生相应的语法分析子程序,完成相应的识别任务。其中终结符产生匹配命令,非终结符则产生调用命令。每次进入子程序之前都预先读入一个单词。因为使用了递归下降方法,所以程序结构和层次清晰明了,易于手工实现,且时空效率较高。实际的语法分析工作,从调用总程序的分析子程序开始,根据产生式进行递归调用各个分析子程序。 第二节
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值