PL0文法编译器C语言源代码
这是我编译原理课程的课程设计时写的,对PL0文法进行了扩充,主要增加了数组及结构体的功能,并用C语言实现了之。可能有人需要,就在这贴出来了。
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "ctype.h"
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
typedef int BOOL;
#define cxmax 2000
#define amax 16383
#define imax 100 /* length of identifier table */
#define tmax 100 /* length of type table */
#define lmax 10 /* maximum level */
#define al 10 /* length of identifiers */
#define norw 27 /* number of reserverd words */
/* standard function */
#define fabs 0
#define fsqr 1
#define fodd 2
#define fchr 3
#define ford 4
#define fwrite 5
#define fwriteln 6
#define fread 7
#define freadln 8
#define feoln 9
/* standard types */
#define intip 1
#define booltip 2
#define chartip 3
/*指令码*/
typedef enum opcode{
add, neg, mul, divd, remd, div2, rem2, eqli, neqi, lssi,
leqi, gtri, geqi, dupl, swap, andb, orb,
load, stor, hhalt, wri, wrc, wrl, rdi, rdc, rdl, eol,
ldc, ldla, ldl, ldg, stl, stg, move, copy, addc, mulc,
jump, jumpz, call, adjs, sets, pexit
}opcode;
/*指令结构体*/
typedef struct instr{
opcode op;
int a;
}instr;
/*词法类别*/
typedef enum symbol{
ident, number, sstring, plus, minus, star, lbrack, rbrack,
colon, eql, neq, lss, leq, gtr, geq, lparen, rparen, comma,
semicolon, period, becomes,
beginsym, endsym, ifsym, thensym, elsesym, whilesym, dosym,
casesym, repeatsym, untilsym, forsym, tosym, downtosym,
notsym, divsym, modsym, andsym, orsym, constsym, varsym,
typesym, arraysym, ofsym, recordsym, progsym, funcsym,
procsym
}symbol;
/*变量类型*/
typedef enum idkind{
konst, varbl, field, tipe, funkt
}idkind;
/*类型的种类,简单的,数组,记录类型*/
typedef enum tpkind{
simple, arrays, records
}tpkind;
typedef char alfa[al+1];
instr code[cxmax + 1];
int m[amax + 1];
/*词法分析相关全局变量*/
char ch;
int cc = 0, ll = 0;
char line[129];
symbol sym;
alfa id;
int num;
char str[81];
int slen;
/*alfa word[norw + 1];*/
int cx;
int lev;
int dx;
BOOL labeled;
int nl; /* as namelist[-1] */
int namelist[lmax];
int ix, tx; /* indices in tables */
/* identifier table */
typedef struct ITAB{
alfa name;
int link;
int tip;
idkind kind;
union{
int val; /*常量类型的值*/
struct{
int vlevel;
int vadr;
BOOL refpar;
}; /*变量类型的属性*/
int offset; /*域类型的偏移地址*/
struct{
int flevel;
int fadr;
int lastpar;
int resultadr;
BOOL inside;
}; /*函数类型的属性*/
};
}ITAB;
ITAB itab[imax + 1];
/* type table */
typedef struct TTAB{
int size;
tpkind kind;
union{
struct{
int low;
int high;
int elemtip;
}; /*数组类型的属性*/
int fields;