Copiler_語法分析_表駆動法
2981 ワード
本論文の出典:http://blog.csdn.net/svitter DFA:
表駆動法を使用しました.
構造の表は以下の通りです.
テーブル駆動
num
...
E
+/-
other
0
1
6
を選択します.
を選択します.
を選択します.
1
1
2
5
を選択します.
を選択します.
2
2
を選択します.
3
を選択します.
を選択します.
3
を選択します.
を選択します.
を選択します.
4
--
4
5
を選択します.
を選択します.
を選択します.
を選択します.
5
5
を選択します.
を選択します.
を選択します.
を選択します.
6
2
を選択します.
を選択します.
を選択します.
を選択します.
7
コードは以下の通りです
表駆動法を使用しました.
構造の表は以下の通りです.
テーブル駆動
num
...
E
+/-
other
0
1
6
を選択します.
を選択します.
を選択します.
1
1
2
5
を選択します.
を選択します.
2
2
を選択します.
3
を選択します.
を選択します.
3
を選択します.
を選択します.
を選択します.
4
--
4
5
を選択します.
を選択します.
を選択します.
を選択します.
5
5
を選択します.
を選択します.
を選択します.
を選択します.
6
2
を選択します.
を選択します.
を選択します.
を選択します.
7
コードは以下の通りです
//============================================================================
// Name : compliler.cpp
// Author : Vit
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <cstdio>
#include <string.h>
#include <stdlib.h>
using namespace std;
int State[8][5];
//set final accept
const bool Acsta[7] =
{ 0, 1, 1, 0, 0, 1, 0, };
//JudgeNum
int JudgeNum(char &ch)
{
if (ch >= '0' && ch <= '9')
return 0;
else if (ch == '.')
return 1;
else if (ch == 'E')
return 2;
else if (ch == '+' || ch == '-')
return 3;
else
return 4;
}
//init the table
void init()
{
//set error state
for (int i = 0; i < 8; i++)
for (int j = 0; j < 5; j++)
{
State[i][j] = 7;
}
//set table
State[0][0] = 1;
State[0][1] = 6;
State[1][0] = 1;
State[1][1] = 2;
State[1][2] = 5;
State[2][0] = 2;
State[2][2] = 3;
State[3][3] = 4;
State[4][0] = 5;
State[5][0] = 5;
State[6][0] = 2;
}
//
char* Judge(char *str)
{
int i, j; //work point
//var
int len = strlen(str); //
char *t = new char[2000]; //
memset(t, '\0', 2000);
int cur; //
char ch; //
int state; //
int beg; //
int endd; //
bool change;
//start
for (i = 0; i < len; i++)
{
beg = cur = i;
ch = str[i];
state = 0;
endd = beg;
change = false;
while (state != 7)
{
state = State[state][JudgeNum(ch)];
if (Acsta[state])
{
endd = cur; //
change = true;
}
ch = str[++cur];
if (change)
{
if ((endd - beg) >= strlen(t))
{
for (j = beg; j <= endd; j++)
{
t[j - beg] = str[j];
}
}
change = false;
}
}
}
return t;
}
int main(void)
{
char *t;
char str[2000];
init();
freopen("test", "r", stdin);
while (~scanf("%s", str))
{
t = Judge(str);
printf("%s
", t);
}
return 0;
}