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

📄 parser.cpp

📁 嵌入式系统开发 TOPPERS and JSP Kernel Release 1.3 TOPPERS = Toyohashi Open Platform for Embedded Real-Tim
💻 CPP
📖 第 1 页 / 共 2 页
字号:
		return Token::OPERATOR;		//Punctuator	work = Punctuator;	while(*work != '\x0')		if( *(work++) == ch )		{			token += static_cast<char>(ch);			return (token.type = Token::PUNCTUATOR);		}	token += static_cast<char>(ch);	token.type = Token::UNKNOWN;	return Token::UNKNOWN;}ostream & operator << (ostream & out, Token & src){	switch(src.type)	{	case Token::IDENTIFIER:		out << "<IDENTIFIER:["; break;	case Token::INTEGER:		out << "<INTEGER:["; break;	case Token::STRINGLITERAL:		out << "<STRINGLITERAL:["; break;	case Token::STRING:		out << "<STRING:["; break;	case Token::OPERATOR:		out << "<OPERATOR:["; break;	case Token::PUNCTUATOR:		out << "<PUNCTUATOR:["; break;	case Token::RESERVEDWORD:		out << "<RESERVEDWORD:["; break;	case Token::SPECIAL:		out << "<SPECIAL:["; break;	case Token::SPACE:		out << "<SPACE:["; break;	case Token::UNKNOWN:		out << "<UNKNOWN>"; return out;	case Token::ERROR:		out << "<ERROR>"; return out;	default:		out << "<???:[";	}	return out << static_cast<string &>(src) << "]("<<src.value<<")>";}void Parser::getToken(const char * term, const char * second, ...){    Token token;	va_list vl;    if(term == NULL)        Exception("Internal: GetToken received an empty string as reserved word.","柒婶エラ〖: GetTokenに鄂矢机误が畔されました");	va_start(vl, second);	vl = (char *)vl - sizeof(const char *);	do {		getToken(token, false);		if(token.compare(term) != 0)		{			lastErrorToken = token;			Exception("Token [%s] should be replaced by [%s]","机剁[%s]は[%s]であるべきです").format(token.c_str(),term);		}		term = va_arg(vl, const char *);	}while(term != 0);}string Parser::getStreamLocation(void){	list<tagFile *>::iterator scope;	string location("[");	char buffer[16];	if(current == 0)		Exception("Stream handling method invocation occured before attaching a stream.","稍赖なストリ〖ム拎侯炭吾");	::sprintf(buffer, ":%d", current->line);	location += current->identifier;	location += buffer;	if(!fileStack.empty())	{		location += " (included at ";		scope = fileStack.begin();		while(scope != fileStack.end())		{			::sprintf(buffer, ":%d, ", (*scope)->line);			location += (*scope)->identifier;			location += buffer;			scope ++;		}		location.erase(location.size()-2);		location += ")";	}	location += "]";	return location;}void Parser::pushStream(const std::string & filename, std::string strid){	fstream * fin;	if(current != 0)		fileStack.push_front(current);			fin = new fstream(filename.c_str(),ios::in);	if(fin->is_open())	{		if(strid.size() == 0)			strid = filename;		current = new tagFile;		current->stream     = fin;		current->identifier = strid;		current->line       = 1;	}else	{				Exception("File operatation failure : [%s]","ファイル拎侯に己窃しました [%s]").format(filename.c_str());		delete fin;	}}map<string, class ParseUnit *> StaticAPI::container;map<string, class ParseUnit *> Directive::container;ParseUnit::ParseUnit(void * _container, const char * name){	map<string, ParseUnit *> * container;    string work(name);	string apiname;	string::size_type i,j;	i = 0;	container = reinterpret_cast<map<string, ParseUnit *> *>(_container);//	j = container->size();		do {		j = work.find_first_of(',', i);		apiname = work.substr(i, j-i);		if(container->find(apiname) != container->end())	        Exception("Multiple registration of [%s]\n","[%s]が脚剩して判峡されようとしています").format(apiname.c_str());	    (*container)[apiname] = this;		i = j + 1;	}while(j != string::npos);}void ParseUnit::printList(void * _container){    int i;	map<string, ParseUnit *> * container;    map<string, ParseUnit *>::iterator scope;	container = reinterpret_cast<map<string, ParseUnit *> *>(_container);    if(container->empty())    {        cout << "  " << Message("None of element registed", "判峡されている妥燎はありません") << endl;        return;    }    i = 0;    scope = container->begin();    while(scope != container->end())    {        cout << '[' << (*scope).first << "] ";        if(i++ >= 6)        {            i = 0;            cout << endl;        }        scope ++;    }    if(i != 0)        cout << endl;}Token & ParseUnit::parseParameter(Parser & p){	static Token result;	Token token;	int nest = 0;	result.type = Token::ERROR;	result.value = 0;	result.assign("");	do	{		p.getToken(token);		if(token == Token::PUNCTUATOR)		{			if(token.compare("(") == 0)				nest ++;			else if(token.compare(")") == 0)				nest --;			else if(nest == 0)				break;			if(nest < 0)				Exception("')' appeared before '('.","滦炳しない誓じ崇柑があります");		}		if(result == Token::ERROR)			result = token;		else		{			result.type = Token::STRING;			result += ' ';			result += token;		}	}while(true);	p.putBack(token);	result.trim();	return result;}int ParseUnit::parseParameters(Parser & p, Directory * container, int min, int max){	Token work;	int count = 0;	if(max == 0)		max = min;	do	{		Token & token = parseParameter(p);		if(token.type == Token::ERROR)			break;		if(token == Token::INTEGER)			container->addChild(new Directory(token.value));		else			container->addChild(new Directory((string &)token));		count ++;		p.getToken(work);	}while(work.compare(",")==0 && count < max);	if(count < min)		Exception("Too few parameters [%d/%d]","パラメ〖タの眶が警なすぎます [%d/%d]").format(count, min);	p.putBack(work);	return count;}int ParseUnit::parseParameters(Parser & p, Directory * container, const char * paramlist){	Token work;	int count;	string list;	string key;	string::size_type head,tail;	list.assign(paramlist);	count = 0;	head = 0;	tail = list.find_first_of(',');	key = list.substr(head,tail-head);	do	{		if(head == string::npos)			Exception("Too many parameters","パラメ〖タの眶が驴すぎます");		Token & token = parseParameter(p);		if(token.type == Token::ERROR)			break;		if(token == Token::INTEGER)			container->addChild(key,new Directory(token.value));		else			container->addChild(key,new Directory((string &)token));		if(tail != string::npos)		{			head = tail + 1;			tail = list.find_first_of(',',head);			key = list.substr(head,tail-head);			count ++;			p.getToken(work);		}else			break;	}while(work.compare(",")==0);	if(tail != string::npos)		Exception("Too few parameters","パラメ〖タの眶が警なすぎます");	return count;}//------Directory * StaticAPI::last = NULL;Directory * StaticAPI::allocate(Directory & container, const Token & token, const char * id, bool regist){	static unsigned int assignment_count = 0;	Directory * node;	if(!(token == Token::IDENTIFIER || token == Token::INTEGER))		Exception("Given token(%s) is not suitable for an object identifier.","オブジェクトの急侍叹として网脱できない机剁(%s)が回年されました").format(token.c_str());	if(regist && (token == Token::INTEGER && token.value <= 0))		Exception("Cannot assign an ID number less or equal to 0.","0笆布のID戎规を肋年することはできません");	node = container.findChild(id);	if(node != 0)	{		Directory::iterator scope;		scope = node->begin();		while(scope != node->end())		{			if((*scope).first.compare(token) == 0)				Exception("Identifier %s is already used.","急侍叹%sはすでに网脱されています").format(token.c_str());			scope ++;		}	}else		node = container.addChild(id);	node = node->addChild(token);	(*node)["#order"] = assignment_count++;	if(token == Token::IDENTIFIER)	{		if(regist)		{			Directory * scope = container.openChild("/","identifier",token.c_str(),NULL);			if(*scope == Directory::INTEGER)				*node = scope->toInteger();		}	}else		*node = token.value;	last = node;	return node;}//------ParserComponent::ParserComponent(void){}ParserComponent::~ParserComponent(void){}void ParserComponent::parseOption(Directory & container){    if(findOption(container, "h", "help"))    {        cout << Message(            "Static API parser\n"            "  -s, --source=filename : Specify the source file\n"            "  -iapi ,--ignore-api   : Ignore unknown static api\n"            "  --print-api           : Show registered static api list\n",             "琅弄APIパ〖サ\n"            "  -s, --source=ファイル叹  : 掐蜗ファイル叹を回年します\n"            "  -iapi, --ignore-api      : 判峡されていないAPIを痰浑します\n"            "  --print-api              : 判峡されているAPIの办枉を山绩します\n");        return;    }    if(findOption(container, 0, "print-api"))    {		cout << Message("List of Registerd Static API","琅弄API 办枉") << std::endl;        StaticAPI::printList();        return;    }	if(mergeOption(container, "s", DEFAULT_PARAMETER) != 0 || mergeOption(container, "s", "-source") != 0)		activateComponent();}bool ParserComponent::parseStaticAPI(Parser & p, Directory & container, Token token, const string domain){    map<string, ParseUnit *>::iterator api;    if(token.type != Token::IDENTIFIER)        return false;	try {	    api = StaticAPI::container.find(token);	    if(api == StaticAPI::container.end())	    {	        if(findOption(container, "iapi", "ignore-api"))	        {	            cerr << Message("Unknown static api %s at %s was ignored. (skipped)\n","润判峡のAPI %s%sは痰浑されます\n").format(token.c_str(), p.getStreamLocation().c_str());	            do {	                p.getToken(token);	            }while(token.compare(";") != 0);				p.putBack(token);	            return true;	        }	        Exception("Static API [%s] is not registered in the configurator", "琅弄API[%s]は踏判峡です").format(token.c_str());		}		if(findOption(container,"D","debug"))			cerr << Message("  StaticAPI [%s]\n","  琅弄API  [%s]\n").format((*api).first.c_str());	    p.getToken("(");	    (*api).second->body(token, container, p, domain);	    p.getToken(")");	    p.getToken(";");	}	catch(Exception * e)	{		string work;		work = p.getStreamLocation() + string(" ") + (const string &)*e;		dumpContainerSnapshot(container);		StaticAPI::dropLastObject();		failCount ++;		token = p.getLastErrorToken();		while (token != Token::ERROR && token != Token::EOS)		{			if( token == ";" )				break;				//粕み叫したト〖クンが琅弄APIと票じ叹涟なら きっとセミコロン撕れ		    api = StaticAPI::container.find(token);			if(api != StaticAPI::container.end())			{				cerr << Message("<The following error must be occured by lack of ';' at the end of previous line>","<肌のエラ〖は木涟乖の';'撕れによる材墙拉が光いです>")				     << endl;				p.putBack(token);				break;			}			p.getToken(token);        }		cerr << Message("Error : %s\n", "エラ〖 : %s\n").format(work.c_str());	}    return true;}void ParserComponent::body(Directory & container){    Token token;    Parser p(container);    Directory * scope;	failCount = 0;	scope = getOption(container, "s");    if(scope->size() == 0)    {        scope = 0;        p.pushStdStream(Message("Standard Input","筛洁掐蜗"));        VerboseMessage("Starting parse with standard input\n","筛洁掐蜗からの机剁豺老を倡幌しました\n");    }else		scope = scope->getFirstChild();    try{        do {            if(scope != 0)            {                VerboseMessage("Starting parse with file[%s]\n","ファイル[%s]の机剁豺老を倡幌しました\n").format((const char *)*scope);				p.pushStream(*scope);            }			this->parse(p, container);			if(p.getToken(token) != Token::EOS)                Exception("Buffer has remaining tokens, parsing is not yet finished", "パ〖スが面们されました");			if(failCount != 0)				Exception("Total %d failures found in this configuration.","%d改の俱巢があります").format(failCount);            VerboseMessage("Parse finished\n","机剁豺老は赖撅に姜位しました\n");        } while(scope != 0 && (scope = scope->getNext()) != 0);    }    catch(Exception * e)    {		string work;		work = p.getStreamLocation() + string(" ") + (const string &)*e;		Exception("Error : %s\n", "エラ〖 : %s\n").format(work.c_str());    }}

⌨️ 快捷键说明

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