文章目录
前言
编译原理上机实验系列(2)
一、预习准备
1.实验目的
掌握First和Follow集合求法,深入理解LL(1)文法分析过程。
2.实验要求
根据文法求出First和Follow集合
3.实验环境
Xcode
二、实验过程
1.实验步骤
(1)First集
假设 α–>tβ,求FIRST(α):
①如果首符号t是终结符则直接放入first集合中
②如果t不是非终结符:
如果t—>ε,则将ε加入FIRST(α),并且将β进行①②操作判断。
如果t不是ε,那么求first(t),并将first(t)的结果放入FIRST(α)中。
(2)Follow集
假设A -->αBβ,A -->αB,求follow(B):
①如果A是开始符, 将加入$ FOLLOW(A), 这里$是输入结束标记.
②对于A -->αBβ,首先判断β是否可以推出ε
如果不能推出ε,那么将first(β)加入follow(B)
如果推出ε,那么将{ first(β)- ε } U follow(A)加入follow(B)
③对于A -->αB,将follow(A)结果加入follow(B)。
2.实验数据记录
待输入数据:
4
S->ABC
A->a
B->@
C->c
预期结果:
first[S] = a
first[A] = a
first[B] = @
first[C] = c
follow[S] = #
follow[A] = c
follow[B] = c
follow[C] = #
3.实验代码
在文法G[S]中使用’@’代表空。
//
// main.cpp
// exam2
//
// Created by 小仙女 on 2021/6/7.
//
#include <cstdio>
#include <cstring>
#include <map>
#include <stack>
#include <algorithm>
using namespace std;
struct node
{
char s1[50], s2[50];
}g[100];
char s[110];
int num;
map<char, int> Map1;
map<char, int> Map2;
int Map1_num;
int Map2_num;
char s1[110], s2[110];
int first[50][50];
int follow[50][50];
int vis[110];
int acc[50];
int select1[100][50];
int c[50][50];
char sta[110];
int cnt;
void dfs1(char ch, int dis[])
{
if(acc[Map1[ch]])
{
for(int i = 1;i<=Map2_num;i++)
{
dis[i] = first[Map1[ch]][i];
}
return;
}
int value[20];
memset(value