实验报告 实验目的: 通过编写一个递归下降分析语法分析程序,了解递归下降分析的原理和实现方法,并能够消除左递归并编写递归下降识别子程序。 实验内容: 1. 消除左递归:根据文法g[e]: e→e+t|t t→t*f|f f→(e)|i,对左递归进行消除,得到消除左递归后的文法。 2. 编写递归下降识别子程序:根据消除左递归后的文法,编写递归下降识别子程序,可以根据输入的符号串判断是否是文法的句子。 实验步骤: 1. 消除左递归: 消除左递归后的文法如下: e → te' e' → +te' | ε t → ft' t' → *ft' | ε f → (e) | i 2. 编写递归下降识别子程序: ```c #include <stdio.h> #include <stdlib.h> char input[100]; int index = 0; void error() { printf("该符号串不是文法的句子\n"); exit(1); } void e(); void f(); void t(); void ep(); void tp(); void match(char c) { if (input[index] == c) { index++; } else { error(); } } void e() { t(); ep(); } void ep() { if (input[index] == '+') { match('+'); t(); ep(); } } void t() { f(); tp(); } void tp() { if (input[index] == '*') { match('*'); f(); tp(); } } void f() { if (input[index] == '(') { match('('); e(); match(')'); } else if (input[index] == 'i') { match('i'); } else { error(); } } int main() { printf("请输入符号串:"); scanf("%s", input); e(); if (input[index] == '\0') { printf("该符号串是文法的句子\n"); } else { printf("该符号串不是文法的句子\n"); } return 0; } ``` 实验结果: 输入:(i*i)+i 输出:该符号串是文法的句子 实验 通过本次实验,我成功消除了左递归,并编写了递归下降识别子程序来判断输入的符号串是否是文法的句子。实验过程中,我深入理解了递归下降分析的原理和实现方法,加深了对形式文法的理解。递归下降分析是一种简单而有效的语法分析方法,在实际应用中具有广泛的用途。通过本次实验,我对编译原理有了更深入的认识和理解。 [2024-12-16 14:43:22 | AI写代码神器 | 1266点数解答]