Скачиваний:
20
Добавлен:
01.05.2014
Размер:
2.46 Кб
Скачать
#ifndef TOKENPARSER_HPP_
#define TOKENPARSER_HPP_

#include <istream>
#include <cstdio>
#include <map>

#include "Errors.hpp"

namespace Parser_impl {

extern char* tokenName[];

enum TokenType {
	TYPE_ID, TYPE_RES, TYPE_OPER, TYPE_DELIM, TYPE_LIT, TYPE_LITSTR
};

enum Tokens {
	
	// Reserved words
	T_VAR=1, T_INT, T_FLOAT, T_VOID, T_BEGIN, T_END, T_IF, T_THEN, T_ELSE, T_WHILE,
	T_DO, T_WRITE, T_RETURN, T_READ, T_WASERROR, T_EXIT,
	
	// Operations
	T_ASS,	// =
	T_OR,	// ||
	T_AND,	// &&
	T_PLUS,	// +
	T_MINUS,	// -
	T_MUL,	// *
	T_DIV,	// /
	T_MOD,	// %
	T_DEG,	// ^
	T_NOT,	// !
	T_EQ,	// ==
	T_NEQ,	// !=
	T_LSS,	// <
	T_LSSEQ,	// <=
	T_GRT,	// >
	T_GRTEQ,	// >=
	T_MINUSUN,
	T_PLUSUN,
	
	// Delimiters
	T_SEMIC, // ;
	T_COMMA, // ,
	T_LBRACK, // (
	T_RBRACK,	// )
	T_EOF
};

struct Token {
	TokenType type;
	long double value;
	std::string str;
	bool isFloat;
	long getLong()
	{
		return long(value);
	}
		
};

class TokenParser {
	
private:
	typedef std::map<std::string, Tokens> MapStr2Token;
	
	static MapStr2Token reservedWords;	
	static void initReservedWords();	
	
	std::istream& input;
	
	int ch;
	bool pushbacked;
	Token current;
	int lineNumber;
	
	void error(int _ch = 0, int expect = 0)
	{
		if ( _ch == 0 )
			throw TokenParserException(lineNumber);
		else if (expect == 0 )
			throw TokenParserException(lineNumber, _ch);
		throw TokenParserException(lineNumber, _ch, expect);
	}
	
	enum States {ST_START, ST_COM, ST_STR, ST_FINISH };	
	
	bool isDelim()
	{
		return (ch == ';' || ch == ',' || ch == '(' || ch == ')' || ch == EOF );
	}
	
	void makeDelimToken();
	
	bool isOP3()
	{		
		return (ch == '=' || ch == '!' || ch == '<' || ch == '>' );
	}	
	
	bool isOP()
	{
		return ( ch == '+' || ch == '-' || ch == '*' || ch == '%' || ch == '/' || ch == '^');
	}
	
	void makeOperationToken();
	
	void getNextChar()
	{
		ch = input.get();
	}
	
	void clearBuffer()
	{
		current.str.clear();
	}
	
	void addCharToBuffer()
	{
		current.str += ch;
	}
	
public:
	
	TokenParser(std::istream& in) : input(in), pushbacked(false), lineNumber(0)
	{
		initReservedWords();
		getNextChar();
	}
	
	Token* currentToken() 
	{
		return &current;
	}
	
	
	void pushBack()
	{
		pushbacked = true;
	}
	
	int getLineNumber()
	{
		return lineNumber;
	}
	
	void getNextToken();
	
};

}

#endif /*TOKENPARSER_HPP_*/
Соседние файлы в папке MyLanguage