2017春季学期编译原理期末实验报告

实验名:PL/0编译器的实现 一、实验目的 理解编译器的工作机制,掌握编译器的构造方法 掌握词法分析器的生成工具LEX的用法 掌握语法分析器的生成工具YACC的用法

二、实验内容简要概括 1.实验分为三个部分: 分别是词法分析、语法分析、语义分析和代码生成部分 三个部分对应PL/0编译程序的编译过程,使得在学习原理的过程中可以更好的体会到分析过程。

2.词法分析    编写PL/0语言识别程序,并借助flex工具生成一个PL/0语言的词法分析程序,对输入的PL/0语言的源程序进行扫描,识别出单词符号的类别,输出各种符号的信息。

参考LEX源程序的格式,自定义声明,辅助定义,识别规则和子程序。

3.语法分析 编写一个PL/0语言的语法分析程序,借助bison工具生成,使得程序可以对输入的PL/0源程序进行语法分析,并按语法归约过程输出归约时所用的语法规则。

4.语义分析 使用C语言编写PL/0的语义分析程序,要求将其转换成一个类pcode语言

三、实验环境: OS:Windows10 1607 Compiler:Cygwin64 Terminal,yacc,lex,bison, code:blocks:13.12

辅助:sublime text 3126, notepad++ 7.41 使用语言:C

四、实验设计说明 1.第一部分:词法分析

实验具体输入输出要求如下

输入:PL0源程序

输出:将单词符号分为下面五类,然后统计PL0源程序中各单词符号出现的次数

K类(关键字)I类(标识符)C类(常量)P类(算符及界符)O类(其他)

根据要求,再参考lex的语法格式,设计思路大致如下:

1)对五类关键词分别建立结构体,类似于Hash的链表法一样,一个关键词中对应一个数组,将每一个读入的,相同类型但是不同内容的符号插在对应类别的结构体后面。结构体设计如图。

2)辅助定义环节添加关键词信息与对应的语义动作insert

  1. 对读进来的PL/0文件进行分析,将结果输出到另外一个文件中

该部分的最大难度在于语义动作insert

本次实验对输入的字符串有长度限制,需要在分析语言的过程中给予警告,但同时也不能终止编译动作,因为如果每次编译报错,只能报一行错误,会使得编译器的分析效率十分低下。本次实验中insert动作对应的函数如下:

2.第二部分:语法分析 实验具体输入输出要求如下

输入:PL0源程序

输出:关于该程序的语法结构分析说明

参考bison的说明,大致明白这次实验是在词法分析的基础之上多加了对于语法规则的定义,其中定义的语句要符合C语言文法。

语法格式:左部(非终结符):右部(文法符号串);

非终结符名称通常用小写字母,终结符名称通常用大写字母。

右部为空表示左部的非终结符可以匹配空串。

左部相同的语法规则应尽量合并。

语义动作出现在规则的尾部时,bison在归约前执行它;语义动作出现在规则的中间时,bison在识别出它前面的若干文法符号后执行它。

实现思路参考词法分析实验,只是这次在对应的语义动作环节直接输出,而不需要insert到结构体中。

实验输出如下:

3.第三部分:语义分析和目标语言的生成

实验具体输入输出要求如下

输入:PL0源程序

输出:类Pcode代码

首先需要对类Pcode进行了解

目标代码类pcode是一种栈式机的汇编语言。

栈式机系统结构:没有累加器和寄存器,只有存储栈指针所有运算都在栈顶

指令格式fla

f  功能码

l  层次差 (标识符引用层减去定义层)

a  根据不同的指令有所区别

参考类Pcode的功能表和解释器结构,将程序分成三个部分:code.l,code.y和define.h。其中define.h定义了类Pcode的功能码代号,符号表和指令结构,code.l属于词法分析部分,code.y属于语法与语义分析部分。其中在语义动作说明部分,根据输入情况不同用$伪变量进行压栈出栈操作。

本次实验中已经提供了interpret函数,所以省略了C语言中对于功能码的具体情况说明,接下来的思路就是根据输入的程序,先检查词法有无错误—>构建符号表-->执行interpret()的内容à输出类Pcode结果

实验结果图在第五部分

五、以一个*PL0*的源程序作具体说明

原PL0程序如下:

var a, b, c;

procedure gcd;

procedure rec;

begin

    if a <> 0 then

        begin

            a := a - 1;

        end;

end;

 

begin

    if c < b then

        begin

            c := b;

            call rec;

        end;

end;

 

begin

    read(a);

    read(b);

    read(c);

    write(a);

    call gcd;

    write(a);

end.

复制代码

这个程序里面存在着过程嵌套,其实这一次实验中还实现了并列,但是在此就不赘述了。 实验输出结果如图

(注:在写报告的过程中才发现之前看错ppt说明的指令功能表,误将INT看成INI,但为了阅读的方便,所以此处不再做修改)

package analysis; import java.util.ArrayList; import java.util.List; import library.Digit; import library.KeyWords; import library.Symbol; /** * * @author 周弘懿 * */ public class AnalyseWords { private List temp = new ArrayList(); public List getTemp() { return temp; } /* 关键字或者标识符的长度。 */ private static final int LENGTHOFKEYWORDS = 500; /* 整型数据的长度。 */ private static final int LENGTHOFINT = 500; /* 字符串常量长度。 */ private static final int LENGTHOFSTRING = 1024; String result = ""; int position; /** * 处理程序 * * @return 词法分析后的结果 */ public void process(String aLine) { /* 存放关键字和标识符 */ byte[] word = new byte[LENGTHOFKEYWORDS]; /* 存放数字 */ byte[] number = new byte[LENGTHOFINT]; /* 存放运算符 */ byte[] symbol = new byte[500]; /* 存放字符串常数或是字符常数 */ byte[] string = new byte[LENGTHOFSTRING]; byte temp[]; temp = aLine.getBytes(); if(new String(temp).trim().length() == 0) this.temp.add("请输入C语言程序!"); /** * 主要逻辑 */ for (position = 0; position= temp.length) { return; } /* 滤掉空格、制表键。 */ if (temp[position] != ' ' || temp[position] != '\t') { /* 允许大小写字母和下划线 */ if ((temp[position] >= 65 && temp[position] = 97 && temp[position] = 48 && temp[position] = temp.length) /* 如果已经超过界限就终止循环。 */{ String checkdWord = new String(word, 0, tempPosition + 1); decideWord(checkdWord); return position; } } while ((temp[position] >= 65 && temp[position] = 97 && temp[position] = 48 && temp[position] = 48 && temp[position] = temp.length) /* 如果已经超过界限就终止循环。 */{ String checkdNumber = new String(number, 0, tempPosition + 1); decideNum(checkdNumber); return position; } } while (temp[position] >= '0' && temp[position] <= '9' || temp[position] == '.'); String checkdNumber = new String(number, 0, tempPosition + 1); decideNum(checkdNumber); // 因为上面的已经移到末尾,因为for还要+1,所以要-1 position--; } return position; } /** * 分析字段是实型还是整型常数 * @param checkdNumber 分析数字字段 */ private void decideNum(String checkdNumber) { if (Digit.hasDot(checkdNumber)) { try { double num = Double.parseDouble(checkdNumber); this.temp.add("(" + num + ", 实型常数)\n"); } catch (Exception e) { this.temp.add("(" + checkdNumber + ", 错误,发现多个.)\n"); } } else { try { long num = Long.parseLong(checkdNumber); this.temp.add("(" + num + ", 整型常数)\n"); } catch (Exception e) { this.temp.add("(" + checkdNumber + ", 错误,不是整型常数!)\n"); } } } /** * 分析字符常数,字符串常数和边界符 * @param position 词法分析语句遍历指针 * @param string 字符,字符串和边界符的数组 * @param temp 词法分析语句数组 * @return 返回词法分析语句遍历指针的新位置 */ public int analysisLimitSymble(int position, byte[] string, byte temp[]) { // 过滤字符串常数 if (temp[position] == '"') { // 存储数组的指针 int tempPosition = -1; do { tempPosition++; string[tempPosition] = temp[position]; position++; } while (temp[position] != '"'); //要把最后一个"给过滤掉,所以要向后移一个位置。 tempPosition++; string[tempPosition] = '"'; String checkdNumber=new String(string,0,tempPosition+1); this.temp.add("(" + checkdNumber + ", 字符串常数)\n"); } // 过滤字符常数 else if (temp[position] == '\'') { // 存储数组的指针 int tempPosition = -1; do { tempPosition++; string[tempPosition] = temp[position]; position++; } while (temp[position] != '\''); tempPosition++; string[tempPosition] = '\''; //要把最后一个"给过滤掉,所以要向后移一个位置。 String checkdNumber=new String(string,0,tempPosition+1); //c语言语法规定字符常量的字符数只能是1,再加上2个’,刚好应该是3。 if(tempPosition+1= 2) { this.temp.add("(" + new String(symbol,0,tempPosition+1)+ ", 错误,字符长度仅限2位)\n"); return position; } position++; if(position >= temp.length) /* 如果已经超过界限就终止循环。 */{ String checkdWord = new String(symbol, 0, tempPosition+1); position = decideSymble(checkdWord, temp, position); return position; } } while(Symbol.isSingleSymble(new String(temp, position, 1))); String checkdWord = new String(symbol, 0, tempPosition+1); //单个运算符可能组成符合运算符 position = decideSymble(checkdWord, temp, position); position--; return position; } private int decideSymble(String checkdWord, byte temp[], int position) { if(Symbol.isComboSymbol(checkdWord)) { this.temp.add("(" + checkdWord + ", 复合运算符)\n"); } else if(Symbol.isSingleSymble(checkdWord)) { this.temp.add("(" + checkdWord + ", 运算符)\n"); }else if(checkdWord.equals("/*")) { //过滤注释 this.temp.add("(" + checkdWord + ", 前注释)\n"); do { position++; if(position >= temp.length) { return position; } } while(temp[position] != '*'); /* 直到阅读到*,表示将其间的注释都过滤 */ position++; if(position>=temp.length) { /*如果已经超过界限就终止循环。*/ this.temp.add("错误,后注释缺少结束符'/'\n"); return position; } if(temp[position]!='/') { this.temp.add("错误,后注释缺少结束符'/'\n"); } else { this.temp.add("(" + new String(temp, position-1, 2) + ", 后注释 )\n"); return position-1; } } return position; } public static void main(String[] args) { AnalyseWords aw = new AnalyseWords(); aw.process("sd"); for (String str : aw.temp) { System.out.println(str); } } }
设计思想 (1)程序主体结构部分: 说明部分 %% 规则部分 %% 辅助程序部分 (2)主体结构的说明 在这里说明部分告诉我们使用的LETTER,DIGIT, IDENT(标识符,通常定义为字母开头的字母数字串)和STR(字符串常量,通常定义为双引号括起来的一串字符)是什么意思.这部分也可以包含一些初始化代码.例如用#include来使用标准的头文件和前向说明(forward ,references).这些代码应该再标记"%{"和"%}"之间;规则部分>可以包括任何你想用来分析的代码;我们这里包括了忽略所有注释中字符的功能,传送ID名称和字符串常量内容到主调函数和main函数的功能. (3)实现原理 程序中先判断这个句语句中每个单元为关键字、常数、运算符、界符,对不同的单词符号给出不同编码形式的编码,用以区分之。 PL/0语言的EBNF表示 <常量定义>::=<标识符>=<无符号整数>; <标识符>::=<字母>={<字母>|<数字>}; <加法运算符>::=+|- <乘法运算符>::=*|/ <关系运算符>::==|#|<|<=|>|>= <字母>::=a|b|…|X|Y|Z <数字>::=0|1|2|…|8|9 三:设计过程 1. 关键字:void,main,if,then,break,int,Char,float,include,for,while,printfscanf 并为小写。 2."+”;”-”;”*”;”/”;”:=“;”:”;”<“;”<=“;”>“;”>=“;”<>“;”=“;”(“;”)”;”;”;”#”为运算符。 3. 其他标记 如字符串,表示以字母开头的标识符。 4. 空格符跳过。 5. 各符号对应种别码 关键字分别对应1-13 运算符分别对应401-418,501-513。 字符串对应100 常量对应200 结束符# 四:举例说明 目标:实现对常量的判别 代码: digit [0-9] letter [A-Za-z] other_char [!-@\[-~] id ({letter}|[_])({letter}|{digit}|[_])* string {({letter}|{digit}|{other_char})+} int_num {digit}+ %% [ |\t|\n]+ "auto"|"double"|"int"|"struct"|"break"|"else"|"long"|"switch"|"case"|"enum"|"register"|"typedef"|"char"|"extern"|"return"|"union"|"const"|"float"|"short"|"unsigned"|"continue"|"for"|"signed"|"void"|"default"|"goto"|"sizeof"|"do"|"if"|"static"|"while"|"main" {Upper(yytext,yyleng);printf("%s,NULL\n",yytext);} \"([!-~])*\" {printf("CONST_string,%s\n",yytext);} -?{int_num}[.]{int_num}?([E][+|-]?{int_num})? {printf("CONST_real,%s\n",yytext);} "0x"?{int_num} {printf("CONST_int,%s\n",yytext);} ","|";"|"("|")"|"{"|"}"|"["|"]"|"->"|"."|"!"|"~"|"++"|"--"|"*"|"&"|"sizeof"|"/"|"%"|"+"|"-"|">"|"<"|">="|"<="|"=="|"!="|"&"|"^"|"|"|"&"|"||"|"+="|"-="|"*="|"/="|"%="|">>="|"<<="|"&="|"^="|"|="|"=" {printf("%s,NULL\n",yytext);} {id} {printf("ID,%s\n",yytext);} {digit}({letter})+ {printf("error1:%s\n",yytext);} %% #include <ctype.h> Upper(char *s,int l) { int i; for(i=0;i<l;i++) { s[i]=toupper(s[i]); } } yywrap() { return 1; } 五:DFA 六:数据测试 七:心得体会 其实匹配并不困难,主要是C++知识要求相对较高,只要把握住指针就好了。 附源程序: #include<iostream.h> #include<stdio.h> #include<stdlib.h> #include<string.h> int i,j,k,flag,number,status; /*status which is use to judge the string is keywords or not!*/ char ch; char words[10] = {" "}; char program[500]; int Scan(char program[]) { char *keywords[13] = {"void","main","if","then","break","int", "char","float","include","for","while","printf", "scanf"}; number = 0; status = 0; j = 0; ch = program[i++]; /* To handle the lettle space ands tab*/ /*handle letters*/ if ((ch >= 'a') && (ch <= 'z' )) { while ((ch >= 'a') && (ch <= 'z' )) { words[j++]=ch; ch=program[i++]; } i--; words[j++] = '\0'; for (k = 0; k < 13; k++) if (strcmp (words,keywords[k]) == 0) switch(k) { case 0:{ flag = 1; status = 1; break; } case 1:{ flag = 2; status = 1; break; } case 2:{ flag = 3; status = 1; break; } case 3:{ flag = 4; status = 1; break; } case 4:{ flag = 5; status = 1; break; } case 5:{ flag = 6; status = 1; break; } case 6:{ flag = 7; status = 1; break; } case 7:{ flag = 8; status = 1; break; } case 8:{ flag = 9; status = 1; break; } case 9:{ flag = 10; status = 1; break; } case 10:{ flag = 11; status = 1; break; } case 11:{ flag = 12; status = 1; break; } case 12:{ flag = 13; status = 1; break; } } if (status == 0) { flag = 100; } } /*handle digits*/ else if ((ch >= '0') && (ch <= '9')) { number = 0; while ((ch >= '0' ) && (ch <= '9' )) { number = number*10+(ch-'0'); ch = program[i++]; } flag = 200; i--; } /*opereation and edge handle*/ else switch (ch) { case '=':{ if (ch == '=') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 401; } else { i--; flag = 402; } break; } case'>':{ if (ch == '>') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 403; } else { i--; flag = 404; } break; } case'<':{ if (ch == '<') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 405; } else { i--; flag = 406; } break; } case'!':{ if (ch == '!') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 407; } else { i--; flag = 408; } break; } case'+':{ if (ch == '+') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 409; } else if (ch == '+') { words[j++] = ch; words[j] = '\0'; flag = 410; } else { i--; flag = 411; } break; } case'-':{ if (ch == '-') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 412; } else if( ch == '-') { words[j++] = ch; words[j] = '\0'; flag = 413; } else { i--; flag = 414; } break; } case'*':{ if (ch == '*') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 415; } else { i--; flag = 416; } break; } case'/':{ if (ch == '/') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 417; } else { i--; flag = 418; } break; } case';':{ words[j] = ch; words[j+1] = '\0'; flag = 501; break; } case'(':{ words[j] = ch; words[j+1] = '\0'; flag = 502; break; } case')':{ words[j] = ch; words[j+1] = '\0'; flag = 503; break; } case'[':{ words[j] = ch; words[j+1] = '\0'; flag = 504; break; } case']':{ words[j] = ch; words[j+1] = '\0'; flag = 505; break; } case'{':{ words[j] = ch; words[j+1] = '\0'; flag = 506; break; } case'}':{ words[j] = ch; words[j+1] = '\0'; flag = 507; break; } case':':{ words[j] = ch; words[j+1] = '\0'; flag = 508; break; } case'"':{ words[j] = ch; words[j+1] = '\0'; flag = 509; break; } case'%':{ if (ch == '%') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 510; } else { i--; flag = 511; } break; } case',':{ words[j] = ch; words[j+1] = '\0'; flag = 512; break; } case'#':{ words[j] = ch; words[j+1] = '\0'; flag = 513; break; } case'@':{ words[j] = '#'; flag = 0; break; } default:{ flag = -1; break; } } return flag; } main() { i=0; printf("please input a program end with @"); do { ch = getchar(); program[i++] = ch; }while(ch != '@'); i = 0; do{ flag = Scan(program); if (flag == 200) { printf("(%2d,%4d)",flag,number); } else if (flag == -1) { printf("(%d,error)",flag); } else { printf("(%2d,%4s)",flag,words); } }while (flag != 0); system("pause"); }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值