Example #1
0
std::wstring get_exp(const node* p)
{
	if (!p) return L"";
	if (p->t == nt_num)
	{
		std::wostringstream oss;
		oss << p->num;
		return get_trans(p, oss.str());
	}
	std::wstring lexp = get_exp(p->l_child);
	std::wstring rexp = get_exp(p->r_child);
	
	if (p->l_child->t == nt_op && get_pred(p->l_child->op) < get_pred(p->op))
	{
		lexp = std::wstring(L"(") + lexp + L")";
	}
	if (p->r_child->t == nt_op && !(get_pred(p->op) < get_pred(p->r_child->op)))
	{
		rexp = std::wstring(L"(") + rexp + L")";
	}
	
	std::wstring e;
	if (p->op == L'_') 
		e = lexp + rexp;
	else 
		e = lexp + L" " + p->op + L" " + rexp;
	return get_trans(p, e);
}
Example #2
0
uint8_t octet_ops::product(uint8_t u, uint8_t v)
{
    if (u == 0 || v == 0) {
        return 0;
    }
    return (uint8_t)get_exp(get_log(u) + get_log(v));
}
AstIdentifier* AstIdentifier::make(const string & id)
{
	AstIdentifier* i = new AstIdentifier(id);
	Expression* res = get_exp(i);
	assert(res->get_type() == AST_IDENTIFIER);
	return static_cast<AstIdentifier*>(res);
}
int main() {
	int t, n, m;
	matrix A, B, F;

	A.a1 = 1; A.a2 = 1; A.a3 = 1; A.a4 = 0;
	F.a1 = 6; F.a2 = 4; F.a3 = 4; F.a4 = 2;
	LL delta;

	scanf("%d", &t);

	while(t--) {
        scanf("%d", &n);
        scanf("%d", &m);

		if(n == 0) {
			printf("0\n");
			continue;
		} else if(n == 1) {
			printf("1\n");
			continue;
		}

		B = get_exp(A, n-1, m);
		B = product(B, F, m);
		delta = ((n+2) / m + 1) * m;
		printf("%lld\n", (B.a2 + delta-n-2) % m);
	}

	return 0;
}
Example #5
0
void show_float(unsigned uf)
{
  float f = u2f(uf);
  unsigned exp = get_exp(uf);
  unsigned frac = get_frac(uf);
  unsigned sign = get_sign(uf);

  printf("\nFloating point value %.10g\n", f);
  printf("Bit Representation 0x%.8x, sign = %x, exponent = 0x%.2x, fraction = 0x%.6x\n",
	 uf, sign, exp, frac);
  if (exp == EXP_MASK) {
    if (frac == 0) {
      printf("%cInfinity\n", sign ? '-' : '+');
    } else
      printf("Not-A-Number\n");
  } else {
    int denorm = (exp == 0);
    int uexp = denorm ? 1-BIAS : exp - BIAS;
    int mantissa = denorm ? frac : frac + (1<<FRAC_SIZE);
    float fman = (float) mantissa / (float) (1<<FRAC_SIZE);
    printf("%s.  %c%.10f X 2^(%d)\n",
	   denorm ? "Denormalized" : "Normalized",
	   sign ? '-' : '+',
	   fman, uexp);
  }
}
Example #6
0
/************************************************
 * this must not be used inside the basic - this is
 * only interpolation of the variable
 *          OR
 *  solving a formula
 *
 * Look up a a bas_token's internal representation in the
   bas_token table.
   *
   * HO HO HO. What if s is formula? with   *+-/
   *   
   *
*/
double lookup_table2(char* s){
  //  register int i,j;
   int i;

  /*
   *   solve a formula or just call lookup_table( s )
   */
  //    printf("...........%s..............\n", s );
  if (   (strpbrk( s ,  "+" )!=NULL)||   
	 (strpbrk( s ,  "-" )!=NULL)||  
	 (strpbrk( s ,  "*" )!=NULL)||    
	 (strpbrk( s ,  "/" )!=NULL)    	 
     ){
    //   printf("............. found a formula\n%s","");
  double value;
  prog=s;
  bas_token_type = get_token(); putback();
  get_exp(&value);
  //  printf("toktyp=%d, value = %lf\n",bas_token_type, value );
  return value;
  }// expr
  else{ // standard   lookup_table( s )
	int io=lookup_table_tk(s);
	//  printf("............. NOT a formula, the var sits at pos %d\n",  io  );
	return variables[io];
  }

  return 0.0; /* unknown command */
}//------------------------lookup_table  2 
AstIdentifierList* AstIdentifierList::make(AstIdentifier* id)
{
	AstIdentifierList* l = new AstIdentifierList(id);
	Expression* res = get_exp(l);
	assert(res->get_type() == AST_IDENTIFIER_LIST);
	return static_cast<AstIdentifierList*>(res);
}
// Using matrix exponentiation
matrix get_exp(matrix B, LL n, int M) {
	if(n == 1) return B;

	matrix C = get_exp(B, n/2, M);
	C = product(C, C, M);

	if(n % 2 == 1) return product(B, C, M);
	return C;
}
Example #9
0
void iterate_num_permutation(node* exp, node** num_nodes, double* nums, int num_count, double result, int rr_level)
{
	do
	{
		for (int i = 0; i < num_count; i++) num_nodes[i]->num = nums[i];
		if (check_exp(exp, rr_level))
		{
			if (g_debug)
			{
		    	std::wcout << get_exp(exp) << " = " << exp->val() << std::endl;
			}
			if (double_equ(exp->val(), result))
			{
				std::wcout << get_exp(exp) << " = " << result << std::endl;
			}
		}
	}while (std::next_permutation(nums, nums + num_count));
}
Example #10
0
static ast::VarDec* get_VarDec(Location *vardec_location)
{
  symbol::Symbol *name = get_Symbol();
  ast::VarDec::Kind kind = get_VarDec_Kind();
  ast::Exp *init = get_exp();
  ast::VarDec* vardec = new ast::VarDec(*vardec_location, *name, *init);
  vardec->kind_set(kind);
  return vardec;
  }
Example #11
0
ast::Exp* scicaml_string2ast(char *buffer)
{
  // std::cerr << "scicaml_string2ast" << std::endl;
  buf = (unsigned char*)buffer;
  initial_buf = (unsigned char*)buffer;
  int buflen = get_uint32();
  ast::Exp* new_ast = get_exp();
  return new_ast;
}
Example #12
0
cell_list *find_depend(char *str)
{
    double hold;
    last_dep = NULL;
    find_var = &depend_callback;
    set_exp(str);
    get_exp(&hold);

    return last_dep;
}
Example #13
0
uint8_t octet_ops::division(uint8_t u, uint8_t v)
{
    if (v == 0) {
        throw std::invalid_argument("Denominator cannot be 0.");
    }
    if (u == 0) {
        return 0;
    }
    return (uint8_t)get_exp((get_log(u) - get_log(v)) + 255);
}
Example #14
0
static std::list<ast::Exp*>* get_exps(void)
{
  int nitems = get_uint32();
  std::list<ast::Exp*> *list = new  std::list<ast::Exp*>;
  for(int i = 0; i < nitems; i++){
    ast::Exp* exp = get_exp();
    list->push_back(exp);
  }
  return list;
}
Example #15
0
static std::list<ast::Var*>* get_vars(void)
{
  int nitems = get_uint32();
  std::list<ast::Var*> *list = new  std::list<ast::Var*>;
  for(int i = 0; i < nitems; i++){
    ast::Var* var = dynamic_cast<ast::Var*>(get_exp());
    list->push_back(var);
  }
  return list;
}
Example #16
0
/* *
 * helper function to get the args
 * */
static char * _get_arg(char * name) {
  char * exp = get_exp();
  if (exp == NULL) {
    require_arg(name);
  } 
#ifdef DEBUG
  fprintf(stderr, "expression is %s\n", name);
  fprintf(stderr, "arg is %s\n", exp);
#endif
  return exp;
}
Example #17
0
/* Execute an IF statement. */
void exec_if()
{
  int   cond;
  double x;
  //  char op;

  //  printf("if:ini bas_token=%s \n", bas_token );
  get_exp(&x); // get left expression 

  // ORIGINAL
  /*
  get_token(); // get the operator 
  if(!strchr("=<>", *bas_token)) {
    serror(0); // not a legal operator 
    return;
  }
  op=*bas_token;  

  get_exp(&y); // get right expression 
*/
  //  printf("if: bas_token=%s  x=%4d \n", bas_token,  x );

  //NEUMIME =
  cond = (int) x;  //20100422
  // cond=int(x);  //  expresion x gives 1 or 0
  // determine the outcome 
  /*  cond = 0;
  switch(op) {
    case '<':
      if(x<y) cond=1;
      break;
    case '>':
      if(x>y) cond=1;
      break;
    case '=':
      if(x==y) cond=1;
      break;
  }
  */


  if(cond) { /* is true so process target of IF */
    get_token();
    if(bas_tok!=THEN) {
      serror(8);
      return;
    }/* else program execution starts on next line */
  }
  else find_eol(); /* find start of next line */
}
Example #18
0
/* Execute a FOR loop. */
void exec_for()
{
  struct for_stack i;
  double value;

  get_token(); /* read the control variable */
  if(!isalpha(*bas_token)) {
    serror(4);
    return;
  }

  i.var=lookup_table();//toupper(*bas_token)-'A'; /* save its index */

  get_token(); /* read the equals sign */
  if(*bas_token!='=') {
    serror(3);
    return;
  }

  get_exp(&value); /* get initial value */

  variables[i.var]=value;

  get_token();
  if(bas_tok!=TO) serror(9); /* read and discard the TO */

  get_exp(&i.target); /* get target value */

  /* if loop can execute at least once, push info on stack */
  if(value>=variables[i.var]) { 
    i.loc = prog;
    fpush( &i);// 20100422  -  i
  }
  else  /* otherwise, skip loop code altogether */
    while(bas_tok!=NEXT) get_token();
}
Example #19
0
int					hdl_coef(t_dtab *token)
{
	unsigned int	i;
	t_tok			tmp;

	get_exp(&tmp);
	i = 0;
	while (++i < token->size)
	{
		if (((t_tok *)token->data)[i].type == TOK_COEF && (((t_tok *)token->data)[i + 1].type == TOK_OP || ((t_tok *)token->data)[i + 1].type == TOK_EQ || ((t_tok *)token->data)[i + 1].type == TOK_EOF))
		{
			if (!dtab_insert(token, i + 1, &tmp))
				return (ERR_ML);
		}
	}
	return (NO_ERR);
}
Example #20
0
/* Execute a simple version of the BASIC PRINT statement */
void print()
{
  double answer;
  int len=0, spaces;
  char last_delim; //  warning from compile-may be used uninited
  // I TRY TO MAKE PUT SOME VALUE FOR COMPILETIME
  last_delim = *bas_token; 

  do {
    get_token(); /* get next list item */
    if(bas_tok==EOL || bas_tok==FINISHED) break;
    if(bas_token_type==QUOTE) { /* is string */
      printf("%s\n",bas_token);
      len += strlen(bas_token);
      get_token();
    }
    else { /* is expression */
      putback();
      get_exp(&answer);
      get_token();
      len += printf("%g", answer);
    }
    last_delim = *bas_token; 

    if(*bas_token==';') {
      /* compute number of spaces to move to next tab */
      spaces = 8 - (len % 8); 
      len += spaces; /* add in the tabbing position */
      while(spaces) { 
	printf(" ");
        spaces--;
      }
    }
    else if(*bas_token==',') /* do nothing */;
    else if(bas_tok!=EOL && bas_tok!=FINISHED) serror(0); 
  } while (*bas_token==';' || *bas_token==',');

  if(bas_tok==EOL || bas_tok==FINISHED) {
    if(last_delim != ';' && last_delim!=',') printf("\n");
  }
  else serror(0); /* error is not , or ; */
  //  return 0;
}//print--------------------------------------------
Example #21
0
/* Assign a variable a value. */
int assignment(){
  int var; double value;

  /* get the variable name */
  get_token();
  // printf("new assignement <%s>\n", bas_token );
  if(!isalpha(*bas_token)) {
    serror(4);
    return 0;
  }
  /*
   *  howto make a table of variables?
   */
  var = lookup_table();// toupper(*bas_token)-'A';

  //  printf("assign <%s> retvar=%d ", bas_token, var );

  /* get the equals sign */
  get_token();
  // printf(" <%s> ", bas_token );
  if(*bas_token!='=') {
    //    printf("assignment%s\n","");
    serror(3);
    return 0;
  }

  /* get the value to assign to var */
  //  printf(" going to get_exp with bas_token <%s> \n ", bas_token );
 get_exp(&value);
 //  printf(" = <%lf> (outcome)\n ", value );

  /* assign the value */
  variables[var] = value;
  //   printf("#<%d> val=<%lf>\n",  var, value );
  return 0; // ????? 
}//--------------------------assignment
Example #22
0
/*
 * interface, not static 
 */
void init_filter_tree(int argc) {
  char * exp;
  int exp_num = 0;
  
  init_op_stack(argc);


  filter_list_size = argc;
  filter_list_len = 0;
  filter_list = (Filter **)(malloc(sizeof(Filter) * argc));

  while((exp = get_exp()) != NULL) {
    exp_num++;
    char * optarg;
    //all the exps
    if (IS_EQUAL(exp, "-name")) {
      optarg = _get_arg("-name");
      init_fnmatch(optarg, true);
    } else if (IS_EQUAL(exp, "-iname")) {
      optarg = _get_arg("-iname");
      init_fnmatch(optarg, false);
    } else if (IS_EQUAL(exp, "-user")) {
      optarg = _get_arg("-user");
      init_user(optarg);
    } else if (IS_EQUAL(exp, "-group")) {
      optarg = _get_arg("-group");
      init_group(optarg);
    } else if (IS_EQUAL(exp, "-perm")) {
      optarg = _get_arg("-perm");
      init_perm(optarg);
    } else if (IS_EQUAL(exp, "-regex")) {
      optarg = _get_arg("-regex");
      init_reg(optarg);
    } else if (IS_EQUAL(exp, "-amin")) {
      optarg = _get_arg("-amin");
      init_time(AMIN, optarg);
    } else if (IS_EQUAL(exp, "-atime")) {
      optarg = _get_arg("-atime");
      init_time(ATIME, optarg);
    } else if (IS_EQUAL(exp, "-anewer")) {
      optarg = _get_arg("-anewer");
      init_time(ANEWER, optarg);
    } else if (IS_EQUAL(exp, "-cnewer")) {
      optarg = _get_arg("-cnewer");
      init_time(CNEWER, optarg);
    } else if (IS_EQUAL(exp, "-cmin")) {
      optarg = _get_arg("-cmin");
      init_time(CMIN, optarg);
    } else if (IS_EQUAL(exp, "-ctime")) {
      optarg = _get_arg("-ctime");
      init_time(CTIME, optarg);
    } else if (IS_EQUAL(exp, "-mtime")) {
      optarg = _get_arg("-mtime");
      init_time(MMIN, optarg);
    } else if (IS_EQUAL(exp, "-mnewer")) {
      optarg = _get_arg("-mnewer");
      init_time(MNEWER, optarg);
    } else if (IS_EQUAL(exp, "-type")) {
      optarg = _get_arg("-type");
      init_filetype(optarg);
    } else if (IS_EQUAL(exp, "-size")) {
      optarg = _get_arg("-size");
      init_filesize(optarg);
    } else if (IS_EQUAL(exp, "-not")) {
#ifdef DEBUG
      fprintf(stderr, "filter not adapter\n");
#endif
      filter_not();
    } else if (IS_EQUAL(exp, "-and")) {
#ifdef DEBUG
      fprintf(stderr, "filter and\n");
#endif
      filter_and();
    } else if (IS_EQUAL(exp, "-or")) {
#ifdef DEBUG
      fprintf(stderr, "filter or\n");
#endif
      filter_or();
    } else {
      //TODO
    }
  }
  if (exp_num == 0) {
    init_true(); 
  }
  filter_tree.passed = op_stack[0];
  free_op_stack();
}
Example #23
0
static  int evaluate( char * * line, long *val )
{
    long        arg;
    char    *   ptr;
    char    *   str;
    char    *   endptr;
    int         ercode;
    operator *  op;
    int         expr_oper;              // looking for term or operator

    expr_oper = 0;
    coper     = 0;
    cvalue    = 0;
    nparens   = 0;
    ptr       = *line;

    while( *ptr ) {
        if( *ptr == ' ' ) {
            if( ignore_blanks ) {
                ptr++;
                continue;
            } else {
                break;
            }
        }
        switch( expr_oper ) {
        case 0:                         // look for term
            str = get_exp( ptr );

            if( str == NULL ) {         // nothing is error
                return( not_ok );
            }

            op = get_op( str );
            if( *(str +1) == NULC ) {
                if( NULL != op ) {
                    push_op( op->operc );
                    ptr++;
                    break;
                }

                if( (*str == '-' ) || (*str == '+' ) ) {
                    push_op(*str);
                    ++ptr;
                    break;
                }
            }

            arg = strtol( str, &endptr, 10 );
            if( (((arg == LONG_MIN) || (arg == LONG_MAX)) && errno == ERANGE)
                 || (str == endptr) ) {
                 return( not_ok );
            }

            push_val( arg );

            ptr += endptr - str;        // to the next unprocessed char

            expr_oper = 1;              // look for operator next
            break;

        case 1:                         // look for operator
            op = get_op( ptr );
            if( NULL == op ) {
                return( not_ok );
            }
            if( ')' == *ptr ) {
                ercode = do_paren();
                if( ok > ercode ) {
                    return( ercode );
                }
            } else {
                while( coper && op->priority <= get_prio_m1() ) {
                    do_expr();
                }
                push_op( op->operc );
                expr_oper = 0;      // look for term next
            }
            ptr++;
            break;
        }
    }

    while( 1 < cvalue ) {
        ercode = do_expr();
        if( ok > ercode )
             return ercode;
    }
    if( !coper ) {
        *line = ptr;                    // next scan position
        return( pop_val( val ) );       // no operations left return result
    } else {
        return( not_ok );
    }
}
Example #24
0
uint8_t octet_ops::alpha_power(int i)
{
    return get_exp(i);
}
Example #25
0
void calculate_values()
{
    cell_list ***depend = NULL;
    cell_list *first = NULL;
    cell_list *sorted = NULL, *sorted_last = NULL;
    cell_list *p = NULL;
    int i,j;

    //rtlDebugOutString("calc");

    abort_calc = 0;
    depend = (cell_list***)allocmem(col_count * sizeof(void*));
    for (i = 0; i < col_count; i++)
    {
        depend[i] = (cell_list**)allocmem(row_count * sizeof(void*));
        for (j = 0; j < row_count; j++)
        {
            if (values[i][j])
                freemem(values[i][j]);
            values[i][j] = NULL;

            if (cells[i][j] && cells[i][j][0] == '=')
            {
                depend[i][j] = find_depend(cells[i][j] + 1);		// после =
                if (abort_calc)
                {
                    values[i][j] = (char*)allocmem(2);
                    values[i][j][0] = '#';
                    values[i][j][1] = '\0';
                    abort_calc = 0;
                    continue;
                }
                cell_list *cur;
                cur = (cell_list*)allocmem(sizeof(cell_list));
                cur->x = i;
                cur->y = j;
                cur->next = first;	// вставили тек. ячейку в начало списка ячеек с формулами
                first = cur;
            }
        }
    }

    //rtlDebugOutString("depend end");
    // топологическая сортировка
    if (!first)
        goto free_memory;

    if (abort_calc)
        goto free_memory;

    while (first)
    {
        // найти наименьший элемент. если его нет - ошибка, т.к. циклическая зависимость
        cell_list *prev = NULL,*min = first;

        bool is_min;
        while (min)
        {
            cell_list *p = first;
            is_min = 1;
            while (p && is_min)
            {
                if (is_in_list(p,depend[min->x][min->y]))
                    is_min = 0;
                p = p->next;
            }
            if (is_min)
                break;
            prev = min;
            min = min->next;
        }
        if (!is_min)
        {
            abort_calc = 1;
            goto free_memory;		// все плохо. ужасно. я плакаю, но пишу goto
        }
        // надо убрать минимум во второй список
        if (prev == NULL)
        {
            first = first->next;
        }
        else
        {
            prev->next = min->next;
        }
        /*
        min->next = sorted;
        sorted = min;
        */
        if (sorted == NULL)
        {
            sorted = min;
            sorted_last = min;
        }
        else
        {
            sorted_last->next = min;
            sorted_last = min;
            min->next = NULL;
        }
    }

    // вычисление значений
    //rtlDebugOutString("sort end");

    p = sorted;
    while (p)
    {
        double d;
        abort_calc = 0;
        set_exp(cells[p->x][p->y]+1);	// все что после "="
        find_var = &calc_callback;
        if (get_exp(&d))
        {
            char *new_val = ftoa(d);
            if (values[p->x][p->y] && strcmp(values[p->x][p->y],new_val) == 0)
            {
                freemem(new_val);
            }
            else
            {
                if (values[p->x][p->y])
                    freemem(values[p->x][p->y]);
                values[p->x][p->y] = new_val;
                sel_moved = 0;
            }
            //sprintf(debuf,"calc %U %U formula %S result %f",p->x,p->y,cells[p->x][p->y]+1,d);
            //rtlDebugOutString(debuf);
        }
        else
        {
            values[p->x][p->y] = (char*)allocmem(2);
            values[p->x][p->y][0] = '#';
            values[p->x][p->y][1] = '\0';
            //sprintf(debuf,"calc %U %U formula %S result #",p->x,p->y,cells[p->x][p->y]+1);
            //rtlDebugOutString(debuf);
        }
        p = p->next;
    }

    if (abort_calc)
        goto free_memory;

    //rtlDebugOutString("calc end");


    // освобождение памяти

free_memory:

    p = sorted;
    while (p)
    {
        cell_list *tmp = p->next;
        cell_list *pp = depend[p->x][p->y];
        while (pp)
        {
            cell_list *tmp = pp->next;
            freemem(pp);
            pp = tmp;
        }
        freemem(p);
        p = tmp;
    }

    for (i = 0; i < col_count; i++)
        freemem(depend[i]);
    freemem(depend);

    //rtlDebugOutString("freemem end");


}
Example #26
0
File: eval.c Project: eldy/other
int evaluate(char *line, double *val)
//--------------------------------------------------------------------
// Evaluates an ASCII mathematical expression
// INPUT:  line:  String to evaluate
//         val:   Storage to receive double result
//   
// RETURN: SUCCESS =  0 if successful  
//         E_ERROR = -1 if syntax error  
//         R_ERROR = -2 if runtime error 
//         DUV_ZERO= -3 Division by 0    
// 
// Side effects: Removes all whitespace from the string and converts
//               it to U.C.
//--------------------------------------------------------------------
{
double arg;
char *ptr = line, *str, *endptr;
int ercode;
struct operator *op;

strupr(line);
rmallws(line);
state = op_sptr = arg_sptr = parens = 0;

while (*ptr)
      {
	    switch (state)
	    {
	    case 0:
		  if (NULL != (str = get_exp(ptr)))
		  {
			if (NULL != (op = get_op(str)) &&
			      strlen(str) == op->taglen)
			{
			      push_op(op->token);
			      ptr += op->taglen;
			      break;
			}

			if (SUCCESS == strcmp(str, "-"))
			{
			      push_op(*str);
			      ++ptr;
			      break;
			}

			if (SUCCESS == strcmp(str, "PI"))
			      push_arg(Pi);

			else
			{
			      if (0.0 == (arg = strtod(str, &endptr)) &&
				    NULL == strchr(str, '0'))
			      {
				    return E_ERROR;
			      }
			      push_arg(arg);
			}
			ptr += strlen(str);
		  }
		  else  return E_ERROR;

		  state = 1;
		  break;

	    case 1:
		  if (NULL != (op = get_op(ptr)))
		  {
			if (')' == *ptr)
			{
			      if (SUCCESS > (ercode = do_paren()))
				    return ercode;
			}
			else
			{
			      while (op_sptr &&
				    op->precedence <= getTOSprec())
			      {
				    do_op();
			      }
			      push_op(op->token);
			      state = 0;
			}

			ptr += op->taglen;
		  }
		  else  return E_ERROR;

		  break;
	    }
      }

      while (1 < arg_sptr)
      {
	    if (SUCCESS > (ercode = do_op()))
		  return ercode;
      }
      if (!op_sptr)
	    return pop_arg(val);
      else  return E_ERROR;
}
Example #27
0
AstInt* AstInt::make(long int i) {
	AstInt* ii = new AstInt(i);
	Expression* res = get_exp(ii);
	assert(res->get_type() == AST_INT);
	return static_cast<AstInt*>(res);
}
Example #28
0
AstNil* AstNil::make() {
	AstNil* ii = new AstNil();
	Expression* res = get_exp(ii);
	assert(res->get_type() == AST_NIL);
	return static_cast<AstNil*>(res);
}
AstExpressionList* AstExpressionList::make(vector<Expression*> & expr) {
	AstExpressionList* l = new AstExpressionList(expr);
	Expression* res = get_exp(l);
	assert(res->get_type() == AST_EXPRESSION_LIST);
	return static_cast<AstExpressionList*>(res);
}
Example #30
0
static ast::Exp* get_exp(void)
{
  ast::Exp* exp;
  // std::cerr << "get_exp at pos " << (buf - initial_buf) << std::endl;
  int code = get_uint8();
  // std::cerr << "    code = " << code << std::endl;
  Location *loc = get_location();
  int is_verbose = get_bool();
  int is_break = get_bool();
  int is_breakable = get_bool();
  int is_return = get_bool();
  int is_returnable = get_bool();
  int is_continue = get_bool();
  int is_continuable = get_bool();
  
  
  switch(code){
  case 1: {   
    std::list<ast::Exp *>* l_body = get_exps();
    exp = new ast::SeqExp(*loc, *l_body);
    break;
  }
  case 2: {
    std::wstring* s = get_wstring();
    exp = new ast::StringExp(*loc, *s);
    break;
  }
  case 3: {
    std::wstring* s = get_wstring();
    exp = new ast::CommentExp(*loc, s);
    break;
  }
  case 4: {
    ast::IntExp::Prec prec = get_IntExp_Prec();
    int value = get_int32();
    exp = new ast::IntExp(*loc, prec, value);
    break;
  }
  case 5: {
    double d = get_double();
    exp = new ast::FloatExp(*loc, d);
    break;
  }
  case 6: {
    double d = get_double();
    exp = new ast::DoubleExp(*loc,d);
    break;
  }
  case 7: {
    bool b = get_bool();
    exp = new ast::BoolExp(*loc, b);
    break;
  }
  case 8: {
    exp = new ast::NilExp(*loc);
    break;
  }
  case 9: {
    symbol::Symbol *name = get_Symbol();
    exp = new ast::SimpleVar(*loc, *name);
    break;
  }
  case 10: {
    exp = new ast::ColonVar(*loc);
    break;
  }
  case 11: {
    exp = new ast::DollarVar(*loc);
    break;
  }
  case 12: {
    std::list<ast::Var*>* vars = get_vars();
    exp = new ast::ArrayListVar(*loc, *vars);
    break;
  }
  case 13: {
    ast::Exp *head = get_exp();
    ast::Exp *tail = get_exp();
    exp = new ast::FieldExp(*loc, *head, *tail);
    break;
  }
  case 14: {
    ast::IfExp::Kind kind = get_IfExp_Kind();
    bool has_else = get_bool();
    ast::Exp* test = get_exp();
    ast::Exp* _then = get_exp();
    ast::IfExp* ifexp;
    if( has_else ){
      ast::Exp* _else = get_exp();
      ifexp = new ast::IfExp(*loc, *test, *_then, *_else);
    } else {
      ifexp = new ast::IfExp(*loc, *test, *_then);
    }
    ifexp->kind_set(kind);
    exp = ifexp;
    break;
  }
  case 15: {
    Location *try_location = get_location();
    Location *catch_location = get_location();
    std::list<ast::Exp *>* try_exps = get_exps();
    std::list<ast::Exp *>* catch_exps = get_exps();
    ast::SeqExp *_try = new ast::SeqExp(*try_location, *try_exps);
    ast::SeqExp *_catch = new ast::SeqExp(*catch_location, *catch_exps);
    exp = new ast::TryCatchExp(*loc, *_try, *_catch);
    break;
  }
  case 16: {
    ast::Exp* test = get_exp();
    ast::Exp* body = get_exp();
    exp = new ast::WhileExp(*loc, *test, *body);
    break;
  }
  case 17: {
    Location *vardec_location = get_location();
    ast::VarDec* vardec = get_VarDec(vardec_location);
    ast::Exp* body = get_exp();
    exp = new ast::ForExp(*loc, *vardec, *body);
    break;
  }
  case 18: {
    exp = new ast::BreakExp(*loc);
    break;
  }
  case 19: {
    exp = new ast::ContinueExp(*loc);
    break;
  }
  case 20: {
    bool is_global = get_bool();
    if( is_global ){
      exp = new ast::ReturnExp(*loc);
    } else {
      ast::Exp* returnExp_exp = get_exp();    
      exp = new ast::ReturnExp(*loc, returnExp_exp);
    }
    break;
  }
  case 21: {
    bool has_default = get_bool();
    ast::SeqExp * default_case = NULL;
    if( has_default ){
      Location *default_case_location = get_location();
      std::list<ast::Exp *>* default_case_exps = get_exps();
      default_case = new ast::SeqExp(*default_case_location, 
				     *default_case_exps);    
    }
    ast::Exp* select = get_exp();

    int nitems = get_uint32();
    std::list<ast::CaseExp*> *cases = new  std::list<ast::CaseExp*>;
    for(int i = 0; i < nitems; i++){

      Location *case_location = get_location();
      Location *body_location = get_location();
      ast::Exp* test = get_exp();
      std::list<ast::Exp *>* body_exps = get_exps();
      ast::SeqExp *body = new ast::SeqExp(*body_location,  *body_exps);

      ast::CaseExp* _case = new ast::CaseExp(*case_location, *test, *body);
      cases->push_back(_case);
    }
    

    if( has_default ){
      exp = new ast::SelectExp(*loc, *select, *cases, *default_case);
    } else {
      exp = new ast::SelectExp(*loc, *select, *cases);
    }
    break;
  }
    /* SHOULD NEVER HAPPEN
  case 22: {
    exp = new ast::CaseExp(*loc);
    break;
  }
    */
  case 23: {
    std::list<ast::MatrixLineExp *>* lines = get_MatrixLines();
    exp = new ast::CellExp(*loc, *lines);
    break;
  }
  case 24: {
    std::list<ast::Exp *>* exps = get_exps();
    exp = new ast::ArrayListExp(*loc, *exps);
    break;
  }
  case 25: {
    std::list<ast::Exp *>* exps = get_exps();
    exp = new ast::AssignListExp(*loc, *exps);
    break;
  }
  case 26: {
    ast::Exp* notexp = get_exp();
    exp = new ast::NotExp(*loc, *notexp);
    break;
  }
  case 27: {
    ast::TransposeExp::Kind kind = get_TransposeExp_Kind();
    ast::Exp* _exp = get_exp();    
    exp = new ast::TransposeExp(*loc, *_exp, kind);
    break;
  }
  case 28: {
    exp = get_VarDec(loc);
    break;
  }
  case 29: {
    symbol::Symbol* name = get_Symbol();
    Location *args_loc = get_location();
    Location *returns_loc = get_location();
    ast::Exp* body = get_exp();
    std::list <ast::Var*>* args_list = get_vars();
    std::list <ast::Var*>* returns_list = get_vars();
    ast::ArrayListVar *args = new ast::ArrayListVar(*args_loc, *args_list);
    ast::ArrayListVar *returns = new ast::ArrayListVar(*returns_loc, *returns_list);
    exp = new ast::FunctionDec(*loc, *name, *args, *returns, *body);
    break;
  }
  case 30: {
    ast::Exp* _start = get_exp();    
    ast::Exp* _step = get_exp();    
    ast::Exp* _end = get_exp();    
    exp = new ast::ListExp(*loc, *_start, *_step, *_end);
    break;
  }
  case 31: {
    ast::Exp* _left = get_exp();    
    ast::Exp* _right = get_exp();    
    exp = new ast::AssignExp(*loc, *_left, *_right);
    break;
  }
  case 32: {
    ast::OpExp::Kind kind = get_OpExp_Kind();
    ast::OpExp::Oper oper = get_OpExp_Oper();
    ast::Exp *left = get_exp();
    ast::Exp *right = get_exp(); 
    ast::OpExp *_opexp  = new ast::OpExp(*loc, *left, oper, *right);
    exp = _opexp;
    _opexp->kind_set(kind);
    break;
  }
  case 33: {
    ast::OpExp::Kind kind = get_OpExp_Kind();
    ast::OpExp::Oper oper = get_OpExp_Oper();
    ast::Exp *left = get_exp();
    ast::Exp *right = get_exp(); 
    ast::LogicalOpExp *_opexp  = 
      new ast::LogicalOpExp(*loc, *left, oper, *right);
    exp = _opexp;
    _opexp->kind_set(kind);
    break;
  }
  case 34: {
    std::list<ast::MatrixLineExp *>* lines = get_MatrixLines();
    exp = new ast::MatrixExp(*loc, *lines);
    break;
  }
  case 35: {
    ast::Exp* name = get_exp();    
    std::list<ast::Exp *> * args = get_exps();
    exp = new ast::CallExp(*loc, *name, *args);
    break;
  }
    /* SHOULD NEVER HAPPEN
  case 36: {
    exp = new ast::MatrixLineExp(*loc);
    break;
  }
    */
  case 37: {
    ast::Exp* name = get_exp();    
    std::list<ast::Exp *>* args = get_exps();
    exp = new ast::CellCallExp(*loc, *name, *args);
    break;
  }
  default: 
    std::cerr << "Unknown code " << code << std::endl;
    exit(2);
  }

  exp->set_verbose(is_verbose);
  if(is_break) exp->break_set();
  if(is_breakable) exp->breakable_set();
  if(is_return) exp->return_set();
  if(is_returnable) exp->returnable_set();
  if(is_continue) exp->continue_set();
  if(is_continuable) exp->continuable_set();
  
  return exp;
}