目指せ!自作スクリプト!~トークン判別プログラム編~

アバター
せんちゃ
記事: 50
登録日時: 15年前
住所: 江別市東野幌町
連絡を取る:

目指せ!自作スクリプト!~トークン判別プログラム編~

投稿記事 by せんちゃ » 13年前

言語系にはトークンを割り当てる処理があると判別が容易になり効率が大変よろしいので
文字列を読み込んでいるときにトークンをちゃんと判別して属性付きのデータを取得するプログラムを作ります

CODE:

#include
#include
using namespace std;


/*
	トークンの種類
*/
enum TokenType{
	Unknown , //不明なトークン
	Digit , //整数文字'0'~'9'まで
	Letter , //文字'A'~'Z'、'a'~'z'、'_'まで

	IntValue , //整数データである

	Add , //加算 
	Sub , //減算
	Mul , //乗算
	Div , //除算
	Insert , //代入
	LeftParenthesis , //'('
	RightParenthesis , //')'
	Eof , //文字列の終了である
};

/*
	トークン構造体
*/
struct Token{
	TokenType type;
	int value;

	Token()
	{
		type = Unknown;
		value = 0;
	}

	Token( TokenType tt , int v = 0 )
	{
		type = tt;
		value = v;
	}
};

そして文字列を操作するコード

CODE:

string text;
int index;
Token token;
char c;


void input()
{
	char buf[256];
	gets_s( buf );
	text += buf;
}

//文字取得
char get_c()
{
	if( index == text.length() ){
		return EOF;
	}

	char result = text[index];
	index++;

	return result;
}

void back_c()
{
	index--;
}


//空白は飛ばす
void skip_space()
{
	while( true ){
		if( text[index] != ' ' ){
			return;
		}

		index++;
	}
}

これらを利用したトークン取得コード

CODE:

/*

	トークンを取得する

*/
Token get_token()
{
	int val = 0;

	skip_space(); //文字がある場所までシーク
	c = get_c();

	if( c == EOF ){
		return Token( Eof );
	}

	if( c >= '0' && c = '0' && c <= '9' ; c = get_c() ){
			//新しい数値を発見するたびに桁数を増やす + 数字文字コード - '0'(数字コードの開始点)で整数値を取得
			val = ( val * 10 ) + ( c - '0' ); 
		}

		back_c(); //次のトークン取得のために一個前に戻しておく
		return Token( IntValue , val ); //整数トークンを返す
	}

	switch( c ){
		case '+' : return Token( Add );
		case '-' : return Token( Sub );
		case '*' : return Token( Mul );
		case '/' : return Token( Div );
		case '(' : return Token( LeftParenthesis );
		case ')' : return Token( RightParenthesis );
	}


	return Token();
}


これで整数値と演算子が取得可能に!!

コメントはまだありません。