第一范文网 - 专业文章范例文档资料分享平台

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

来源:用户分享 时间:2025/8/17 3:56:31 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

语法分析子流程图:

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文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c58yt92166g565jb3urou8mpoj7ocb000zp9_2.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top