⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 parser.cpp

📁 an easy compiler to compile C
💻 CPP
字号:
// Parser.cpp: implementation of the Parser class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Parser.h"

#include <string>
using namespace std;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

Parser::Parser()
{

}

void Parser::parse() {
	look_ahead = lexer.getNextToken();
	while (look_ahead.type != Token::DONE) {
		expression();  match(';'); code_gen.emit(Token(';'));
	}
}

void Parser::expression() {

	Token tk;
	term();
	while(1) {

		switch(look_ahead.type) {
		case '+': case '-':
			tk = look_ahead;
			match(look_ahead); term(); code_gen.emit(tk);
			break;

		default:
			return;  //empty or wrong operator
		}//switch

	}//while
}

void Parser::term() {

	Token tk;
	factor();
	while(1) {
		switch(look_ahead.type) {
		case '*': case '/': case Token::DIV: case Token::MOD:
			tk = look_ahead;
			match(look_ahead); factor(); code_gen.emit(tk);
			break;

		default:
			return ;  //empty or wrong operator
		}//switch

	}//while
}

void Parser::factor() {

	switch(look_ahead.type) {
		case '(':
			match(Token('('));  expression(); match(Token(')'));
			break;

		case Token::NUM:
			code_gen.emit(look_ahead); match(look_ahead);
			break;

		case Token::ID:
			code_gen.emit(look_ahead); match(look_ahead);
			break;

		default:
			error("->" + look_ahead.toStr() + "->Parser::factor..syntax error");
	}//switch
}

void Parser::match(const Token& token) {
	
	if (look_ahead == token)
		look_ahead = lexer.getNextToken();
	else
		error("->" + look_ahead.toStr() + "->Parser::match..syntax error");
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -