编译原理-简单的语法分析示例

/*
*功能:简单的语法分析器
*作者:王文堃
*创建时间:2016/4/5
*/

//根据输入判断语法是否正确
//文法是:S->cAd A->ab|a
//输入是:cad,cabd
//预计输出是:正确

#include<iostream>
using namespace std;

#define MAXSIZE 10

//函数声明
void GetNextChar();
int S();
int A();
void init_sentence();
void show_sentence();


//程序中需要用到的全局变量
char sentence[MAXSIZE] = {'\0'}; //用来接收输入的字符串
int ip = 0; //用来指定字符串的下标

//将数组下标加一
void GetNextChar()
{
    ip++;
}

//根据每一非终结符对应一个递归子函数,函数中应有S,A两个子函数
//S()针对S->cAd文法
int S()
{
    if (sentence[ip] == 'c') //判断输入第一个字符是不是c
    {
        GetNextChar();
        if (1 == A()) //文法中第二个A匹配成功
        {
            if (sentence[ip] == 'd')
            {
                GetNextChar();
                return 1; //成功
            }
        }
        return 0; //文法中A没有匹配成功
    }
    return 0; //若第一个字符不是c就返回0
}

//A()针对A->ab|a这种文法
int A()
{
    int oldip = ip; //保存ip的值用来回溯
    if (sentence[ip] == 'a')
    {
        GetNextChar();
        if (sentence[ip] == 'b')
        {
            GetNextChar();
            return 1; //成功A->ab
        }
    }

    //回溯
    ip = oldip;
    if (sentence[ip] == 'a')
    {
        GetNextChar();
        return 1; //成功A->a
    }
    return 0;
}

//从文件中读取输入到sentence中
void init_sentence()
{
    FILE *pFile;
    char ch;
    int i = 0;
    pFile = fopen("sentence.txt", "r");
    ch = fgetc(pFile);
    while (ch != EOF)
    {
        sentence[i++] = ch;
        ch = fgetc(pFile);
    }
}

void show_sentence()
{
    int i = 0;
    while(sentence[i] != '\0')
        cout << sentence[i++];
    cout << endl;
}

void main()
{
    init_sentence();
    show_sentence();
    cout << "检查结果是:" << endl;
    if (1 == S())
        cout << "语法正确" << endl;
    else
        cout << "语法错误" << endl;
    getchar();
}

文本名字为:sentence.txt
文本内容为:cad
将文本放置在与.cpp同目录下

注:源程序中描述的很清楚,此处不在赘述,功能十分单一供初学者参考,如有不明白的地方或者需要源文件的请联系:[email protected]

发布了36 篇原创文章 · 获赞 29 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章