Tiny语言的词法分析器-C++版-课程设计报告

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验报告学号:姓名:专业:计算机科学与技术班级:2班第9周

二、构造Tiny语言DFA #

ID:letter(letter)* Number: digit(digit)*

三、根据DFA编写词法分析器

#include

#include

!

#include

using namespace std;

static int rowCounter = 1;//静态变量,用于存储行数

static bool bracketExist = false;//判断注释存在与否,false为不存在

class Lex

{

@

public:

ofstream output;

string line = "";

Lex(string inputLine)

{

line = inputLine;

scan(Trim(line));

rowCounter++;

}

string Trim(string &str)//函数用于去除每行前后空格

{

int s = (" \t");

int e = (" \t");

str = (s, e - s + 1);

str += "\0";

:

return str;

}

void scan(string inputLine)

{

ofstream output;

("", ios::app);

%

string line = inputLine;

int i = 0;

string str = "";

int temp;

string token = "";

output << rowCounter << ": " << line << endl;//输出每行

while (line[i] != '\0')//根据DFA扫描并判断

'

{

if (line[i] == '{')//注释

{

bracketExist = true;

}

if (bracketExist == true)

{

output << "\t" << rowCounter << ": ";

,

while (line[i] != '}')

{

output << line[i];//不处理,直接输出

if (line[i + 1] != NULL)

{

i++;

}

else

break;

}

if (line[i] == '}')//注释结束

{

output << line[i]<

bracketExist = false;

}

|

}

if (bracketExist == false)

{

//数字

while (isdigit(line[i]))

{

temp = temp * 10 + line[i];

*

if (!isdigit(line[i + 1]))

{

output << "\t" << rowCounter << ": " << "NUM, val= " << temp - '0' << endl;

}

if (line[i + 1] != NULL&&isdigit(line[i + 1]))

i++;

else

break;

}

temp = 0;

//符号

while (!(isdigit(line[i]) || (line[i] >= 'a'&&line[i] <= 'z') ||

(line[i] >= 'A'&&line[i] <= 'Z') || line[i] == ' ' || line[i] == '{' || line[i] == '}')) {

-

token = token + line[i];

if (isdigit(line[i + 1]) || (line[i + 1] >= 'a'&&line[i + 1] <= 'z') || (line[i + 1] >= 'A'&&line[i + 1] <= 'Z') || line[i + 1] == ' ' || line[i + 1] == '{' || line[i + 1] == '}' || line[i + 1] == NULL)

{

if (isToken(token))

{

output << "\t" << rowCounter << ": " << token << endl;

}

else

)

{

int j = 0;

while (token[j] != '\0')

{

output << "\t" << rowCounter << ": " << token[j] << endl;

j++;

}

}

@

}

else

{

i++;

continue;

}

if (line[i + 1] != NULL)

i++;

@

else

break;

}

token = "";

//字母

while ((line[i] >= 'a'&&line[i] <= 'z') || (line[i] >= 'A'&&line[i] <= 'Z'))

<

{

str = str + line[i];

if (!((line[i + 1] >= 'a'&&line[i + 1] <= 'z') || (line[i + 1] >= 'A'&&line[i + 1] <= 'Z')))

{

if (isResearvedWord(str)) //判断是否是保留字

{

output << "\t" << rowCounter << ": " << "Reversed Word: " << str << endl;

,

相关文档
最新文档