예제 #1
0
int evaluate(char *expression , Stack *dataStack , Stack *operatorStack ) {

    Tokenizer *tokenizer;
    Token *token;
    NumberToken *number;
    OperatorToken *operator;


    tokenizer = tokenizerNew(expression);
    while(1) {
        number=(NumberToken*)nextToken(tokenizer);
        if(number == NULL) {
            Throw(ERR_NOT_DATA);
        }
        else if(number->type!=NUMBER_TOKEN) {
            Throw(ERR_NOT_DATA);
        } else
            push(dataStack,number);


        operator=(OperatorToken *)nextToken(tokenizer);
        if(operator == NULL) {
            break;
        } else if(operator->type!=OPERATOR_TOKEN) {
            Throw(ERR_NOT_OPERATOR);
        } else
            tryEvaluateOperatorsOnStackThenPush(dataStack, operatorStack ,operator);
    }
    evaluateAlloperatorOnStack(operatorStack ,dataStack);



}
struct token *readAllTokens(char *fileName, struct lm *lm)
/* Get list of all tokens from file. */
{
struct tokenizer *tkz;
struct token *tokList = NULL, *tok;
char *s;

tkz = tokenizerNew(fileName);
tkz->uncommentC = tkz->uncommentShell = tkz->leaveQuotes = TRUE;
while ((s = tokenizerNext(tkz)) != NULL)
    {
    lmAllocVar(lm, tok);
    tok->string = lmCloneString(lm, s);
    tok->fileName = fileName;
    tok->lineIx = tkz->lf->lineIx;
    slAddHead(&tokList, tok);
    }
slReverse(&tokList);
return tokList;
}
예제 #3
0
int evaluate(char *expression,Stack *dataStack,Stack *operatorStack){
	
	Tokenizer *tokenizer;
	Token *token;
	Token *ansToken;
	ErrorCode e;
	int i;
	int counter =0;
	NumberToken *result;
	
	dataStack=stackNew();
	operatorStack=stackNew();
	tokenizer = tokenizerNew(expression);
	if(expression ==NULL){	
		Throw(ERR_NO_EXPRESSION);
	}
	
	while((token=nextToken(tokenizer))!=NULL){
		if(counter%2==0&&token->type==OPERATOR_TOKEN){
			Throw(ERR_NOT_DATA);
		}
		else if(counter%2==1&&token->type==NUMBER_TOKEN){
			Throw(ERR_NOT_OPERATOR);
		}
		
		if(isNumber(token)){
			
			push(token,dataStack);
		}
		else if(isOperator(token)) 
		{
			tryEvaluateOperatorOnStackThenPush((OperatorToken*)token,dataStack,operatorStack);
		}
		
		counter ++;
	}
	evaluateAllOperatorOnStack(dataStack,operatorStack);
	result=(NumberToken*)pop(dataStack);
	printf("counter needed for each expression : %d \n",counter);
	return result->value;
}