Beispiel #1
0
/* concurrent assignment   (a,b,c:=c-b,a-c,b-a)
** NR: number of variables   3
** ALIST: list of variables  a,b,c
** ELIST: expression leaving values on the stack c-b,a-c,b-a
*/
Expression *assign_expression(int nr, Argument *alist, Expression *elist)
{
    /* assignment is a special operator */
    Type *tlist;
    Type ct;
    int i;
    Expression *e1;
    if ((i=left_on_stack(elist)) != nr) return 0;
    tlist = type_of_expression(elist);
    for (i=0; i<nr; i++) {
	ct = get_type(alist[i]);
	if (IsConst(ct)) {
	    fprintf(stderr, "Unable to make assignments to constants.\n");
	    return 0;
	}
	if (!get_operator(tlist[i], OPASSIGN, NoRefType(ct))) {
	    fprintf(stderr, "Assignment not defined for %s:=%s.\n",
		    lookup_typename(ct), lookup_typename(tlist[i]));
	    return 0;
	}
    }
    i=nr;
    while (i) {
	i--;
	e1=make_expression(alist[i]);
	e1=combine_expression(elist, e1, OPASSIGN);
	if (!e1) return 0;
	elist=e1;
    }
    return elist;
}
Beispiel #2
0
 ExprNode::ExprNode(const char *op_name, size_t sz)
 : op(get_operator(op_name, sz))
 {
     if (op->stateful()) {
         op=op->clone();
     }
 }
Beispiel #3
0
int
main(void)
{
	int n1, d1;	/* numerator, denominator of first fraction */
	int n2, d2;	/* numerator, denominator of second fraction */
	char op;	/* arithmetic operator + - * or /  */
	char again;	/* y or n depending on user's desire to continue */
	int n_ans,	/* numerator, denominator of answer */
	    d_ans;

	/* While the user wants to continue, gets and solves arithmetic
	   problems with common fractions. */

	do
	{
       	   /* Gets a fraction problem */
	   scan_fraction(&n1, &d1);
	   op = get_operator();
	   scan_fraction(&n2, &d2);

	   /* Computes the result */
	   switch (op)
	   {
	  	case '+':
			add_fractions(n1, d1, n2, d2, &n_ans, &d_ans);
			break;

		case '-':
			add_fractions(n1, d1, -n2, d2, &n_ans, &d_ans);
			break;

		case '*':
			multiply_fractions(n1, d1, n2, d2, &n_ans, &d_ans);
			break;

		case '/':
			multiply_fractions(n1, d1, d2, n2, &n_ans, &d_ans);
	   }
	   reduce_fraction(&n_ans, &d_ans);

	   /* Displays problem and result */
	   printf("\n");
	   print_fraction(n1, d1);
	   printf(" %c ", op);
	   print_fraction(n2, d2);
	   printf(" = ");
	   print_fraction(n_ans, d_ans);

	   /* Asks user about doing another problem */
	   printf("\nDo another problem? (y/n) > ");
	   scanf(" %c", &again);
	}
	while (again == 'Y' || again == 'y');
	return(0);
}
Beispiel #4
0
int compare_ops(char *o1, char *o2) {
    int o1p, o2p;
    Operator* o1o;
    Operator* o2o;

    if (is_lparen(o2)) return 0;

    o1o = get_operator(o1);
    o2o = get_operator(o2);

    o1p = o1o->precedence;
    o2p = o2o->precedence;

    if ((is_lassoc(*o1o) && o1p <= o2p) ||
        (is_rassoc(*o1o) != -1 && o1p < o2p)) {
        return 1;
    }

    return 0;
}
Beispiel #5
0
void get_atom()
{
  sari_spatiu();
  if ( isalpha( curent_char()) )
    get_name();
  else  if ( isdigit( curent_char()) )
    get_number();
  else  if ( isoperator(curent_char()) )
    get_operator();
  else eroare("caracter neasteptat");
  atom.cod = scan_cod();
}
Beispiel #6
0
void select_match(const char *expr) {
  const char *ptr;
  union arg *args;
  int rc, operator;
  char buffer[128];

  for(ptr = expr; 
      *ptr && *ptr != '=' && *ptr != '~' 
        && *ptr != '<' && *ptr != '>' && *ptr != '!';
      ++ptr)
    ;
  if(!*ptr)
    fatal(0, "invalid match expression '%s'", expr);
  args = xmalloc(3 * sizeof *args);
  args[0].string = xstrndup(expr, ptr - expr);
  ptr = get_operator(ptr, &operator);
  if(!ptr)
    fatal(0, "%s: unrecognized match operator\n", expr);
  if(*ptr == ':')
     ++ptr;
  switch(operator) {
  case '~':
    rc = regcomp(&args[1].regex, ptr, REG_ICASE|REG_NOSUB);
    if(rc) {
      regerror(rc, &args[1].regex, buffer, sizeof buffer);
      fatal(0, "regexec: %s", buffer);
    }
    select_add(select_regex_match, args, 2);
    break;
  case IDENTICAL:
    args[1].string = xstrdup(ptr);
    select_add(select_string_match, args, 2);
    break;
  default:
    args[1].operator = operator;
    args[2].string = xstrdup(ptr);
    select_add(select_compare, args, 3);
    break;
  }
}
Beispiel #7
0
data_t *eval(const data_t *exp, data_t *env) {
	if(eval_plz_die) {
		eval_plz_die = 0;
		ExitThread(0);
	}

	if(is_self_evaluating(exp))
		return (data_t*)exp;
	if(is_variable(exp))
		return lookup_variable_value(exp, env);
	if(is_quoted_expression(exp))
		return get_text_of_quotation(exp);
	if(is_assignment(exp))
		return eval_assignment(exp, env);
	if(is_definition(exp))
		return eval_definition(exp, env);
	if(is_if(exp))
		return eval_if(exp, env);
	if(is_lambda(exp))
		return make_procedure(get_lambda_parameters(exp), get_lambda_body(exp), env);
	if(is_begin(exp))
		return eval_sequence(get_begin_actions(exp), env);
	if(is_cond(exp))
		return eval(cond_to_if(exp), env);
	if(is_letrec(exp))
		return eval(letrec_to_let(exp), env);
	if(is_let_star(exp))
		return eval(let_star_to_nested_lets(exp), env);
	if(is_let(exp))
		return eval(let_to_combination(exp), env);
	if(is_application(exp))		
		return apply(
			eval(get_operator(exp), env),
			get_list_of_values(get_operands(exp), env));
	
	printf("Unknown expression type -- EVAL '");
	return make_symbol("error");
}
Beispiel #8
0
/*
 * rpn_to_namazu_query() 関数
 *
 * 説明: RPNの検索式を解析して,Namazu用の検索式に変換する。   
 * 返値: (void)
 * 引数:
 * 	(Z_RPNStructure *)rpn : 解析すべき検索式。
 *	(char *) query : Namazu用の検索文字列。
 *	(bend_searchresult *) r : Z39.50での検索結果(エラー処理用)
 */
void rpn_to_namazu_query(Z_RPNStructure *rpn, char *query, bend_searchresult *r)
{
  char left_query[BUFSIZE], right_query[BUFSIZE], operator[BUFSIZE];

  switch (rpn->which) {
  case Z_RPNStructure_complex:
    rpn_to_namazu_query(rpn->u.complex->s1, left_query, r);
    
    rpn_to_namazu_query(rpn->u.complex->s2, right_query, r);

    get_operator(operator, rpn->u.complex->roperator);

    sprintf(query, "( %s %s %s )", left_query, operator, right_query);
    break;
  case Z_RPNStructure_simple:
    get_operand(query, rpn->u.simple, r);
    break;
  default:
    strcpy(query, "!!!UNKNOWN-RPN!!!");
    logf(LOG_FATAL, "Unknown RPN Structure");
    break;
  }
}
static int eval_expression_go(struct _asm_context *asm_context, struct _var *var, struct _operator *last_operator)
{
  char token[TOKENLEN];
  int token_type;
  struct _var var_stack[3];
  int var_stack_ptr = 1;
  struct _operator operator;
  int last_token_was_op = -1;

#ifdef DEBUG
printf("Enter eval_expression_go,  var=%d/%f/%d\n", var_get_int32(var), var_get_float(var), var_get_type(var));
#endif

  memcpy(&operator, last_operator, sizeof(struct _operator));
  VAR_COPY(&var_stack[0], var);

  while(1)
  {
#ifdef DEBUG
printf("eval_expression> going to grab a token\n");
#endif
    token_type = tokens_get(asm_context, token, TOKENLEN);

#ifdef DEBUG
printf("eval_expression> token=%s   var_stack_ptr=%d\n", token, var_stack_ptr);
#endif

    // Issue 15: Return an error if a stack is full with noe operator.
    if (var_stack_ptr == 3 && operator.operation == OPER_UNSET)
    {
      return -1;
    }

    if (token_type == TOKEN_QUOTED)
    {
      if (token[0] == '\\')
      {
        int e = tokens_escape_char(asm_context, (unsigned char *)token);
        if (e == 0) return -1;
        if (token[e+1] != 0)
        {
          print_error("Quoted literal too long.", asm_context);
          return -1;
        }
        sprintf(token, "%d", token[e]);
      }
        else
      {
        if (token[1]!=0)
        {
          print_error("Quoted literal too long.", asm_context);
          return -1;
        }
        sprintf(token, "%d", token[0]);
      }

      token_type = TOKEN_NUMBER;
    }

    // Open and close parenthesis
    if (IS_TOKEN(token,'('))
    {
      if (last_token_was_op == 0 && operator.operation != OPER_UNSET)
      {
        operate(&var_stack[var_stack_ptr-2], &var_stack[var_stack_ptr-1], last_operator);
        var_stack_ptr--;
        operator.operation = OPER_UNSET;

        VAR_COPY(var, &var_stack[var_stack_ptr-1]);
        tokens_push(asm_context, token, token_type);
        return 0;
      }

      if (operator.operation == OPER_UNSET && var_stack_ptr == 2)
      {
        // This is probably the x(r12) case.. so this is actually okay
        VAR_COPY(var, &var_stack[var_stack_ptr-1]);
        tokens_push(asm_context, token, token_type);
        return 0;
      }

      struct _var paren_var;
      struct _operator paren_operator;

      paren_operator.precedence = PREC_UNSET;
      paren_operator.operation = OPER_UNSET;
      memset(&paren_var, 0, sizeof(struct _var));

      if (eval_expression_go(asm_context, &paren_var, &paren_operator) != 0)
      {
        return -1;
      }

      last_token_was_op = 0;

#ifdef DEBUG
printf("Paren got back %d/%f/%d\n", var_get_int32(&paren_var), var_get_float(&paren_var), var_get_type(&paren_var));
#endif

      VAR_COPY(&var_stack[var_stack_ptr++], &paren_var);

      token_type = tokens_get(asm_context, token, TOKENLEN);
      if (!(token[1] == 0 && token[0] == ')'))
      {
        print_error("No matching ')'", asm_context);
        return -1;
      }
      continue;
    }

    if (IS_TOKEN(token,')'))
    {
      tokens_push(asm_context, token, token_type);
      break;
    }

    // End of expression
    if (IS_TOKEN(token,',') || IS_TOKEN(token,']') || token_type == TOKEN_EOF ||
        IS_TOKEN(token,'.'))
    {
      tokens_push(asm_context, token, token_type);
      break;
    }

    if (token_type == TOKEN_EOL)
    {
      //asm_context->tokens.line++;
      tokens_push(asm_context, token, token_type);
      break;
    }

    // Read number
    if (token_type == TOKEN_NUMBER)
    {
      last_token_was_op = 0;

      if (var_stack_ptr == 3)
      {
        print_error_unexp(token, asm_context);
        return -1;
      }

      var_set_int(&var_stack[var_stack_ptr++], atoll(token));
    }
      else
    if (token_type == TOKEN_FLOAT)
    {
      if (var_stack_ptr == 3)
      {
        print_error_unexp(token, asm_context);
        return -1;
      }

      var_set_float(&var_stack[var_stack_ptr++], atof(token));
    }
      else
    if (token_type == TOKEN_SYMBOL)
    {
      last_token_was_op = 1;

      struct _operator operator_prev;
      memcpy(&operator_prev, &operator, sizeof(struct _operator));

      if (get_operator(token, &operator) == -1)
      {
        print_error_unexp(token, asm_context);
        return -1;
      }

      // Issue 15: 2015-July-21 mkohn - If operator is ~ then reverse
      // the next number.
      if (operator.operation == OPER_NOT)
      {
        int64_t num;

        if (parse_unary(asm_context, &num, OPER_NOT) != 0) { return -1; }

        if (var_stack_ptr == 3)
        {
          print_error_unexp(token, asm_context);
          return -1;
        }

        var_set_int(&var_stack[var_stack_ptr++], num);
        memcpy(&operator, &operator_prev, sizeof(struct _operator));

        last_token_was_op = 0;

        continue;
      }

      // Stack pointer probably shouldn't be less than 2
      if (var_stack_ptr == 0)
      {
        printf("Error: Unexpected operator '%s' at %s:%d\n", token, asm_context->tokens.filename, asm_context->tokens.line);
        return -1;
      }

#ifdef DEBUG
printf("TOKEN %s: precedence %d %d\n", token, last_operator->precedence, operator.precedence);
#endif

      if (last_operator->precedence == PREC_UNSET)
      {
        memcpy(last_operator, &operator, sizeof(struct _operator));
      }
        else
      if (last_operator->precedence > operator.precedence)
      {
        if (eval_expression_go(asm_context, &var_stack[var_stack_ptr-1], &operator) == -1)
        {
          return -1;
        }
      }
        else
      {
        operate(&var_stack[var_stack_ptr-2], &var_stack[var_stack_ptr-1], last_operator);
        var_stack_ptr--;
        memcpy(last_operator, &operator, sizeof(struct _operator));
      }
    }
      else
    {
      if (asm_context->pass != 1)
      {
        print_error_unexp(token, asm_context);
      }
      return -1;
    }
  }

#ifdef DEBUG
printf("going to leave  operation=%d\n", last_operator->operation);
PRINT_STACK()
#endif

  if (last_operator->operation != OPER_UNSET)
  {
    operate(&var_stack[var_stack_ptr-2], &var_stack[var_stack_ptr-1], last_operator);
    var_stack_ptr--;
  }

  VAR_COPY(var, &var_stack[var_stack_ptr-1]);

  return 0;
}
Beispiel #10
0
static int parse_ifdef_expression(struct _asm_context *asm_context, int *num, int paren_count, int precedence, int state)
{
char token[TOKENLEN];
struct _operator operator;
int token_type;
//int state=0;  // 0 = get next num to process
int not=0;
int n1=0;
int n;

  operator.operation=OPER_NONE;
  operator.precedence=precedence;
  n=*num;

  while(1)
  {
    token_type=get_token(asm_context, token, TOKENLEN);

#ifdef DEBUG
printf("debug> #if: %d) %s   n=%d paren_count=%d precedence=%d state=%d\n", token_type, token, n, paren_count, precedence, state);
#endif

    if (token_type==TOKEN_EOL || token_type==TOKEN_EOF)
    {
      pushback(asm_context, token, token_type);

      if (paren_count!=0)
      {
        print_error("Unbalanced parentheses.", asm_context);
        return -1;
      }

      if (state!=1)
      {
        print_error("Unexpected end of expression.", asm_context);
        return -1;
      }

      if (operator.operation!=OPER_NONE)
      {
        n=eval_operation(operator.operation,n1,n);
#ifdef DEBUG
printf("debug> #if eval_operation() @EOL  n=%d precedence=%d state=%d\n", n, precedence, state);
#endif
        if (n==-1) { return -1; }
      }

      *num=n;
      return 0;
    }

    if (state!=1)
    {
      if (state==2)
      {
        n1=n;
      }

      if (token_type==TOKEN_SYMBOL)
      {
        if (IS_TOKEN(token,'!'))
        {
          not^=1;
          continue;
        }
          else
        if (IS_TOKEN(token,'('))
        {
          if (parse_ifdef_expression(asm_context, &n, paren_count+1, PREC_OR, 0)==-1) return -1;
        }
          else
        if (IS_TOKEN(token,')'))
        {
          if (paren_count==0)
          {
            print_error_unexp(token, asm_context);
            return -1;
          }

          if (state!=1)
          {
            print_error("Unexpected end of expression.", asm_context);
            return -1;
          }

          if (operator.operation!=OPER_NONE)
          {
            n=eval_operation(operator.operation,n1,n);
#ifdef DEBUG
printf("debug> #if eval_operation() @paren  n=%d\n", n);
#endif
            if (n==-1) { return -1; }
          }

          *num=n;
          return 0;
        }
      }
        else
      if (token_type==TOKEN_STRING)
      {
        int param_count;
        char *value=defines_heap_lookup(&asm_context->defines_heap, token, &param_count);

        if (strcasecmp(token, "defined")==0)
        {
          n=parse_defined(asm_context);
#ifdef DEBUG
printf("debug> #if: parse_defined()=%d\n", n);
#endif
          if (n==-1) return -1;
        }
          else
        if (value!=NULL && param_count==0 && is_num(value))
        {
          n=atoi(value);
        }
          else
        {
          print_error_unexp(token, asm_context);
          return -1;
        }
      }
        else
      if (token_type==TOKEN_NUMBER)
      {
        n=atoi(token);
      }

      if (not==1)
      {
        if (n==0)
        { n=1; }
          else
        { n=0; }

        not=0;
      }

#if 0
      if (state==2)
      {
#ifdef DEBUG
printf("debug> #if eval_operation() n1=%d n=%d\n", n1, n);
#endif
        n=eval_operation(operator.operation,n1,n);
        state=0;
#ifdef DEBUG
printf("debug> #if eval_operation() n=%d operation=%d\n", n, operator.operation);
#endif
      }
#endif

      state=1;
      continue;
    }

    if (token_type==TOKEN_SYMBOL || token_type==TOKEN_EQUALITY)
    {
      struct _operator next_operator;

      if (get_operator(token, &next_operator)==-1)
      {
        print_error_unexp(token, asm_context);
        return -1;
      }

#ifdef DEBUG
printf("debug> #if get_operator() token=%s operation=%d precedence=%d\n", token, next_operator.operation, next_operator.precedence);
#endif

      if (next_operator.precedence>precedence)
      {
        pushback(asm_context, token, token_type);
        if (parse_ifdef_expression(asm_context, &n, paren_count, next_operator.precedence, 1)==-1) return -1;
      }
        else
      if (next_operator.precedence<precedence)
      {
        pushback(asm_context, token, token_type);
        return 0;
      }
        else
      {
        state=2;

        if (operator.operation!=OPER_NONE)
        {
          n=eval_operation(operator.operation,n1,n);
#ifdef DEBUG
printf("debug> #if eval_operation() @ state 2  n=%d\n", n);
#endif
          if (n==-1) { return -1; }
        }

        operator=next_operator;
      }

      continue;
    }

    print_error_unexp(token, asm_context);
    return -1;
  }

  return -1;
}
Beispiel #11
0
int is_operator(char *s) {
    return get_operator(s) != NULL;
}
Beispiel #12
0
static void
process_ucpp_token(struct ucpp_token *tok) {
	int           			*dummyptr       = n_xmalloc(sizeof *dummyptr);
	static struct input_file	infile;

#if 0
        NONE,           /* whitespace */
        NEWLINE,        /* newline */
        COMMENT,        /* comment */
        BUNCH,          /* non-C characters */
        PRAGMA,         /* a #pragma directive */
        CONTEXT,        /* new file or #line */


        SHARP,          /*      #       */
        DSHARP,         /*      ##      */

        OPT_NONE,       /* optional space to separate tokens in text output */

        DIGRAPH_TOKENS,                 /* there begin digraph tokens */

        /* for DIG_*, do not change order, unless checking undig() in cpp.c */
        DIG_LBRK,       /*      <:      */
        DIG_RBRK,       /*      :>      */
        DIG_LBRA,       /*      <%      */
        DIG_RBRA,       /*      %>      */
        DIG_SHARP,      /*      %:      */
        DIG_DSHARP,     /*      %:%:    */

        DIGRAPH_TOKENS_END,             /* digraph tokens end here */

        LAST_MEANINGFUL_TOKEN,          /* reserved words will go there */

        MACROARG,       /* special token for representing macro arguments */
#endif

        switch (tok->type) {
	case LPAR:           /*      (       */
        case RPAR:           /*      )       */
		store_token(&toklist, dummyptr,
			tok->type == LPAR? TOK_PAREN_OPEN :
				TOK_PAREN_CLOSE, lineno, NULL);
		break;
        case LBRA:           /*      {       */
        case RBRA:           /*      }       */
		store_token(&toklist, dummyptr,
			tok->type == LBRA? TOK_COMP_OPEN: TOK_COMP_CLOSE,
			lineno, NULL);
		break;
        case LBRK:           /*      [       */
        case RBRK:           /*      ]       */
		store_token(&toklist, dummyptr,
			tok->type == LBRK? TOK_ARRAY_OPEN : TOK_ARRAY_CLOSE,
			lineno, NULL);
		break;
	case SEMIC:          /*      ;       */
		store_token(&toklist, dummyptr, TOK_SEMICOLON, lineno, NULL);
		break;
	case STRING: {
		struct ty_string        *tmpstr;
		char			*str_value = tok->name;
		int			is_wide_char = 0;
	
		if (*str_value == 'L') {
			/* Wide character string */
			++str_value;
			is_wide_char = 1;
		}

		set_input_file_buffer(&infile, str_value+1); /* +1 to skip opening " */
		
		tmpstr = get_string_literal(&infile, is_wide_char);  /* not wide char?? */
		store_token(&toklist, tmpstr,
			TOK_STRING_LITERAL, lineno, NULL); 
		break;
		}
        case NAME: {           /* identifier */
		char	*ident;

		set_input_file_buffer(&infile, tok->name+1);
		ident = get_identifier(*tok->name, &infile);
		if (ident != NULL) {
			store_token(&toklist, ident,
				TOK_IDENTIFIER, lineno, n_xstrdup(tok->name));
		}
		break;
		}
	case CHAR: {
		int	err = 0;
		int	is_wide_char = 0;
		char	*str_value = tok->name;
		int	tmpi;

		if (*str_value == 'L') {
			/* Wide character string */
			++str_value;
			is_wide_char = 1;
		}

		set_input_file_buffer(&infile, str_value+1);
		tmpi = get_char_literal(&infile, &err); /* XXX cross-comp */
		if (!err) {
			int	char_type;

			/*
			 * Character literals are really treated
			 * like integer constants
			 */
			int	*tmpip = zalloc_buf(Z_CEXPR_BUF); /*n_xmalloc(16);*/ /* XXX */
			if (tmpip == NULL) {
				perror("malloc");
				exit(EXIT_FAILURE);
			}
			*tmpip = tmpi;

			if (is_wide_char) {
				char_type = backend->get_wchar_t()->code;

				/*
				 * The assignment above assumes int,
				 * i.e. 32bit on all supported
				 * platforms
				 */
				assert(backend->get_sizeof_type(
					backend->get_wchar_t(), NULL) == 4);
			} else {
				char_type = TY_INT;
			}
			store_token(&toklist, tmpip, char_type, lineno, n_xstrdup(tok->name));
		}
		is_wide_char = 0;
		break;
		}
	case NUMBER: {
		struct num	*n;

		set_input_file_buffer(&infile, tok->name+1);
		n = get_num_literal(*tok->name, &infile);
		if (n != NULL) {
			store_token(&toklist, n->value,
				n->type, lineno, n_xstrdup(tok->name));
		} else {
			lexerror("Couldn't read numeric literal");
		}
		break;
		}
	case MDOTS: {
		int	*tmp = n_xmalloc(sizeof *tmp);
		*tmp = 0; 
		store_token(&toklist, tmp, TOK_ELLIPSIS, lineno, NULL);
		break;
		}
	case SLASH:          /*      /       */
	case ASSLASH:        /*      /=      */
	case MINUS:          /*      -       */
	case MMINUS:         /*      --      */
	case ASMINUS:        /*      -=      */
	case ARROW:          /*      ->      */
	case PLUS:           /*      +       */
	case PPLUS:          /*      ++      */
	case ASPLUS:         /*      +=      */
	case LT:             /*      <       */
	case LEQ:            /*      <=      */
	case LSH:            /*      <<      */
	case ASLSH:          /*      <<=     */
	case GT:             /*      >       */
	case GEQ:            /*      >=      */
	case RSH:            /*      >>      */
	case ASRSH:          /*      >>=     */
	case ASGN:           /*      =       */
	case SAME:           /*      ==      */
#ifdef CAST_OP
	case CAST:           /*      =>      */
#endif
	case NOT:            /*      ~       */
	case NEQ:            /*      !=      */
	case AND:            /*      &       */
	case LAND:           /*      &&      */
	case ASAND:          /*      &=      */
	case OR:             /*      |       */
	case LOR:            /*      ||      */
	case ASOR:           /*      |=      */
	case PCT:            /*      %       */
	case ASPCT:          /*      %=      */
	case STAR:           /*      *       */
	case ASSTAR:         /*      *=      */
	case CIRC:           /*      ^       */
	case ASCIRC:         /*      ^=      */
	case LNOT:           /*      !       */
	case COMMA:          /*      ,       */
	case QUEST:          /*      ?       */
	case COLON:          /*      :       */
	case DOT:            /*      .       */
        case UPLUS: /* unary + */
        case UMINUS:          /* unary - */
		{
		int	*opval = n_xmalloc(sizeof *opval);
		char	*optext = operators_name[tok->type];

		set_input_file_buffer(&infile, optext+1);
		*opval = get_operator(*optext, &infile, &optext); /* XXX cross-comp */
		if (*opval == -1) {
			lexerror("Invalid operator `%s'", optext);
			free(opval);
		} else {
			store_token(&toklist, opval, TOK_OPERATOR, lineno, tok->name);
		}
		break;
		}
	default:
		printf("Unhandled token, type %d, value %s\n", tok->type, tok->name? tok->name: "?");
		break;
	}

	return NULL;
}
Beispiel #13
0
static void cc_operator_attack_rate(Ym_driver *driver, uint8_t controller,
  uint8_t channel, uint8_t value)
{
    ym_set_attack_rate(driver, channel, get_operator(controller),
      value/scale(32));
}
Number shunting_yard(std::vector<std::string> & tokens, std::vector<std::string> & out_ops, bool boolean_exp = false) {
    prepare();
    std::string previous_token;
    Operator * op;
    Operator * previous_op = new Sum();
    std::string last_token = "";
    std::string token;

    for(auto s = tokens.begin(); s != tokens.end(); ++s) {
        token = *s;
        //std::cout<<token<<std::endl;
        if(is_number(token)) {
            if(is_number(previous_token)) {
                throw std::string("Too many operands");
            }
            if(previous_op && previous_op->sign() == ")") {
                throw std::string("Missing operation between paretheses");
            }
            Number i = parse_number(token);
            if(i >= Number("10", "99") || i <= Number("-10", "99")) {
                //std::cout<<i<<'\n';
                throw std::string("Number out of valid range");
            }

            if(is_variable(token)) {
                std::stringstream g;
                g << i;
                out_ops.push_back(token + "= " + g.str());
            }
            output_stack.push(i);
            previous_op = nullptr;
        }
        else if((op = get_function_op(token)) != nullptr) {
            operator_stack.push(op);
        }

        else if (token == ",") {
            while(!operator_stack.empty() && operator_stack.top()->sign() != "(") {
                evaluate(operator_stack.top(), out_ops);
                operator_stack.pop();
            }
            // error
            if(operator_stack.empty()) {
                throw std::string("mismatched parens");
            }
            // dirty fix, the problem is that in get_operator we only return a
            // negative if there was an operator before, so root(3, -27) was being
            // treated as a substraction
            previous_op = new Sum();
        }

        else if((op = get_operator(token, previous_op, boolean_exp)) != nullptr) {
            if(op->sign() == "(") {
                if(!previous_op || (previous_op && previous_op->sign() == ")" )) {
                    throw std::string("Missing operation between paretheses");
                }
                operator_stack.push(op);
            } else if(op->sign() == ")") {
                while(!operator_stack.empty() && operator_stack.top()->sign() != "(") {
                    evaluate(operator_stack.top(), out_ops);
                    operator_stack.pop();
                }
                // error
                if(operator_stack.empty()) {
                    throw std::string("mismatched parens");
                }
                operator_stack.pop();
                if(!operator_stack.empty() && operator_stack.top()->sign() == "r") {
                    evaluate_function(operator_stack.top(), out_ops);
                    operator_stack.pop();
                }
            }
            else {
                while(!operator_stack.empty() &&
                        ( (op->associativity() == assoc::LEFT && op->precedence() <= operator_stack.top()->precedence())
                          ||
                          (op->associativity() == assoc::RIGHT && op->precedence() < operator_stack.top()->precedence())))
                {
                    evaluate(operator_stack.top(), out_ops);
                    operator_stack.pop();
                }
                operator_stack.push(op);
            }
            previous_op = op;
        }

        else if(token == "=" && !boolean_exp) {
            if(s+1 != tokens.end())
                last_token = *(s+1);
            break;
        }
        // unknown token
        else {
            throw std::string("Unexpected Token '" + token + "'");
        }
        previous_token = token;
    }

    while(!operator_stack.empty()) {
        op = operator_stack.top();
        if(op->sign() == "(") {
            throw std::string("mismatched parens");
        }
        operator_stack.pop();
        evaluate(op, out_ops);
    }

    if(token != "=" && !boolean_exp) {
        throw std::string("Missing =");
    }

    if(!last_token.empty() && !boolean_exp) {
        if(var_map.find(last_token) != var_map.end()) {
            var_map[last_token] = output_stack.top();
            if(tokens[tokens.size()-1] != last_token) {
                throw std::string("Warning, no more expressions after variable assignment");
            }
            // out ops A=
            std::stringstream ss;
            ss << output_stack.top();
            out_ops.push_back(last_token + "= " + ss.str());
            //std::cout << var_map[last_token] << '\n';
        }
        else {
            throw std::string("Warning, no more expressions after =");
        }

    }
    if(output_stack.empty()) return Number ("0","0");

    Number ans = output_stack.top();
    output_stack.pop();
    if(!output_stack.empty()) throw std::string("too many arguments to function");
    return ans;

}
Beispiel #15
0
Status push_multiplication(Stack **operands, Stack **operators)
{
    return push_operator(get_operator('*', OPERATOR_BINARY), operands, operators);
}
Beispiel #16
0
/* combine two expression with an operator. Unary operators
** only use the first argument.
** The function automatically chooses that operator that correctly
** converts the sub expressions to the correct types.
** If no operator is given, the two expressions are combined into
** a list. If only the first expression is given and no operator,
** then an evaluate operator is added if necessary, which ensures
** that the value is placed in a stack variable (which needed for
** concurrent assignments).
*/
Expression *combine_expression(Expression *e1, Expression *e2,
			       Operator op)
{
  Expression *te, *tf;
  OpStruct *os;
  int i;
  Type *restype;
  Type t[3];
  if (!op) {
      i=1;
      te=e1;
      while (1) {
	  if (te->type==ArgType) i=1;
	  else i=0;
	  if (!te->next) break;
	  te=te->next;
      }
      if (!e2 && i) {
	  te->next=malloc(sizeof(Expression));
	  te->next->restype=NoRefType(te->restype);
	  te=te->next;
	  te->type=OpType;
	  te->delta=-1;
	  te->val.op=0;
	  te->next=NULL;
      } else {
	  te->next=e2;
      }
      return e1;
  }
  restype = type_of_expression(e1);
  /* e1 could result in a list of expressions.
  ** a combination would use the last element from that list
  */
  for (i=0; restype[i]; i++);
  if (i) i--; /* else restype[0]==0 */
  t[0] = restype[i];
  if (e2) {
      restype = type_of_expression(e2);
      t[1]=restype[0];
      t[2]=0;
  } else t[1]=0;
  os=get_operator(t[0], op, t[1]);
  if (!os) {
      /* no operator for that type combination */
      fprintf(stderr, "Operator not defined for combination (%s %s %s)\n",
	      lookup_typename(t[0]), op_name[op], lookup_typename(t[1]));
      return NULL;
  }
  /* automatic type conversion should be added to both expressions */
  /* or operator functions have to be defined for all possible combinations */
  te = (Expression*) malloc(sizeof(Expression));
  te->type=OpType;
  te->delta=(t[1]>0)?-2:-1;
  te->val.ifunc=os->ifunc;
  te->restype=os->restype;
  tf=e1;
  while (tf->next) tf=tf->next;
  tf->next=e2;
  while (tf->next) tf=tf->next;
  tf->next=te;
  te->next=NULL;
  return e1;
}
Beispiel #17
0
static void cc_operator_freq_multiplier(Ym_driver *driver, uint8_t controller,
  uint8_t channel, uint8_t value)
{
    ym_set_multiplier(driver, channel, get_operator(controller),
      value/scale(16));
}
Beispiel #18
0
Status parse(const Token *tokens, Stack **operands, Stack **operators, Stack **functions)
{
    Status status = OK;
    const Token *token, *previous, *next;

    for (token = tokens, previous = &NO_TOKEN, next = token + 1;
         token->type != TOKEN_NONE; previous = token, token = next++)
    {
        switch (token->type)
        {
            case TOKEN_OPEN_PARENTHESIS:
            {
                // Implicit multiplication: "(2)(2)".
                if (previous->type == TOKEN_CLOSE_PARENTHESIS)
                {
                    status = push_multiplication(operands, operators);
                }

                stack_push(operators, get_operator('(', OPERATOR_OTHER));
                break;
            }

            case TOKEN_CLOSE_PARENTHESIS:
            {
                // Apply operators until the previous open parenthesis is found.
                bool found_parenthesis = false;

                while (*operators && status == OK && !found_parenthesis)
                {
                    const Operator *operator = stack_pop(operators);

                    if (operator->symbol == '(')
                    {
                        found_parenthesis = true;
                    }
                    else
                    {
                        status = apply_operator(operator, operands);
                    }
                }

                if (!found_parenthesis)
                {
                    status = ERROR_CLOSE_PARENTHESIS;
                }
                else if (*functions)
                {
                    status = apply_function(stack_pop(functions), operands);
                }

                break;
            }

            case TOKEN_OPERATOR:
            {
                status = push_operator(
                    get_operator(*token->value, get_arity(*token->value, previous)),
                    operands, operators);

                break;
            }

            case TOKEN_NUMBER:
            {
                if (previous->type == TOKEN_CLOSE_PARENTHESIS ||
                        previous->type == TOKEN_NUMBER ||
                        previous->type == TOKEN_IDENTIFIER)
                {
                    status = ERROR_SYNTAX;
                }
                else
                {
                    status = push_number(token->value, operands);

                    // Implicit multiplication: "2(2)" or "2a".
                    if (next->type == TOKEN_OPEN_PARENTHESIS ||
                            next->type == TOKEN_IDENTIFIER)
                    {
                        status = push_multiplication(operands, operators);
                    }
                }

                break;
            }

            case TOKEN_IDENTIFIER:
            {
                // The identifier could be either a constant or function.
                status = push_constant(token->value, operands);
                if (status == ERROR_UNDEFINED_CONSTANT &&
                        next->type == TOKEN_OPEN_PARENTHESIS)
                {
                    stack_push(functions, token->value);
                    status = OK;
                }
                else if (next->type == TOKEN_OPEN_PARENTHESIS ||
                           next->type == TOKEN_IDENTIFIER)
               {
                    // Implicit multiplication: "a(2)" or "a b".
                    status = push_multiplication(operands, operators);
                }

                break;
            }

            default:
            {
                status = ERROR_UNRECOGNIZED;
            }
        }

        if (status != OK)
        {
            return status;
        }
    }

    // Apply all remaining operators.
    while (*operators && status == OK)
    {
        const Operator *operator = stack_pop(operators);

        if (operator->symbol == '(')
        {
            status = ERROR_OPEN_PARENTHESIS;
        }
        else
        {
            status = apply_operator(operator, operands);
        }
    }

    return status;
}
Beispiel #19
0
int main( int argc, char * argv[] )
{
	int tmp;
	int i = 0;
	int num1;
	int num2;
	int new_num;
	char op;

	char * src; 

	char cur_op;
	char top_op;

	printf( "expression value demo begin !\n" );
#if 0
	push_int( 100 );

	push_int( 200 );

	tmp = pop_int();
	printf( "pop is %d \n", tmp );
	
	tmp = pop_int();
	printf( "pop is %d \n", tmp );
#endif
	if( argc > 1 )
		printf( "input expression string is %s \n", argv[1] );
	else 
		exit(0);

	src = argv[1];

	push_char( '\0');

	while( 1 )
	{
		printf( "src[%d] = %c \n", i, src[i] );	
get_num:		
		/* get a number */
		num1 = get_number( src[i] );
		if( num1 >= 0 )
			printf( "get a number : %d \n", num1 );	
		else
			break;

		/* push this number */
		printf( "push current int : %d \n", num1 );
		push_int( num1 );

		/* get the next op */
		i++;

		cur_op = get_operator( src[i] );
		if( cur_op > 0 )
			printf( "get a operator: %c \n", cur_op );	
		else if( cur_op == '\0' )
		{
			printf( "get a operator == 0: %c \n", cur_op );	
		}

cmp_op:
		top_op = get_top_char();
		printf( "get top stack operator: %c \n", top_op );	
		
		/* if current op > stack top op, then push current op */
		if( get_prio( cur_op ) > get_prio( top_op ) )
		{
			printf( "<push> push current op : %c \n", cur_op );
			push_char( cur_op );
			
			printf( "<push> push ok!\n" );
		}
		else
		{
			op = pop_char();
			num2 = pop_int();
			if( op == '\0' )
			{ 
				printf( "op == 0, last result = %d \n", num2 );
				exit( 0 );
			}

			num1 = pop_int();
			
			printf( "<calc> pop 2 num and 1 op, do calc: %d %c %d \n", num1, op, num2 );
			new_num = calc( num1, num2, op );
			printf( "get calc result: %d \n", new_num );
		
			/* push this new number */
			printf( "push new int : %d \n", new_num );
			push_int( new_num );

			goto cmp_op;
		}

		/* get the next op */
		i++;		
	} 

	return 0;
}
Beispiel #20
0
static void cc_operator_freq_detune(Ym_driver *driver, uint8_t controller,
  uint8_t channel, uint8_t value)
{
    ym_set_detune(driver, channel, get_operator(controller),
      value/scale(8));
}
Beispiel #21
0
static void cc_operator_d1l(Ym_driver *driver, uint8_t controller,
  uint8_t channel, uint8_t value)
{
    ym_set_d1l(driver, channel, get_operator(controller),
      value/scale(16));
}
Beispiel #22
0
/*
 * 名前: rpn_to_resultset() 関数
 *
 * 説明: RPNを階層的に検索して結果集合を求める。
 * 返値: (void)
 * 引数:
 *	Z_RPNStructure *rpn : RPN
 *	char *resultfile: 結果集合ファイル
 * 	bend_searchresult *r : (エラー処理用)
 */
void rpn_to_resultset(Z_RPNStructure *rpn, char *resultfile, bend_searchresult *r)
{
  char cmd_string[BUFSIZE];
  char operator[BUFSIZE];
  char query[BUFSIZE], left_query[BUFSIZE], right_query[BUFSIZE];
  char left_resultfile[BUFSIZE], right_resultfile[BUFSIZE];

  switch (rpn->which) {
  case Z_RPNStructure_complex:

    get_operator(operator, rpn->u.complex->roperator);
    
    if (parse_rpn_structure(rpn)) {
      sprintf(left_resultfile, "%s.l", resultfile);
      rpn_to_resultset(rpn->u.complex->s1, left_resultfile, r);
      sprintf(right_resultfile, "%s.r", resultfile);
      rpn_to_resultset(rpn->u.complex->s2, right_resultfile, r);
      if (!strcmp(operator, "and")) {
	sprintf(cmd_string, "sort %s %s | uniq -d > %s",
		left_resultfile, right_resultfile, resultfile);
      } else if (!strcmp(operator, "or")) {
	sprintf(cmd_string, "sort %s %s | uniq > %s",
		left_resultfile, right_resultfile, resultfile);
      } else if (!strcmp(operator, "not")) {
	sprintf(cmd_string, "sort %s %s %s | uniq -u > %s",
		left_resultfile, right_resultfile, right_resultfile, resultfile);
      }
      system(cmd_string);
      logf(LOG_LOG, "%s", cmd_string);
    } else {
      rpn_to_namazu_query(rpn->u.complex->s1, left_query, r);
      rpn_to_namazu_query(rpn->u.complex->s2, right_query, r);
      sprintf(query, "( %s %s %s )", left_query, operator, right_query);
      longvowel_to_hyphen(query);
      sprintf(cmd_string,
	      "%s %s \"%s\" %s > %s",
	      NAMAZU_PATH, NAMAZU_OPTION, query, NAMAZU_DATABASE, resultfile);
      system(cmd_string);
      logf(LOG_LOG, "%s", cmd_string);
    }
    break;
  case Z_RPNStructure_simple:
    if (parse_rpn_structure(rpn)) {
      sprintf(cmd_string, "ln -s %s-%d.%s %s",
	     RESULTFILE, getpid(), rpn->u.simple->u.resultSetId, resultfile);
      system(cmd_string);
      logf(LOG_LOG, "%s", cmd_string);
    } else {
      get_operand(query, rpn->u.simple, r);
      longvowel_to_hyphen(query);
      sprintf(cmd_string,
	      "%s %s \"%s\" %s > %s",
	      NAMAZU_PATH, NAMAZU_OPTION, query, NAMAZU_DATABASE, resultfile);
      system(cmd_string);
      logf(LOG_LOG, "%s", cmd_string);
    }
    break;
  default:
    logf(LOG_FATAL, "Unknown RPN Structure");
    break;
  }
}
Beispiel #23
0
int main(void)
{
  
  char a, o;    
  int flush, r;
  float digits_a, digits_b;
  
  flush = r = 0; 
  digits_a = digits_b = 0;
 
do
  {
    digits_a = get_operand();
    
    o = get_operator();
    while (o != 'c')
      {

	
	digits_b = get_operand();
	
	
	switch(o)
	  {
	    
	  case '+':
	    r = add(digits_a, digits_b);
	    break;
	    
	    
	  case '-':
	    r = subtract(digits_a, digits_b);
	    
	    
	  case '*':
	    r = multiply(digits_a, digits_b);
	    break;
	    
	    
	  case '/':
	    r = division(digits_a, digits_b);
	    break;
	    	    
	    
	  case 'e':
	    r = exponent(digits_a, digits_b);
	    break;
	    
	    
	  default:
	    printf("\nINVALID OPERATOR\n");
	    break;
	    
	  } /* end of SWITCH */
	
	printf("\n\nResult = %d\n",r);
	
	digits_a = r;
	o = get_operator();
	
      } /* while o != clear */
    
    printf("\nEnter  n  to quit, or\n");
    printf("enter  y  to do another operation: ");
    
    a = getchar();
    
    if (a == 'y')
      {
	while (flush != '\n')
	  {
	    flush = getchar();
	  }
      }
  }while (a == 'y');

return 0;
}
Beispiel #24
0
static int
parse_stdin (FILE *infile, time_t *ref, int round, const char *format)
{
    char *input = NULL;
    char result[1024];
    size_t inputsize;
    ssize_t len;
    struct tm tm;
    time_t t;
    int r;

    while ((len = getline (&input, &inputsize, infile)) != -1) {
	const char *oper;
	char *trail, *tmp;

	/* trail is trailing whitespace and (optional) comment */
	trail = strchr (input, '#');
	if (!trail)
	    trail = input + len;

	while (trail > input && isspace ((unsigned char) *(trail-1)))
	    trail--;

	if (trail == input) {
	    printf ("%s", input);
	    continue;
	}

	tmp = strdup (trail);
	if (!tmp) {
	    fprintf (stderr, "strdup() failed\n");
	    continue;
	}
	*trail = '\0';
	trail = tmp;

	/* operator */
	oper = find_operator_in_string (input, &tmp, &round);
	if (oper) {
	    *tmp = '\0';
	} else {
	    oper = get_operator (round);
	    assert (oper);
	}

	r = parse_time_string (input, &t, ref, round);
	if (!r) {
	    if (!localtime_r (&t, &tm)) {
		fprintf (stderr, "localtime_r() failed\n");
		free (trail);
		continue;
	    }

	    strftime (result, sizeof (result), format, &tm);
	} else {
	    const char *errstr = parse_time_strerror (r);
	    if (errstr)
		snprintf (result, sizeof (result), "ERROR: %s", errstr);
	    else
		snprintf (result, sizeof (result), "ERROR: %d", r);
	}

	printf ("%s%s %s%s", input, oper, result, trail);
	free (trail);
    }

    free (input);

    return 0;
}
Beispiel #25
0
static void cc_operator_amplitude(Ym_driver *driver, uint8_t controller,
  uint8_t channel, uint8_t value)
{
    ym_set_amplitude(driver, channel, get_operator(controller),
      value/scale(128));
}