Esempio n. 1
0
static void on_privmsg( irc_session_t *session,
                 const char *event,
                 const char *origin,
                 const char **params,
                 unsigned int count) {

    char nick[256];
    char host[256];
    char *msg;

    
    /* printf("<%s> %s \n", origin, params[1]); */
    irc_target_get_nick(origin, nick, 256);
    irc_target_get_host(origin, host, 256);
    msg = irc_color_strip_from_mirc(params[1]);  

    if ( (!is_voice(nick) && !is_op(nick))
        || ((is_voice(nick) || is_op(nick)) && !botcmd_parse(session, msg, nick, host, 1))) {
     
        send_to_log(nick, msg);

    }

    free(msg);
}
Esempio n. 2
0
void NativeMovRegMem::verify() {
  NativeInstruction::verify();
  // make sure code pattern is actually a "ld" or "st" of some sort.
  int i0 = long_at(0);
  int op3 = inv_op3(i0);

  assert((int)add_offset == NativeMovConstReg::add_offset, "sethi size ok");

  if (!(is_op(i0, Assembler::ldst_op) &&
        inv_immed(i0) &&
        0 != (op3 < op3_ldst_int_limit
         ? (1 <<  op3                      ) & (op3_mask_ld  | op3_mask_st)
         : (1 << (op3 - op3_ldst_int_limit)) & (op3_mask_ldf | op3_mask_stf))))
  {
    int i1 = long_at(ldst_offset);
    Register rd = inv_rd(i0);

    op3 = inv_op3(i1);
    if (!is_op(i1, Assembler::ldst_op) && rd == inv_rs2(i1) &&
         0 != (op3 < op3_ldst_int_limit
              ? (1 <<  op3                      ) & (op3_mask_ld  | op3_mask_st)
               : (1 << (op3 - op3_ldst_int_limit)) & (op3_mask_ldf | op3_mask_stf))) {
      fatal("not a ld* or st* op");
    }
  }
}
Esempio n. 3
0
File: bot.c Progetto: tbhCiro/bot
int bot_parse_service(struct IRC *bot, char *server, char *command, char *me, char *channel, char *msg){
	if(DEBUG){
		printf("[server: %s] [command: %s] [me: %s] [channel: %s] %s\n",server,command,me,channel,msg);
	}
	
	// 353 is the NAMES list
	if(strcasecmp(command, "353") == 0){
		parse_op(bot,msg);
		if(DEBUG){
			print_op(bot);
		}
	}
	if(strcasecmp(command, "MODE") ==0){
		if((msg[0]=='+') && (msg[1]=='o')){
			// if it's not already in the oplist
			if(is_op(bot,&msg[3])==-1){
				add_op(bot,&msg[3]);
				if(DEBUG){
					print_op(bot);
				}
			}
		}
		else if((msg[0]=='-') && (msg[1]=='o')){
			if(is_op(bot,&msg[3])!=-1){
				rm_op(bot,&msg[3]);
				if(DEBUG){
					print_op(bot);
				}
			}
		}
	}
	
	return 0;
}
int evalRPN(vector<string>& tokens) {
        stack<int> val;
        for (string s : tokens) {
            if ( !is_op(s) ) {
                val.push( stoi(s) );
            }
            else {
                int num2 = val.top(); val.pop();
                int num1 = val.top(); val.pop();
                if (s == "+") {
                    val.push(num1 + num2);
                }
                else if ( s == "-") {
                    val.push(num1 - num2);
                }
                else if ( s == "*") {
                    val.push(num1 * num2);
                }
                else if ( s == "/") {
                    val.push(num1 / num2);
                }
            }
        }
        
        return val.top();
    }
Esempio n. 5
0
void handle_folding(Instruction *head) {
    if (!head->next || !head->next->next) {
        return;
    }
    Instruction *prev = head, *current = prev->next, *next = current->next;
    while (current && next) {
        if (prev->opcode == LOADI && current->opcode == LOADI && is_op(next)) {
            int first = prev->field2, second = current->field2, dest = next->field1;
            prev->field1 = dest;
            if (next->opcode == ADD) {
                prev->field2 = first + second;
            } else if (next->opcode == MUL) {
                prev->field2 = first * second;
            } else {
                prev->field2 = first - second;
            }
            Instruction *tmp = next->next;
            free(current);
            free(next);
            prev->next = tmp;
            if (prev->next && prev->next->next) {
                current = prev->next;
                next = current->next;
            } else {
                return;
            }
        } else {
            prev = current;
            current = next;
            next = next->next;
        }
    }
}
Esempio n. 6
0
File: expr.c Progetto: FK2469/F-NEMU
int find_dominant_operator(int p, int q) {
	int op = -1;
	int priority = -1;
	int i;
	int in_parenthes = 0;
	for(i = p; i <= q; i ++) {
		if(tokens[i].type == '(') {
			in_parenthes ++;
			continue;	
		}
		if(tokens[i].type == ')') {
			in_parenthes --;
			continue;
		}
		if(!is_op(tokens[i].type)) continue;
		if(in_parenthes > 0) continue;

		if(priority <= get_priority(tokens[i].type)) {
			priority = get_priority(tokens[i].type);
			op = i;
		}
		
	}
	return op;
}
Esempio n. 7
0
bool ExpressionManager::op_num_ratio_check(string expression){
    int op_cnt = 0;
    int num_cnt = 0;
    
    char exp_str[STR_BUFF_SIZE];
    exp_str[0] = '\0';
    //create a C string from the expression string
    //for use in strtok
    strcat(exp_str, expression.c_str());

    char * token;

    //use strtok to tokenize the string
    //separating by spaces

    token = strtok(exp_str, " ");
    while(token != NULL){
        //cout << "token: " << token << "\n";
        if(is_int_num(string(token))){
            num_cnt++;
        } else if(is_op( *token)){
            op_cnt++;
        } else if(strchr(symbols, *token) != NULL){
            //it's fine
        }  else {
            //it's not fine
            return false;
        }
        //increment to the next token
        token = strtok(NULL, " ");
    }
    return ((num_cnt - 1) == op_cnt);
}
Esempio n. 8
0
void NativeCall::verify() {
  NativeInstruction::verify();
  // make sure code pattern is actually a call instruction
  int x = long_at(0);
  if (!is_op(x, Assembler::call_op)) {
    fatal("not a call: 0x%x @ " INTPTR_FORMAT, x, p2i(instruction_address()));
  }
}
Esempio n. 9
0
bool NativeInstruction::is_load_store_with_small_offset(Register reg) {
  int x = long_at(0);
  if (is_op(x, Assembler::ldst_op) &&
      inv_rs1(x) == reg && inv_immed(x)) {
    return true;
  }
  return false;
}
Esempio n. 10
0
//==========================================================================================================
//==========================================================================================================
Production::Production(vector<Symbol> _symbols, string _action_name): symbols(_symbols), action_name(_action_name) {
    // Find the last symbol that is an operator
    auto iter = find_if(symbols.rbegin(), symbols.rend(), [](Symbol sym){ return is_op(sym); });
    
    if(iter != symbols.rend())
        op = get_op(*iter);
    else
        op = nullptr;
}
Esempio n. 11
0
static
expr_code(stream, node, need_lval) {
    auto op = node[0];
    if ( op == '()' )
        do_call( stream, node, need_lval );
    else if ( is_op(node[0]) )
        opexpr_code( stream, node, need_lval );
    else
        return leaf_code( stream, node, need_lval );
}
Esempio n. 12
0
/**
 *  tests helper functions is_var() and is_op()
 */
static char * test_helpers() {
    char tmp[VAR_LENGTH+1], str[LINE_LENGTH];
    char * trimmed;
    int ret, i;
    printf("Testing %s\n", __FUNCTION__);
    
    /* test is_var() from A-Z */
    for (i='A'; i<='Z'; i++) {
        tmp[0] = i;
        tmp[1] = '\0';
        ret = is_var(tmp);
        mu_assert("error, ret != 1", ret == 1);
    }
    /* test bogus inputs */
    /* small letter */
    tmp[0] = 'a';
    ret = is_var(tmp);
    mu_assert("error, ret != 0", ret == 0);
    /* number */
    tmp[0] = '1';
    ret = is_var(tmp);
    mu_assert("error, ret != 0", ret == 0);    
    
    /* test is_op */
    tmp[0] = '+';
    ret = is_op(tmp);
    mu_assert("error, ret != 1", ret == 1);
    tmp[0] = '-';
    ret = is_op(tmp);
    mu_assert("error, ret != 1", ret == 1);
    tmp[0] = '*';
    ret = is_op(tmp);
    mu_assert("error, ret != 1", ret == 1);
    tmp[0] = '/';
    ret = is_op(tmp);
    mu_assert("error, ret != 1", ret == 1);    
    /* test bogus inputs */
    tmp[0] = '=';
    ret = is_op(tmp);
    mu_assert("error, ret != 0", ret == 0);
    tmp[0] = '^';
    ret = is_op(tmp);
    mu_assert("error, ret != 0", ret == 0);
    tmp[0] = '$';
    ret = is_op(tmp);
    mu_assert("error, ret != 0", ret == 0);    
    
    /* test trim_space() */
    strcpy(str, "\t\tFD 30 \t\t   ");
    trimmed = trim_space(str);
    mu_assert("error, trimmed != \"FD 30\"", strsame(trimmed, "FD 30"));
    strcpy(str, "  \t  \tDO A FROM 1 TO 8 { \t\t   ");
    trimmed = trim_space(str);
    mu_assert("error, trimmed != \"DO A FROM 1 TO 8 {\"", strsame(trimmed, "DO A FROM 1 TO 8 {"));
    
    return 0;
}
Esempio n. 13
0
void out_formula(formula *v) {
	if (!is_op(v->smb)) {
		printf("%c", v->smb);
		return;
	}
	printf("(");
	out_formula(v->left);
	printf("%c", v->smb);
	out_formula(v->right);
	printf(")");
}
Esempio n. 14
0
File: expr.c Progetto: bcho/homework
int validate_expr(char *expression)
{
    char x, op;
    int vt, opt, level;
    char ops[STACK_SIZE];

    vt = -1; opt = -1;
    while ((x = *expression++) != '\0')
        if (is_value(x)) {
            vt += 1;
        } else if (is_op(x)) {
            level = op_level(x);
            while (opt >= 0 && level < op_level(ops[opt]) && \
                    ops[opt] != LEFTP) {
                op = ops[opt];
                opt -= 1;
                if (op == PLUS || op == MULT)
                    vt -= 1;
                if (vt < 0)
                    return 0;
            }
            if (x == RIGHP) {
                while (opt >=0 && ops[opt] != LEFTP) {
                    op = ops[opt];
                    if (op == PLUS || op == MULT)
                        vt -= 1;
                    if (vt < 0)
                        return 0;
                    opt -= 1;
                }
                if (opt < 0)
                    return 0;
                opt -= 1;
            } else {
                ops[++opt] = x;
            }
        } else if (!is_whitespace(x)){
            return 0;
        }

    while (opt >= 0) {
        op = ops[opt];
        if (op == LEFTP)
            return 0;
        if (op == PLUS || op == MULT)
            vt -= 1;
        if (vt < 0)
            return 0;
        opt -= 1;
    }

    return vt == 0 && opt == -1;
}
Esempio n. 15
0
void handle_simplification(Instruction *head) {
    if (!head->next || !head->next->next) {
        return;
    }
    Instruction *prev = head, *current = prev->next, *next = current->next;
    while (current && next) {
        if ((prev->opcode == LOADI || current->opcode == LOADI) && is_op(next)) {
            int new_value = -1;
            if (next->opcode == ADD || next->opcode == SUB) {
                if (prev->field2 == 0) {
                    new_value = current->field2;
                } else if (current->field2 == 0) {
                    new_value = prev->field2;
                } else if (prev->field2 == current->field2) {
                    new_value = 0;
                }
            } else {
                if (prev->field2 == 0 || current->field2 == 0) {
                    new_value = 0;
                } else if (prev->field2 == 1) {
                    new_value = current->field2;
                } else if (current->field2 == 1) {
                    new_value = prev->field2;
                }
            }
            if (new_value != -1) {
                if (current->opcode == LOAD) {
                    prev->opcode = LOAD;
                }
                prev->field1 = next->field1;
                prev->field2 = new_value;
                Instruction *tmp = next->next;
                free(current);
                free(next);
                prev->next = tmp;
                if (prev->next && prev->next->next) {
                    current = prev->next;
                    next = current->next;
                } else {
                    return;
                }
            } else {
                prev = current;
                current = next;
                next = next->next;
            }
        } else {
            prev = current;
            current = next;
            next = next->next;
        }
    }
}
Esempio n. 16
0
static char	*next_operator(char *str, char *end_expr, t_bistro *bistro)
{
    int		nb_par;
    char		*save_str;

    nb_par = 0;
    save_str = str;
    if (IS_GRP_BEG(*str, bistro))
        nb_par++;
    while (++str < end_expr)
        if (IS_GRP_BEG(*str, bistro))
            nb_par++;
        else if (IS_GRP_END(*str, bistro))
        {
            if (--nb_par < 0)
                my_puterror(E_SYNTAX);
        }
        else if (!nb_par && is_op(*str, bistro) &&
                 !is_op(*(str - 1), bistro))
            return str;
    return NULL;
}
Esempio n. 17
0
/* Eval the args given to -test and computes the function, unused */
ast_st* eval_args(int argc, const char ** argv, int par, int * index) {

  ast_st *tmp1, *tmp2;
  kind_en op = Nothing;
  int i;

  for (i = 0; i < argc; i++) {

    if (!strcmp(argv[i],"(")) {

      tmp2 = eval_args(argc-i, argv+i+1, 1, index);
      if (tmp2 == NULL) return NULL;
      i += *index;
    }
    else if (!strcmp(argv[i], ")"))
      if (par) {
        *index = i+1;
        return tmp1;
      }
      else {
        printf("Closing parenthesis unmatched\n");
        return NULL;
      }

    else if (is_op(argv[i])) { 
      op = get_op(argv[i]);
    }

    else {
      int val = !strcmp(argv[i], "") ? 0 : atoi(argv[i]);
      tmp2 = create_int(val);
      
      if (op != Nothing) {
        tmp1 = create_node(op, tmp1, tmp2);
        op = Nothing;
      } else tmp1 = tmp2;
    }
  }

  if (!par)
    return tmp1;
  else {
    printf("Opening parenthesis unmatched\n");
    return NULL;
  }
}
Esempio n. 18
0
File: expr.c Progetto: FK2469/F-NEMU
uint32_t expr(char *e, bool *success) {
	if(!make_token(e)) {
		*success = false;
		return 0;
	}

	/* TODO: Insert codes to evaluate the expression. */
	int i;
	for(i = 0; i < nr_token; i ++) {
		if(tokens[i].type == '*' && (i == 0 || is_op(tokens[i-1].type))) {
				tokens[i].type = DEREF;
				}
	}
	/* TEST: printf("Test func:expr(char*,bool*)\n and the nr_token is %d\n",nr_token); */
	uint32_t result = eval(0, nr_token-1, success);
	return result;
}
Esempio n. 19
0
gf8 do_read( char * s, int * index ) {
  char op = 0;
  skip(' ',s,index);
  if (is_num(s[*index])) return read_number(s,index);
  if (is_op(s[*index])) { 
    op = s[*index];*index = (*index) + 1;
    return read_op(op,s,index);
  }
  if (s[*index] == 0) return 0;

  if (s[*index] == '\n') {
    *index = *index + 1;
    return do_read(s,index);
  }

  printf("Unknown character %c\n",s[*index]);
  exit(-1);
}
Esempio n. 20
0
static expr *parse_rhs(expr *lhs, int priority)
{
	for(;;){
    int this_pri, next_pri;
		e_op op;
		expr *rhs;

		op = tok_cur;
		if(!is_op(op))
			return lhs; /* eof, rparen and colon covered here */

		this_pri = PRECEDENCE(op);
    if(this_pri > priority)
      return lhs;

		/* eat the op */
		tok_next();

		/* special case for ternary */
		if(op == tok_question){
			expr *if_t = parse();

			if(tok_cur != tok_colon)
				CPP_DIE("colon expected for ternary-? operator");
			tok_next();

			rhs = parse();

			lhs = expr_new_top(lhs, if_t, rhs);
		}else{
			rhs = parse_primary();

			/* now on the next op, or eof (in which case, precedence returns -1 */
			next_pri = PRECEDENCE(tok_cur);
			if(next_pri < this_pri) {
				/* next is tighter, give it our rhs as its lhs */
				rhs = parse_rhs(rhs, next_pri);
			}

			lhs = expr_op(op, lhs, rhs);
		}
  }
}
Esempio n. 21
0
File: parse.c Progetto: elboza/WiCE
char* get_arg(struct expr_node **expr,char *p,int line_count)
{
	int m_type;
	struct expr_node *new_expr,*new_expr2,*save_expr,*save_tree;
	char s1[MAXSTR];
	p=get_token(p);
	m_type=is_item(line_count);
	new_expr=(struct expr_node*)malloc(sizeof(struct expr_node));
	if(new_expr==NULL)
	{ sprintf(s1,"at line %d, error malloc exr_node",line_count);die(s1);}
	new_expr->type=m_type;
	strncpy(new_expr->str,my_token,MAXSTR);
	new_expr->left=NULL;
	new_expr->right=NULL;
	p=skip_space(p);
	if((*p=='\n')||(*p==',')|| (is_bool_op(p,line_count)))
	{
		*expr=new_expr;
		return p;
	}
	p=get_token(p);
	m_type=is_op(line_count);
	new_expr2=(struct expr_node*)malloc(sizeof(struct expr_node));
	if(new_expr2==NULL)
	{ sprintf(s1,"at line %d, error malloc exr_node",line_count);die(s1);}
	new_expr2->type=m_type;
	strncpy(new_expr2->str,my_token,MAXSTR);
	new_expr2->left=new_expr;
	new_expr2->right=NULL;
	*expr=new_expr2;
	p=skip_space(p);
	p=get_arg(&(new_expr2->right),p,line_count);
	if((new_expr2->type<new_expr2->right->type)&&(new_expr2->type<3)&&(new_expr2->right->type<3))
	{
		save_expr=new_expr2->right;
		save_tree=new_expr2->right->left;
		new_expr2->right->left=new_expr2;
		save_expr->left->right=save_tree;
		*expr=save_expr;
	}
	return p;
}
Esempio n. 22
0
struct POLISH *read_POLISH()
{
  char word[VARMAXLEN];

  struct POLISH *rv = NULL;

  /////////////
  long old_offset = ftell(stdin);

  if(scanf("%s", word) == EOF)
    syntax_error("unexpected end", "POLISH");

  if(strcmp(word, ";") == 0)
  {
    return rv;
  }
  else if(strlen(word) == 1 && is_op(word[0]))
  {
    /*printf("here is op\n");*/
    rv = (struct POLISH*)malloc(sizeof(struct POLISH));

    rv->type = PO_OP;
    rv->po.op = word[0];

    rv->next = read_POLISH();
  }
  else
  {
    /*printf("here is varnum\n");*/
    fseek(stdin, old_offset, SEEK_SET);

    rv = (struct POLISH*)malloc(sizeof(struct POLISH));
    
    rv->type = PO_VN;
    rv->po.vn = read_VARNUM();

    rv->next = read_POLISH();
  }
  return rv;

}
Esempio n. 23
0
t_inst		*create_inst(char *s, int where, t_inst *head, int c)
{
	t_inst *maillon;

	maillon = (t_inst *)malloc(sizeof(t_inst));
	maillon->is_label = 0;
	maillon->where = -1;
	maillon->s = ft_strdup(erase_char(s));
	maillon->opcode = 0;
	if (!head)
	{
		maillon->value = find_opcode(s);
		maillon->size = 1;
		if (maillon->value == -1)
			bad_instruction(c);
		maillon->opcode = is_op(maillon->value);
	}
	else
		find_value(s, maillon, head, c);
	maillon->where = where;
	maillon->next = NULL;
	return (maillon);
}
Esempio n. 24
0
void tokenizer::name()
{
    assert(m_scope == 0);

    const char* p = mp_char;
    char c = *mp_char;
    if (c == '[')
        ++m_scope;
    else if (c == ']')
    {
        m_tokens.push_back(new lexer_name_token(p, 1));
        next();
        return;
    }

    size_t len = 1;
    for (next(); has_char(); next(), ++len)
    {
        c = *mp_char;
        if (c == '[')
        {
            ++m_scope;
        }
        else if (c == ']')
        {
            if (!m_scope)
                break;

            --m_scope;
        }
        else if (is_op(c))
            break;
    }

    m_tokens.push_back(new lexer_name_token(p, len));
}
Esempio n. 25
0
string ExpressionManager::infixToPostfix(string infixExpression){
    stack<char> symbols;
    string out_str = "";
    //do tests for the validity of the infix expression
    if(!isBalanced(infixExpression)){
        return invalid;
    }
    if(!op_num_ratio_check(infixExpression)){
        return invalid;
    }

    char exp_str[STR_BUFF_SIZE];
    exp_str[0] = '\0';
    //create a C string from the expression string
    //for use in strtok
    strcat(exp_str, infixExpression.c_str());

    char * token;

    //use strtok to tokenize the string
    //separating by spaces

    token = strtok(exp_str, " ");
    while( 1 ){
        if(token == NULL){
            while(!symbols.empty()){
                out_str += symbols.top();
                out_str += " ";
                symbols.pop();
            }
            break;
        }
        //cout << "token: " << token << "\n";
        if(is_int_num(string(token))){
                out_str += string(token);
                out_str += " ";
        } else if(is_paren( *token ) == OPEN_PAREN){
            symbols.push( *token );
        } else if(is_paren( *token ) == CLOSE_PAREN){
            char top_char = symbols.top();
            symbols.pop(); 
            while(get_precedence(top_char) > OPEN_PAREN){
                //symbols.pop();
                out_str += top_char;
                out_str += " ";
                top_char = symbols.top();
                symbols.pop();
            }
        }  else if(is_op( *token )){
            if(symbols.empty()){
                symbols.push( *token );
            } else {
                char top_char = symbols.top();
                int top_prec = get_precedence(top_char);
                int token_prec = get_precedence( *token );
                while( top_prec >= token_prec ){
                    //go through any tokens with greater than or equal precedence
                    symbols.pop();
                    out_str += top_char;
                    out_str += " ";
                    if(symbols.empty()){
                        break;
                    }
                    top_char = symbols.top();
                    top_prec = get_precedence(top_char);
                }
                symbols.push( *token );
            }
        }
        //increment to the next token
        token = strtok(NULL, " ");
    }
    
    //to remove the last part of the string (the trailing space)
    //if using C++11 you can do out_str.pop_back();
    out_str.erase(out_str.end() - 1);

    return out_str;
}
Esempio n. 26
0
void tokenizer::run()
{
    if (!m_size)
        // Nothing to do.
        return;

    init();

    while (has_char())
    {
        if (is_digit(*mp_char))
        {
            numeral();
            continue;
        }

        if (!is_op(*mp_char))
        {
            name();
            continue;
        }

        if (is_arg_sep(*mp_char))
        {
            op(op_sep);
            continue;
        }

        switch (*mp_char)
        {
            case ' ':
                space();
                break;
            case '+':
                op(op_plus);
                break;
            case '-':
                op(op_minus);
                break;
            case '/':
                op(op_divide);
                break;
            case '*':
                op(op_multiply);
                break;
            case '=':
                op(op_equal);
                break;
            case '<':
                op(op_less);
                break;
            case '>':
                op(op_greater);
                break;
            case '(':
                op(op_open);
                break;
            case ')':
                op(op_close);
                break;
            case '"':
                string();
                break;
        }
    }
}
Esempio n. 27
0
char *infix2postfix(const char *expr, const size_t esize, const hefesto_int_t main_call) {

    const char *efinis = expr + esize, *e;
    char *t, *term, *tt;
    hefesto_common_stack_ctx *sp = NULL, *dp = NULL;
    hefesto_common_list_ctx *lp = NULL, *l;
    hefesto_int_t p, tp;
    size_t sz;
    hefesto_int_t bracket = 0;
    char *indexing;
    char *iexpr;
    char *args;
    size_t offset, count;
    hefesto_int_t state = 0;

    term = (char *) hefesto_mloc(HEFESTO_MAX_BUFFER_SIZE);
    memset(term, 0, HEFESTO_MAX_BUFFER_SIZE);

    t = term;
    *t = 0;

    for (e = expr; e != efinis; e++) {

        if (*e == 0) break;

        if (*e == '\n' || *e == '\r' || *e == '\t' || *e == ' ') continue;

        if (*e != 0 && *e != ' ' && *e != '\n' && *e != '\r' && *e != '\t' &&
            *e != '(' && *e != ')' && !is_op(*e) && *e != '[' &&
            !is_hefesto_string_tok(*e)) {
            *t = *e;
            t++;
            *t = 0;
            continue;
        } else if (is_hefesto_string_tok(*e)) {
            offset = 0;
            iexpr = get_next_string(e, &offset);
            e += offset;
            for (indexing = iexpr; *indexing != 0; indexing++, t++)
            *t = *indexing;
            free(iexpr);
            *t = 0;
        } else if (*e == '(' && !is_hefesto_numeric_constant(term) &&
               !is_hefesto_string(term) && *term && *term != '(' &&
               !is_op(*term)) {
            bracket++;
            offset = 0;
            args = get_next_call_args(e, &offset);

            if (*args) {
                iexpr = infix2postfix_function_args(args, strlen(args));
                tt = t;
                for (indexing = iexpr; *indexing != 0; indexing++, t++)
                    *t = *indexing;
                *t = 0;
                free(iexpr);
                count = 0;
                for (t = tt; *t != 0; t++) {
                    if (*t == '(') {
                        count++;
                    } else if (*t == ')') {
                        count--;
                    } else if (*t == '"') {
                        t++;
                        while (*t != '"' && *t != 0) {
                            t++;
                            if (*t == '\\') t += 2;
                        }
                    }
                }
                //  WARN(Santiago): null buffer position skipping avoidance.
                while (*t == 0 && t != term) {
                    t--;
                }
                t++;
                tt = ((char *)e + offset);
                while (is_hefesto_blank(*tt)) tt++;
                // can't add one more ')' because this is a function that is an
                // argument of another function
                if (*tt == ',') count--;
                while (count > 0) {
                    *t = ')';
                    t++;
                    count--;
                }
                *t = 0;
            }
            e += offset;
            free(args);
            if (*e == ')') e++;
        } else if ((*e == '-' || *e == '+') && t == term && isdigit(*(e+1)) &&
                   state == 0) {
            *t = *e;
            t++;
            continue;
        }

        if ((is_op(*e) || *e == '(' || *e == ')') && t == term) {
            *t = *e;
            t++;
            *t = 0;
            if (is_op(*(e+1)) && *e != '(' && *e != ')') { // composed operands
                *t = *(e+1);
                e++;
                t++;
                *t = 0;
            }
            state = 0;
        } else if ((e + 1) != efinis) e--;

        if (strcmp(term,"(") == 0) {
            sp = hefesto_common_stack_ctx_push(sp, (void *) term, t - term,
                                               HEFESTO_VAR_TYPE_UNTYPED);
        } else if(strcmp(term, ")") == 0) {
            t = (char *)hefesto_common_stack_ctx_data_on_top(sp);
            if (t && strcmp(t, "(") != 0) {
                while (sp && sp->data != NULL && strcmp(sp->data, "(") != 0) {
                    lp = add_data_to_hefesto_common_list_ctx(lp,
                                    hefesto_common_stack_ctx_data_on_top(sp),
                                    hefesto_common_stack_ctx_dsize_on_top(sp));
                    dp = hefesto_common_stack_ctx_on_top(sp);
                    sp = hefesto_common_stack_ctx_pop(sp);
                    del_hefesto_common_stack_ctx(dp);
                }
            }
            dp = hefesto_common_stack_ctx_on_top(sp);
            sp = hefesto_common_stack_ctx_pop(sp);
            del_hefesto_common_stack_ctx(dp);
        } else if ((p = get_op_precedence(term)) != -1) {

            tp = get_op_precedence(hefesto_common_stack_ctx_data_on_top(sp)); 

            while (tp != -1 && tp >= p) {
                lp = add_data_to_hefesto_common_list_ctx(lp,
                                    hefesto_common_stack_ctx_data_on_top(sp),
                                    hefesto_common_stack_ctx_dsize_on_top(sp));
                dp = hefesto_common_stack_ctx_on_top(sp);
                sp = hefesto_common_stack_ctx_pop(sp);
                del_hefesto_common_stack_ctx(dp);
                tp = get_op_precedence(hefesto_common_stack_ctx_data_on_top(sp)); 
            }

            sp = hefesto_common_stack_ctx_push(sp, (void *) term, t - term,
                                                   HEFESTO_VAR_TYPE_UNTYPED);
        } else {
            lp = add_data_to_hefesto_common_list_ctx(lp, term, t - term);
            state = 1;
        }
        t = term;
        *t = 0;

    }

    if (*term) {
        sp = hefesto_common_stack_ctx_push(sp, (void *) term, t - term,
                                           HEFESTO_VAR_TYPE_UNTYPED);
    }

    while (!hefesto_common_stack_ctx_empty(sp)) {
        lp = add_data_to_hefesto_common_list_ctx(lp,
                        hefesto_common_stack_ctx_data_on_top(sp),
                        hefesto_common_stack_ctx_dsize_on_top(sp));
        dp = hefesto_common_stack_ctx_on_top(sp);
        sp = hefesto_common_stack_ctx_pop(sp);
        del_hefesto_common_stack_ctx(dp);
    }

    free(term);

    for (p = 0, sz = 0, l = lp; l; l = l->next, p++) {
        sz += l->dsize;
    }

    sz += (size_t) p;

    term = (char *) hefesto_mloc(sz);
    *term = 0;

    for (l = lp; l; l = l->next) {
        if (*(char *)l->data == '(') continue;
        strncat(term, (char *) l->data, sz - 1);
        if (l->next && *(char *)l->next->data != '[')
        strncat(term, " ", sz - 1);
    }

    del_hefesto_common_list_ctx(lp);
    return term;

}
Esempio n. 28
0
string ExpressionManager::postfixToInfix(string postfixExpression){
    if(!op_num_ratio_check(postfixExpression)){
        return invalid;
    }
    if(strcspn(postfixExpression.c_str(), symbols) 
            != postfixExpression.length()){
        //a postfix expression shouldn't have any paren symbols
        return invalid;
    }
    if(!is_op(postfixExpression[postfixExpression.length() - 1])){
        //if the last character of the expression is not an operator
        //then it must not be a valid postfix expression
        return invalid;
    }
    stack<string> exp_stack;
    string out_str = "";

    string right;
    string left;


    char exp_str[STR_BUFF_SIZE];
    exp_str[0] = '\0';
    //create a C string from the expression string
    //for use in strtok
    strcat(exp_str, postfixExpression.c_str());

    char * token;

    //use strtok to tokenize the string
    //separating by spaces

    token = strtok(exp_str, " ");
    while(token != NULL){
        //cout << "token: " << token << "\n";
        if(is_int_num(string(token))){
            exp_stack.push( string(token) );
        } else if(is_op( *token)){
            right = exp_stack.top();
            exp_stack.pop();
            left = exp_stack.top();
            exp_stack.pop();
           
            string push_str;
            push_str += "( ";
            push_str += left;
            push_str += " ";
            push_str += string(token);
            push_str += " ";
            push_str += right;
            push_str += " )";
            exp_stack.push(push_str);

        } else {
            //it's not fine
            return invalid;
        }
        //increment to the next token
        token = strtok(NULL, " ");
    }

    out_str = exp_stack.top();


    return out_str;
}
Esempio n. 29
0
float eval(char *expr){
  float nums[80];
  char ops[80];
  char c;
  char temp_string[80];
  int t,s;
  int line=0,neg=0,done=0;
  int sparens;
  float temp_result;

  /* Parse String */
  nums[0]=0;
  for (t=0;(c=expr[t]);t++) {
    if (nums[line]==0 && c=='-') {
      neg=1;
    } else if (('0' <= c && c <= '9') || c=='.') {
      sscanf(expr+t,"%f",&nums[line]);
      while (('0' <= expr[t] && expr[t] <= '9') || expr[t]=='.') t++;
      t--;
      if (neg) nums[line] = -nums[line];
    } else if (is_op(c)) {
      ops[line]=c;
      line++;
      nums[line]=0;
      neg=0;
    } else if (c != ' ') {
      Error("Parse Error on string");
      error=1;
      return 0;
    }
  }
  ops[line]=0;

  /* Handle Parenthases */
  sparens=0;
  for (t=0;t<line;t++) {
    if (ops[t]=='(') sparens++;
    if (ops[t]==')') sparens--;
  }
  if (sparens != 0) {
    Error("Error with parenthases.");
    error=1;
    return 0;
  }
  
  while(!done) {
    sparens=-1;
    for (t=0;t<line;t++) {
      if (ops[t]=='(') {
        sparens=t;
      } else if (ops[t]==')') {
        if (sparens==-1) {
	 Error("Error with parenthases.");
         error=1;
	 return 0;
        }
        *temp_string='\0';
        for (s=sparens+1;s<=t;s++) sprintf(temp_string,"%s%f%c",temp_string,nums[s],ops[s]);
        temp_string[strlen(temp_string)-1]='\0';
        temp_result=eval(temp_string);
        ops[sparens]=ops[t+1];
        for (s=sparens+1;s<line-t+1;s++) {
	  ops[s]=ops[(t-sparens)+s+1];
	  nums[s]=nums[(t-sparens)+s+1];
        }
        nums[sparens]=temp_result;
        line-=(t-sparens)+1;
        t=line;
      }
    }
    if (sparens==-1) done=1;
    if (t==line-1 && sparens != -1) {
      Error("Error with parenthases.");
      error=1;
      return 0;
      done=1;
    }
  }

  /* Handle Exponent */
  for (t=0;t<line;t++) {
    if (ops[t]=='^') {
      nums[t]=pow(nums[t],nums[t+1]);
      ops[t]=ops[t+1];
      for (s=t+1;s<line;s++) {
        nums[s]=nums[s+1];
        ops[s]=ops[s+1];
      }
      line--;
      t--;
    }
  }


  /* Handle Mult and Div */
  for (t=0;t<line;t++) {
    if (ops[t]=='*') nums[t]*=nums[t+1];
    else if (ops[t]== '/') nums[t] /= nums[t+1];
    if (ops[t]=='*' || ops[t]=='/') {
      ops[t]=ops[t+1];
      for (s=t+1;s<line;s++) {
        nums[s]=nums[s+1];
        ops[s]=ops[s+1];
      }
      line--;
      t--;
    }
  }

  /* Handle Add and Sub */
  for (t=0;t<line;t++) {
    if (ops[t]=='+') nums[t]+=nums[t+1];
    else if (ops[t]== '-') nums[t] -= nums[t+1];
    if (ops[t]=='+' || ops[t]=='-') {
      ops[t]=ops[t+1];
      for (s=t+1;s<line;s++) {
        nums[s]=nums[s+1];
        ops[s]=ops[s+1];
      }
      line--;
      t--;
    }
  }

  if (line != 0) {
    printf("Error processing string %s\n",expr);
    exit();
  }

  return (nums[0]);

}
Esempio n. 30
0
string ExpressionManager::postfixEvaluate(string postfixExpression){
    if(!op_num_ratio_check(postfixExpression)){
        return invalid;
    }
    if(strcspn(postfixExpression.c_str(), symbols) 
            != postfixExpression.length()){
        //a postfix expression shouldn't have any paren symbols
        return invalid;
    }
    
    //if(!is_op(postfixExpression[postfixExpression.length() - 1])){
    //    //if the last character of the expression is not an operator
    //    //then it must not be a valid postfix expression
    //    return invalid;
    //}
    stack<int> exp_stack;
    string out_str = "";

    string right;
    string left;


    char exp_str[STR_BUFF_SIZE];
    exp_str[0] = '\0';
    //create a C string from the expression string
    //for use in strtok
    strcat(exp_str, postfixExpression.c_str());

    char * token;

    //use strtok to tokenize the string
    //separating by spaces

    token = strtok(exp_str, " ");
    while(token != NULL){
        //cout << "token: " << token << "\n";
        if(is_int_num(string(token))){
            exp_stack.push( atoi(token) );
        } else if(is_op( *token)){
            if(exp_stack.empty()){
                return invalid;
            }
            int iright = exp_stack.top();
            exp_stack.pop();
            if(exp_stack.empty()){
                return invalid;
            }
            int ileft = exp_stack.top();
            exp_stack.pop();
          
            //int iright = stoi(right); 
            //int ileft = stoi(left);
            //stringstream ps;
            int eval = 0;
            switch (*token){
                case '+':
                    eval = ileft + iright;
                    break;
                case '-':
                    eval = ileft - iright;
                    break;
                case '*':
                    eval = ileft * iright;
                    break;
                case '/':
                    if(iright == 0 ) return invalid;
                    eval = ileft / iright;
                    break;
                case '%':
                    if(iright == 0 ) return invalid;
                    eval = ileft % iright;
                    break;
            }

            exp_stack.push(eval);

        } else {
            //it's not fine
            return invalid;
        }
        //increment to the next token
        token = strtok(NULL, " ");
    }
    if(!exp_stack.empty()){
        char out_buff[STR_BUFF_SIZE];
        sprintf(out_buff, "%i", exp_stack.top());
        out_str = out_buff;
    } else {
        return invalid;
    }   

    return out_str;
       
}