毕业设计编译原理设计报告c语言词法与语法分析器的实现

loading 分享 2026-8-23 下载文档

语法分析子流程图:

3.程序代码实现

整个词法以及语法的程序设计在一个工程里面,一共包含了8个文件,分别为main.cpp、parse.cpp、scan.cpp、util.cpp、scan.h、util.h、 globals.h、parse.h,其中scan.cpp和scan.h为词法分析程序。

以下仅列出各个文件中的核心代码:

Main.cpp

#include \

#define NO_PARSE FALSE #include \#if NO_PARSE #include \#else

#include \#endif

int lineno=0; FILE * source; FILE * listing; FILE * code;

int EchoSource = TRUE;

int TraceScan=TRUE; int TraceParse=TRUE; int Error = FALSE;

int main(int argc,char * argv[]) {

TreeNode * syntaxTree; char pgm[120]; scanf(\ source=fopen(pgm,\ if(source==NULL)

{

fprintf(stderr,\exit(1);

} listing = stdout; fprintf(listing,\TION: %s\\n\#if NO_PARSE while(getToken()!=ENDFILE); #else

syntaxTree = parse(); if(TraceParse){ fprintf(listing,\ printTree(syntaxTree); } #endif fclose(source); return 0; }

Parse.cpp

#include \#include \#include \#include \

static TokenType token; /* holds current token */

/* function prototypes for recursive calls */ static TreeNode * declaration_list(void); static TreeNode * declaration(void); static TreeNode * params(void); static TreeNode * param_list(void); static TreeNode * param(void);

static TreeNode * compound_stmt(void); static TreeNode * local_declarations(void); static TreeNode * statement_list(void); static TreeNode * statement(void);

static TreeNode * expression_stmt(void); static TreeNode * if_stmt(void); static TreeNode * while_stmt(void); static TreeNode * return_stmt(void); static TreeNode * expression(void); static TreeNode * var(void);

static TreeNode * simple_exp(void);

static TreeNode * additive_expression(void); static TreeNode * term(void); static TreeNode * factor(void);

static TreeNode * args(void); static TreeNode * arg_list(void);

static void syntaxError(char * message) { fprintf(listing,\

fprintf(listing,\Error = TRUE; }

/*判断读取的字符*/

static void match(TokenType expected) {

if(token==expected) {

token=getToken( ); }

else {

syntaxError(\

printToken(token,tokenString);

fprintf(listing,\ \ } }

/*进行语法分析,构建语法树*/ TreeNode * declaration_list(void) { TreeNode * t= declaration(); TreeNode * p= t; while ((token==INT) || (token==VOID) ) {

TreeNode *q = declaration(); if (q!=NULL) { if (t==NULL) t = p = q; }

else /* now p cannot be NULL either */ { p->sibling = q; p = q; }

} return t; }

TreeNode * declaration(void) { TreeNode * t = NULL; switch (token) {

case VOID : case INT :

t = newStmtNode(DecK); if(token == INT) t->type =Integer; else

t->type = Void; match(token); switch (token) {


毕业设计编译原理设计报告c语言词法与语法分析器的实现.doc 将本文的Word文档下载到电脑
搜索更多关于: 毕业设计编译原理设计报告c语言词法与语法分析器的实现 的文档
相关推荐
相关阅读