花了一天写出的程序没有顾及很多层面,但对于理解基本的实验道理和交上实验还是有点帮助的。代码实现了基于有限自动机的词法分析,采用递归下降分析法和EBNF文法实现语法分析并生成中间代码。from sdu
lexAnalysis.h
/*
* lexAnalysis.h
*
* Created on: 2014-12-2
* Author: liuqiushan
*/
#ifndef LEXANALYSIS_H_
#define LEXANALYSIS_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum _SYM
{
_CONST,
_VAR,
_procedure,
_begin,
_end,
_if,
_then,
_ID, // such as the 'a' in 'var a;'
_INT, // such as the '10' in 'const a = 10;'
_ASSIGN,// '='
_PLUS,// '+'
_SUB,// '-'
_STAR,// '*'
_DIV,// '/'
_LESS,// '<'
_MORE,// '>'
_LESSEQ,// '<='
_MOREEQ,// '>='
_DH,// ','
_MD,// ':='
_LEFT,// '('
_RIGHT,// ')'
_JH,// '#'
_FH// ‘;’
}SYM;
SYM getSYM(char* str);
void appendStr(char* str, char* c, int p_str);
int isABC(char* c);
int isNumber(char* c);
#endif /* LEXANALYSIS_H_ */
LexAnalysis.c
/*
* LexAnalysis.c
*
* Created on: 2014-12-2
* Author: liuqiushan
*/
#include "lexAnalysis.h"
SYM getSYM(char* _str)
{
SYM temp = _ID; // default identifier
if(!strcasecmp(_str, "CONST"))
temp = _CONST;
else if(!strcasecmp(_str, "VAR"))
temp = _VAR;
else if(!strcasecmp(_str, "procedure"))
temp = _procedure;
else if(!strcasecmp(_str, "begin"))
temp = _begin;
else if(!strcasecmp(_str, "end"))
temp = _end;
else if(!strcasecmp(_str, "if"))
temp = _if;
else if(!strcasecmp(_str, "then"))
temp = _then;
return temp;
}
void appendStr(char str[], char* c, int p_str )
{
str[p_str] = *c;
}
int isABC(char* c)
{
char ch = *c;
if(ch=='q'||ch=='w'||ch=='e'||ch=='r'||ch=='t'||ch=='y'||ch=='u'||ch=='i'||ch=='o'||ch=='p'||
ch=='a'||ch=='s'||ch=='d'||ch=='f'||ch=='g'||ch=='h'||ch=='j'||ch=='k'||ch=='l'||
ch=='z'||ch=='x'||ch=='c'||ch=='v'||ch=='b'||ch=='n'||ch=='m'||ch=='Q'||ch=='W'||
ch=='E'||ch=='R'||ch=='T'||ch=='Y'||ch=='U'||ch=='I'||ch=='O'||ch=='P'||ch=='A'||
ch=='S'||ch=='D'||ch=='F'||ch=='G'||ch=='H'||ch=='J'||ch=='K'||ch=='L'||ch=='Z'||
ch=='X'||ch=='C'||ch=='V'||ch=='B'||ch=='N'||ch=='M')
return 1;
else
return 0;
}
int isNumber(char* c)
{
char ch = *c;
if(ch=='1'||ch=='2'||ch=='3'||ch=='4'||ch=='5'||ch=='6'||ch=='7'||ch=='8'||ch=='9'||ch=='0')
return 1;
else
return 0;
}
synAnalysis.h
/*
* synAnalysis.h
*
* Created on: 2014-12-2
* Author: liuqiushan
*/
#ifndef SYNANALYSIS_H_
#define SYNANALYSIS_H_
typedef enum _KIND
{
PRO,//procedure
CON,//constant
VAR //variable
}CVPKind;
/*
* PL/0 Object Instruction
*
* There are three domains:
*
* f is the function code
* l is the difference between the declared level and the invoked level of the variable
*
* -----------------------------
* | | | |
* | f | l | a |
* | | | |
* -----------------------------
*/
typedef enum _FunctionCode
{
LIT,//① LIT: put the constant on the top of the stack, a is the constant
LOD,//② LOD: put the variable on the top of the stack,