任务描述
基于第二章的词法分析程序和第三章的语法分析程序,使用C/C++语言编写PL/0编译程序的语义分析程序,并生成四元式形式的中间代码。
编程要求
完成上述编程任务,将C/C++语言源程序复制粘贴到右侧代码编辑器,点击“评测”按钮,运行程序,系统会自动进行结果对比。
测试说明
平台会对你编写的代码进行测试:
测试输入:
const a = 10;
var b, c;
//单行注释
/*
* 多行注释
*/
procedure p;
if a <= 10 then
begin
c := b + a;
end;
begin
read(b);
while b # 0 do
begin
call p;
write(2 * c);
read(b);
end;
end.
预期输出:
语义正确
中间代码:
(1)(syss,_,_,_)
(2)(const,a,_,_)
(3)(=,10,_,a)
(4)(var,b,_,_)
(5)(var,c,_,_)
(6)(procedure,p,_,_)
(7)(j<=,a,10,$8)
(8)(+,b,a,c)
(9)(ret,_,_,_)
(10)(read,b,_,_)
(11)(j#,b,0,$13)
(12)(j=,b,0,$17)
(13)(call,p,_,_)
(14)(*,2,c,T1)
(15)(write,T1,_,_)
(16)(read,b,_,_)
(17)(syse,_,_,_)
符号表:
const a 10
var b 0
var c 0
procedure p
测试输入:
const a = 10;
var a, b, c;
procedure p;
if a <= 10 then
begin
c := b + a;
end;
begin
read(b);
while b # 0 do
begin
call p;
write(2 * c);
read(b);
end;
end.
预期输出:
(语义错误,行号:2)
测试输入:
const a = 10;
var b, c;
//单行注释
/*
* 多行注释
*/
procedure p;
if a <= 10 then
begin
c := b + a;
end;
begin
read(p);
while b # 0 do
begin
call p;
write(2 * c);
read(b);
end;
end.
预期输出:
(语义错误,行号:16)
测试输入:
const a = 10;
var b, c;
//单行注释
/*
* 多行注释
*/
procedure p;
if a <= 10 then
begin
c := b + a;
end;
begin
read(p);
while b # 0 do
begin
call q;
write(2 * c);
read(b);
end;
end.
预期输出:
(语义错误,行号:19)
测试输入:
const a = 10;
var a, b, c;
//单行注释
/*
* 多行注释
*/
procedure p;
if a <= 10 then
begin
c := b + a;
end;
begin
read(p);
while b # 0 do
begin
call q;
write(2 * d);
read(b);
end;
end.
预期输出:
(语义错误,行号:2)
(语义错误,行号:16)
(语义错误,行号:19)
(语义错误,行号:20)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
/* ------------ 全局变量声明定义 ------------ */
/* 单词表 */
typedef struct WordTable{
int type; // 所属类型
char id[20]; // 标识识别符值
int lineNum; // 所在的行
int flag = 0;
};
WordTable wordTable[100]; // 单词表
char word[20] = "\0"; // 存储单个字符,添加到 wordTable 中
/* 符号表 */
typedef struct SymbolTable {
char type[20];
char variable[20];
int value;
};
SymbolTable symbolTable[50]; // 符号表
/* 内部代码 */
typedef struct InterCode {
char op[20];
char arg1[20];
char arg2[20];
char result[20];
};
InterCode interCode[50];
/* 标签表 */
typedef struct LabelTable {
char name[10];
int value = -1;
};
LabelTable lableTable[50]; // 标签表
int count_grammarError = 0; // 语法错误个数
int count_semanticError = 0; // 语义错误个数
int grammarErrorLine = 0; // 语法错误行号
int quaternionLine = 0; // 四元式行号
int wordIndex = 0; // 记录当前 wordTable 的下标
int symbolIndex = 0; // 记录当前 symbolTable 的下标
int lableIndex = 0; // 记录当前 lableTable 的下标
char allWord[39][20] ={
"begin","call","const","do","end","if","odd","procedure",
"read","then","var","while","write","(",")",",",";",".",
"+","-","*","/","=","#","<",">","<=",">=",":=","0","1","2","3",
"4","5","6","7","8","9",
};
char reservedWord[20][20] ={ // 保留字
"begin","call","const","do","end","if","odd","