parser.c

来自「a compiler in java that parses and creat」· C语言 代码 · 共 63 行

C
63
字号
#include "global.h"

int lookahead;

/* parses and translates expression list */ 
parse() {
	lookahead = lexan();
	while( lookahead != DONE ) {
		expr(); match(';');
	}
}

expr() {
	int t;
	term();
	while(1) {
		switch( lookahead ) {
			case '+':
			case  '-':
				t = lookahead;
				match( lookahead ); term(); emit(t, NONE);
				continue;
			defualt: 
				return;
		}
	}
}

term() {
	int t;
	factor();
	while(1) {
		switch( lookahead ) {
			case '*': 
				t = lookahead;
				match(lookahead); factor(); emit( t, NONE );
			default:
				return;
		}
		
	}
}

factor() {
	switch(lookahead) {
		case '(':
			match('('); expr(); match(')'); break;
		case NUM:
			emit(NUM, tokenval); match(NUM); break;
		case ID:
			emit(ID, tokenval); match(ID); break;
		default: 
			error(" syntax error ");		
	}
	
}

match(int t) {	
	if(lookahead == t)
		lookahead  = lexan();
	else
		error(" Syntax Error ");
}

⌨️ 快捷键说明

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