]> Panopticon :: K&R in Python :: 1.24 基本的な構文エラーチェック

<< 1.23 コメントを削除する | main | 2.4 文字列s1から、文字列s2中に含まれる任意の文字を除去 >>

1.24 基本的な構文エラーチェック

プログラミング言語C ANSI規格準拠

1.24 in C

#include <stdio.h>
#define BUF_SIZE 1024
#define SIZE 128

int sp = 0;
char *stack = NULL;
int ssize = 0;

int is_empty(){
	if (sp == 0){
		return 1;
	} else {
		return 0;
	}
}

void push(char c){
	if ( sp >= ssize){
		stack = realloc(stack,sizeof(char) * (ssize += SIZE));
	}
	stack[sp++] = c;
}

char pop(void){
	if (sp == 0){
		fprintf(stderr,"STACK IS EMPTY");
		exit(0);
	} else {
		return stack[--sp];
	}
}

void spit_stack(){
	int i;
	fprintf(stderr,"%d\n",sp);
	while(!is_empty()){
		fprintf(stderr,"unpaired %c was found\n",pop());
	}
	free(stack);
}

int find_pair(char c){

	char c1,c2;
	if (c == ')') c1 = '(';
	else if (c == '}') c1 = '{';
	else if (c == ']') c1 = '[';

	if (is_empty()) {
		fprintf(stderr,"unpaired %c was found\n",c);
		exit(0);
	} else if ((c2 = pop()) == c1){
		return 1;
	} else {
		fprintf(stderr,"mismatch between %c and %c\n",c2,c);
		exit(0);
	}
}
	
int main(void){
	char s[BUF_SIZE];
	int i, j, len;
	int comment1, comment2, quoted1, quoted2;
	comment1 = comment2 = quoted1 = quoted2 = 0;
	while (fgets(s,BUF_SIZE,stdin)){

		for (i=0;i < strlen(s);i++){
			if (quoted1){
				if (s[i] == '\\') {
					putchar(s[i]);
					putchar(s[++i]);
				} else if (s[i] == '\"'){
					quoted1 = 0;
				}
				putchar(s[i]);
			} else if (quoted2){
				if (s[i] == '\\') {
					putchar(s[i]);
					putchar(s[++i]);
				} else if (s[i] == '\''){
					quoted2 = 0;
				}
				putchar(s[i]);
			} else if(comment1) {
				if (s[i] == '*' && s[i+1] == '/') {
					comment1 = 0;
					i++;
					putchar('\n');
				}
			} else if(comment2) {
				if (s[i] == '\n') {
					comment2 = 0;
					putchar('\n');
				}
			} else {
				if (s[i] == '\"'){
					quoted1 = 1;
					putchar(s[i]);
				} else if (s[i] == '\''){
					quoted2 = 1;
					putchar(s[i]);
				} else if (s[i] == '/') {
					if(s[i+1] == '*') {
						comment1 = 1;
						i++;
					} else if (s[i+1] == '/') {
						comment2 = 1;
						i++;
					} else {
						putchar(s[i]);
					}
				} else if (s[i] == '(' || s[i] == '{' || s[i] == '['){
					push(s[i]);
					putchar(s[i]);
				} else if (s[i] == ')' || s[i] == '}' || s[i] == ']'){
					find_pair(s[i]);
					putchar(s[i]);
				} else {
					putchar(s[i]);
				}
			}
		}
	}
	if (is_empty() == 0){
		spit_stack();
	}
	return 0;
}

こんなのになった。括弧の数の対応だけはとっているが、『基本的な構文エラーのチェック』よりかなり前の段階にいるなあ。Pythonがどうとかいう以前の問題なのでちょっと考えよう。

カテゴリ

Trackback URI

http://www.panopticon.jp/mt/mt-tb.cgi/30

Trackbacks(0)

コメントする