boost::shared_ptr< Base<EncodingT> > FunctionCall<EncodingT>::interpret(Context<EncodingT> & c)
 {
     boost::shared_ptr< Base<EncodingT> > val(new Base<EncodingT>());
     boost::shared_ptr< Function<EncodingT> > fct = dynamic_pointer_cast< Function<EncodingT> >(c.getFunction(m_name));
     if (fct)
     {
         Context<EncodingT> new_context(c);
         new_context.clear();
         std::vector<typename EncodingT::string_t> paramsName = fct->getParams();
         std::vector< boost::shared_ptr< Base<EncodingT> > > in;
         for (size_t i = 0; i<m_params.size() && i<paramsName.size(); ++i)
         {
             in.push_back(m_params[i]->interpret(c));
             new_context.add(paramsName[i], in[i]);
         }
         val = fct->interpret(new_context);
         for (size_t i = 0; i<m_params.size() && i<paramsName.size(); ++i)
         {
             boost::shared_ptr< Address<EncodingT> > ref = dynamic_pointer_cast< Address<EncodingT> >(m_params[i]);
             if (ref)
             {
                 boost::shared_ptr< Base<EncodingT> > out = new_context.getObject(paramsName[i]);
                 if (out != in[i])
                 {
                     ref->allocate(out, c);
                 }
             }
         }
     }
     return val;
 }
Example #2
0
/* s_log is not initialized here, but we can use log_raw */
void sthreads_init(void) {
    /* create the first (listening) context and put it in the running queue */
    if(!new_context()) {
        log_raw("Unable create the listening context");
        exit(1);
    }
}
Example #3
0
void Function::renderasm(ASMhandle& context){
	if(debug) cerr<<"Function: renderasm start"<<endl;

	/* Function header assembly */
	assembler.push_back(ss<<"\t.align	2"<<endl);
	assembler.push_back(ss<<"\t.globl "<<name<<endl);		// This has to be ommitted for functions declared static
	assembler.push_back(ss<<"\t.ent "<<name<<endl);
	assembler.push_back(ss<<"\t.type "<<name<<", @function"<<endl);
	assembler.push_back(ss<<name<<":"<<endl);


	ASMhandle new_context(context);

	new_context.subroutine_enter();

	init_args(new_context);

	if(debug) cerr<<"Function: renderasm of parameters successful"<<endl;

	if(fn_body!=NULL) fn_body->renderasm(new_context, true);
	else	context.subroutine_exit(NULL);

	if(debug) cerr<<"Function: renderasm of body successful"<<endl;
	
	/* Function end assembly */
	assembler.push_back(ss<<endl<<"\t.end "<<name<<endl<<endl);
}
Example #4
0
File: eval.c Project: S010/misc
struct expr    *
lambda(struct expr * e, struct context * context)
{
	int             i;
	const struct list *lp, *la;
	struct expr    *pe, *pr;
	struct context *ctx;

	/* assume e is a valid func call expr */

	ctx = new_context();
	ctx->is_root_level = 0;
	ctx->next = (struct context *) context;
	dbgprintf("created new context\n");
	for (i = 0, lp = e->v.list->v->v.list->next->v->v.list, la = e->v.list->next; lp && la; ++i, lp = lp->next, la = la->next) {
		dbgprintf("evaluating arguments, iter %d\n", i);
		pe = add_to_context(ctx, strdup(lp->v->v.atom->v), eval(la->v, context));
		full_free_expr(pe);
	}
	dbgprintf("eval'ing e expr\n");
	pr = eval(e->v.list->v->v.list->next->next->v, ctx);
	free_expr(e);
	free_context(ctx);
	return pr;
}
Example #5
0
void dij_pop_code()
   {
   struct _fnode *fnode; 
   struct iCode *icode;
   struct _context_stack *kill_me;
   struct iContext *context;
   int i;
   printf("enter pop_code\n");
   context = new_context();
   context->append_codeblock(context, dij_box( close_buffer() ));
   context->i_namespace->size_namespace(context->i_namespace,
            write_code->num_parameters , 
            write_code->num_locals , 
            write_code->num_returns,
            0
         );
   context->i_namespace->write_namespace(context->i_namespace,
        write_code->parameters,
        write_code->locals,
        write_code->returns
        );    
   fnode = fgraph->ground(fgraph, context);
   kill_me = write_code;

   write_code = write_code->under;
   if( kill_me )
      {
      if( kill_me->parameters) free(kill_me->parameters);
      if( kill_me->locals) free(kill_me->locals);
      if( kill_me->returns) free(kill_me->returns);
      free(kill_me);
      }
   dij_write( (long int) fnode );
   printf("exit pop_code\n");
   }
Example #6
0
/* Allocates memory (new_context()) */
void factor_vm::init_contexts(cell datastack_size_, cell retainstack_size_,
                              cell callstack_size_) {
  datastack_size = datastack_size_;
  retainstack_size = retainstack_size_;
  callstack_size = callstack_size_;

  ctx = NULL;
  spare_ctx = new_context();
}
Example #7
0
RINGING_START_NAMESPACE

RINGING_USING_STD

void search_base::run( search_base::outputer &o ) const
{
  scoped_pointer< context_base > ctx( new_context() );
  ctx->run( o );
}
Example #8
0
int sthreads_init(void) {
    /* create the first (listening) context and put it in the running queue */
    if(!new_context()) {
        s_log(LOG_ERR, "Unable create the listening context");
        return 1;
    }
    /* no need to initialize ucontext_t structure here
       it will be initialied with swapcontext() call */
    return 0;
}
Example #9
0
/* conn = cyrussasl.server_new("serice_name", "host FQDN", "user realm",
 *                             "iplocal", "ipremote")
 *
 * conn: an opaque data structure (from Lua's perspective) related to this 
 *       specific authentication attempt.
 * service_name: the name of the service that's being protected by SASL (e.g.
 *               xmpp, smtp, ...)
 * host FQDN: the fully-qualified domain name of the server that users 
 *            are connecting to. May be nil.
 * user realm: the authentication user realm to use for AuthN purposes. 
 *             May be nil.
 * iplocal: Either nil or a string of the form "a.b.c.d;port" (for IPv4). 
 *          Used to tell the SASL library what the local side of the connection
 *          is using.
 * ipremote: Either nil or a string denoting the remote side of the connection.
 *
 * On error, this throws Lua error exceptions. (It is not the typical
 * case that this method might cause an error, except when attempting
 * to set up SASL initially during development.)
 */
static int cyrussasl_sasl_server_new(lua_State *l)
{
  const char *service_name, *fqdn, *realm, *iplocal, *ipremote;
  int numargs = lua_gettop(l);
  int err;
  sasl_conn_t *conn = NULL;
  struct _sasl_ctx **ctxp = NULL;

  if (numargs != 5) {
    lua_pushstring(l, 
		   "usage: "
		   "conn = "
		   "cyrussasl.server_new(service_name, fqdn, realm, "
		   "iplocal, ipremote)");
    lua_error(l);
    return 0;
  }

  service_name = tostring(l, 1);
  fqdn = tostring(l, 2);
  realm = tostring(l, 3);
  iplocal = tostring(l, 4);
  ipremote = tostring(l, 5);

  ctxp = new_context(l);
  if (!ctxp) {
    lua_pushstring(l, "Unable to allocate a new context");
    lua_error(l);
    return 0;
  }

  _init_server_callbacks(*ctxp);

  err = sasl_server_new( service_name,       /* service name (passed in) */
			 fqdn,               /* serverFQDN               */
			 realm,              /* user_realm               */
			 iplocal,            /* iplocalport              */
			 ipremote,           /* ipremoteport             */
			 (*ctxp)->callbacks, /* per-connection callbacks */
			 0,                  /* flags                    */
			 &conn );            /* returned connection ptr  */

  (*ctxp)->conn = conn;

  if ( err != SASL_OK ) {
    lua_pushstring(l, "sasl_server_new failed");
    lua_error(l);
    return 0;
  }

  /* Return 1 item on the stack (a userdata pointer to our state struct).
   * It was already pushed on the stack by new_context(). */

  return 1; /* return # of arguments returned on stack */
}
Example #10
0
/* Allocates memory */
cell factor_vm::begin_callback(cell quot_) {
  data_root<object> quot(quot_, this);

  ctx->reset();
  spare_ctx = new_context();
  callback_ids.push_back(callback_id++);

  init_context(ctx);

  return quot.value();
}
Example #11
0
int create_client(int ls, int s, void *arg, void *(*cli)(void *)) {
    CONTEXT *ctx;

    s_log(LOG_DEBUG, "Creating a new context");
    ctx=new_context();
    if(!ctx)
        return -1;
    s_log(LOG_DEBUG, "Context %ld created", ctx->id);
    makecontext(&ctx->ctx, (void(*)(void))cli, ARGC, arg);
    return 0;
}
Example #12
0
int sthreads_init(void) {
    /* create the first (listening) context and put it in the running queue */
    if(!new_context()) {
        s_log(LOG_ERR, "Cannot create the listening context");
        return 1;
    }
    /* update tls for newly allocated ready_head */
    ui_tls=tls_alloc(NULL, ui_tls, "ui");
    /* no need to initialize ucontext_t structure here
       it will be initialied with swapcontext() call */
    return 0;
}
Example #13
0
int create_client(int ls, int s, CLI *arg, void *(*cli)(void *)) {
    CONTEXT *context;

    (void)ls; /* this parameter is only used with USE_FORK */
    
    s_log(LOG_DEBUG, "Creating a new context");
    context=new_context();
    if(!context) {
        if(arg)
            str_free(arg);
        if(s>=0)
            closesocket(s);
        return -1;
    }

    /* initialize context_t structure */
    if(getcontext(&context->context)<0) {
        str_free(context);
        if(arg)
            str_free(arg);
        if(s>=0)
            closesocket(s);
        ioerror("getcontext");
        return -1;
    }
    context->context.uc_link=NULL; /* stunnel does not use uc_link */

    /* create stack */
    context->stack=str_alloc(arg->opt->stack_size);
    if(!context->stack) {
        str_free(context);
        if(arg)
            str_free(arg);
        if(s>=0)
            closesocket(s);
        s_log(LOG_ERR, "Unable to allocate stack");
        return -1;
    }
    str_detach(context->stack);
#if defined(__sgi) || ARGC==2 /* obsolete ss_sp semantics */
    context->context.uc_stack.ss_sp=context->stack+arg->opt->stack_size-8;
#else
    context->context.uc_stack.ss_sp=context->stack;
#endif
    context->context.uc_stack.ss_size=arg->opt->stack_size;
    context->context.uc_stack.ss_flags=0;

    makecontext(&context->context, (void(*)(void))cli, ARGC, arg);
    s_log(LOG_DEBUG, "New context created");
    return 0;
}
Example #14
0
/*
 * Return malloc'd string containing only the context specifier given
 * a string containing the raw pinerc entry
 */
char *
context_string(char *s)
{
    CONTEXT_S *t = new_context(s, NULL);
    char      *rv = NULL;

    if(t){
	/*
	 * Take what we want from context, then free the rest...
	 */
	rv = t->context;
	t->context = NULL;			/* don't free it! */
	free_context(&t);
    }

    return(rv ? rv : cpystr(""));
}
Example #15
0
static void test_otrl_proto_create_data(void)
{
	char* encmessagep = NULL;
	ConnContext* context = new_context("Alice", "Alice's account", "Secret protocol");
	char* msg = "HELO";
	OtrlTLV* tlvs = NULL;
	unsigned char flags = 12;
	unsigned char* extrakey = NULL;

	context->msgstate = OTRL_MSGSTATE_PLAINTEXT;
	ok(otrl_proto_create_data(&encmessagep, context, msg, tlvs, flags, extrakey)
			== gcry_error(GPG_ERR_CONFLICT), "Conflict detected");

	context->msgstate = OTRL_MSGSTATE_ENCRYPTED;
	context->context_priv->their_keyid = 0;
	ok(otrl_proto_create_data(&encmessagep, context, msg, tlvs, flags, extrakey)
			== gcry_error(GPG_ERR_CONFLICT), "Conflict detected");
}
Example #16
0
struct nsa_context *
nsa_init(const char *file)
{
  const char *fname[2];
  fname[0] = file;
  fname[1] = NULL;
  if (!access(fname[0],R_OK))
    {
      context = new_context();
      runexpat(i_list, fname, sH, eH);
      sex_system = new_system();
      sex_system->n = "sexnum";
      free(sex_system->steps);
      sex_system->steps = NULL;
      return context;
    }
  return NULL;
}
Example #17
0
RingoFetchContext & RingoFetchContext::create (RingoOracleContext &context,
                                               const Array<char> &query_id)
{
   OsLocker locker(_instances_lock);
   TL_GET(PtrArray<RingoFetchContext>, _instances);

   int id = 1;

   for (int i = 0; i < _instances.size(); i++)
      if (_instances[i]->id >= id)
         id = _instances[i]->id + 1;

   AutoPtr<RingoFetchContext> new_context(new RingoFetchContext(id, context, query_id));
   const BingoOracleContext &boc = context.context();

   new_context->id = id;

   _instances.add(new_context.release());
   return *_instances.top();
}
Example #18
0
int main(void)
{
	int i, any_left = 1;

	for (i = 0; i < NCTXTS; i++) {
		struct context *ctxt;
		batch[i] = ctxt = new_context();
		caller(ctxt, ctxt);
	}

	while (any_left) {
		any_left = 0;
		for (i = 0; i < NCTXTS; i++)
			if (thisfunc(batch[i]))
				any_left = 1;
	}

	printf("All done\n");
	return 0;
}
Example #19
0
/* Look up a connection context by name/account/protocol from the given
 * OtrlUserState.  If add_if_missing is true, allocate and return a new
 * context if one does not currently exist.  In that event, call
 * add_app_data(data, context) so that app_data and app_data_free can be
 * filled in by the application, and set *addedp to 1. */
ConnContext * otrl_context_find(OtrlUserState us, const char *user,
	const char *accountname, const char *protocol, int add_if_missing,
	int *addedp,
	void (*add_app_data)(void *data, ConnContext *context), void *data)
{
    ConnContext ** curp;
    int usercmp = 1, acctcmp = 1, protocmp = 1;
    if (addedp) *addedp = 0;
    if (!user || !accountname || !protocol) return NULL;
    for (curp = &(us->context_root); *curp; curp = &((*curp)->next)) {
        if ((usercmp = strcmp((*curp)->username, user)) > 0 ||
		(usercmp == 0 &&
		  (acctcmp = strcmp((*curp)->accountname, accountname)) > 0) ||
		(usercmp == 0 && acctcmp == 0 &&
		  (protocmp = strcmp((*curp)->protocol, protocol)) >= 0))
	    /* We're at the right place in the list.  We've either found
	     * it, or gone too far. */
	    break;
    }
    if (usercmp == 0 && acctcmp == 0 && protocmp == 0) {
	/* Found it! */
	return *curp;
    }
    if (add_if_missing) {
	ConnContext *newctx;
	if (addedp) *addedp = 1;
	newctx = new_context(user, accountname, protocol);
	newctx->next = *curp;
	if (*curp) {
	    (*curp)->tous = &(newctx->next);
	}
	*curp = newctx;
	newctx->tous = curp;
	if (add_app_data) {
	    add_app_data(data, *curp);
	}
	return *curp;
    }
    return NULL;
}
Example #20
0
void run_server()
{
    zctx_t *ctx;
    void *socket;
    int i, n, nclient;
    char buf[256];
    char data[256];
    char client[256];

    ctx = new_context();
    socket = new_socket(ctx, ZMQ_ROUTER);
//  socket = new_socket(ctx, ZMQ_REP);
    assert_result(socket_bind(socket, host), 0);
//  assert_result(zmq_bind(socket, host), 0);

    log_printf(0, "my identity=%s\n", zsocket_identity(socket));

    i = 0;
    for (;;) {
        log_printf(0, "Waiting %d\n", i);
        nclient = zmq_recv(socket, client, sizeof(client), 0);
        client[nclient] = 0;
        log_printf(0, "From %s [%d]\n", client, nclient);
        n = zmq_recv(socket, buf, sizeof(buf), 0);
        buf[n] = 0;
        if (n != 0) log_printf(0, "Missing EMPTY frame! buf=%s\n", buf);
        n = zmq_recv(socket, buf, sizeof(buf), 0);
        buf[n] = 0;
        log_printf(0, "Got %s\n", buf);

        zmq_send(socket, client, nclient, ZMQ_SNDMORE);
        zmq_send(socket, NULL, 0, ZMQ_SNDMORE);
        snprintf(data, sizeof(buf), "(%s) World %d", buf, i);
        zmq_send(socket, data, strlen(data)+1, 0);
        i++;
    }

    destroy_context(ctx);
}
J_Context_Shared_t Contexts_Handler::create_j_context(int i_width, int i_height
													  , const char* const i_title
													  , j_monitor_t i_monitor
													  , j_window_t i_share_window){
	glfwWindowHint(GLFW_VISIBLE, false);

	J_Context_Shared_t new_context(new J_Context);
	//M_main_context = M_main_context ? M_main_context : new_context;
	Context_RAII context_saver;
	new_context->M_width = i_width;
	new_context->M_height = i_height;

	if(!(new_context->M_window = glfwCreateWindow(i_width, i_height, i_title, i_monitor, i_share_window))){
		
		throw J_OpenGL_Init_Error("Could not create glfw window!");
	}

	glfwMakeContextCurrent(new_context->M_window);
	glClearColor(0.1f,0.0f,0.4f,0.0f);
	glClear(GL_COLOR_BUFFER_BIT);
	glfwSwapBuffers(new_context->M_window);
	new_context->M_context = new GLEWContext();

	

	M_active_context = new_context;
	M_active_glew = new_context->M_context;
	if(int error_code = glewInit()){
		cerr << "\nError Code: " << error_code << endl;
		throw J_OpenGL_Init_Error("Could Not Initialize Glew!");
	}


	glEnable(GL_BLEND); 
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	return new_context;
}
Example #22
0
void run_client()
{
    zctx_t *ctx;
    void *socket;
    int i, n;
    char buf[256];
    char *me;

    ctx = new_context();
    socket = new_socket(ctx, ZMQ_REQ);
    socket_connect(socket, host);
//  zmq_connect(socket, host);

    me = zsocket_identity(socket);
    log_printf(0, "my identity=%s\n", me);
    i = 0;
    for (;;) {
        log_printf(0, "Sending %d\n", i);
//     zmq_send(socket, host, strlen(host), ZMQ_SNDMORE);
//     zmq_send(socket, me, strlen(me), ZMQ_SNDMORE);

        snprintf(buf, sizeof(buf), "Hello %d", i);
        zmq_send(socket, buf, strlen(buf)+1, 0);

//     zmq_recv(socket, buf, sizeof(buf), 0);
//     log_printf(0, "From %s\n", buf);
        n = zmq_recv(socket, buf, sizeof(buf), 0);
        buf[n] = 0;
        log_printf(0, "Got %s\n", buf);

        sleep(1);
        i++;
    }

    destroy_context(ctx);
}
Example #23
0
/*
 *	Parse statement starting with an identifier.
 *	Possibilities include:
 *		Assignment
 *		Procedure statement
 */
void
parse_identifier(TOKEN *first_token)
{
    TOKEN		token, next_token;
    TOKEN		param_token, attrib_token, type_token;
    int		token_class, next_token_class;
    DECL		*decl_list, *extra_decl_list;
    PARAM_LIST	*param_list, *param_ptr;
    DECL_MEMBER	*decl_ptr;
    DECL_ID		*decl_id;
    BOOLEAN		extern_proc, got_type, interrupt_proc;
    char		*tmp_text_ptr;

    /* Check for label or procedure */
    tmp_text_ptr = text_ptr;
    token_class = get_token(&token);

    if (token_class == LABEL) {
        /* Determine if label or procedure definition */
        next_token_class = get_token(&next_token);
        if ((next_token_class == RESERVED) &&
                (next_token.token_type == PROCEDURE)) {
            /*
             *	Procedure - Check for parameter list
             */
            param_list = NULL;
            token_class = get_token(&param_token);
            if (token_class == LEFT_PAREN) {
                /* Yes - get parameter list */
                get_param_list(&param_list);

                /* Get token after parameter list */
                token_class = get_token(&attrib_token);
            } else
                /* No param list - save as attribute */
                token_copy(&param_token, &attrib_token);

            out_white_space(first_token);
            extern_proc = FALSE;
            interrupt_proc = FALSE;

            got_type = (token_class == RESERVED) &&
                       (attrib_token.token_type >= BYTE) &&
                       (attrib_token.token_type <= SELECTOR);
            if (got_type) {
                /*
                 *	Process [ <type> ]
                 */
                token_copy(&attrib_token, &type_token);
                token_class = get_token(&attrib_token);
            }

            while (token_class == RESERVED) {
                if (attrib_token.token_type == INTERRUPT) {
                    /*
                     *	Process [ <interrupt> ]
                     */
                    interrupt_proc = TRUE;
                    token_class = get_token(&attrib_token);
                    if (token_class == NUMERIC)
                        /* Interrupt number */
                        token_class = get_token(&attrib_token);
                } else

                    /*
                     *	Process [ EXTERNAL |  { [ PUBLIC ] [ REENTRANT ] } ]
                     */
                    if (attrib_token.token_type == EXTERNAL) {
                        out_str("extern");
                        out_must_white(&attrib_token);
                        extern_proc = TRUE;

                        token_class = get_token(&attrib_token);
                    } else

                        if ((attrib_token.token_type == PUBLIC) ||
                                (attrib_token.token_type == REENTRANT)) {
                            do {
                                if (attrib_token.token_type == PUBLIC) {
                                    /* Ignore for now */
                                    token_class = get_token(&attrib_token);
                                } else

                                    if (attrib_token.token_type == REENTRANT) {
                                        /* Ignore for now */
                                        token_class = get_token(&attrib_token);
                                    } else
                                        break;
                            } while (token_class == RESERVED);
                        } else
                            break;
            }

            if (token_class != END_OF_LINE) {
                parse_error("';' expected");
                return;
            }

            if (interrupt_proc && !extern_proc)
                parse_warning("INTERRUPT procedure declared");

            /* Create declaration for procedure */
            get_element_ptr(&decl_ptr);
            get_var_ptr(&decl_ptr->name_list);
            /* Type = PROCEDURE */
            get_token_ptr(&decl_ptr->type);
            token_copy(&next_token, decl_ptr->type);
            /* Name = procedure name */
            get_token_ptr(&decl_ptr->name_list->name);
            token_copy(first_token, decl_ptr->name_list->name);
            /* Flag if parameter list */
            if (param_list)
                decl_ptr->initialization = DATA;
            /* Add it to context */
            add_to_context(decl_ptr);

            if (got_type) {
                /* Output procedure type */
                out_token_name(&type_token);
                out_must_white(&type_token);
            }

            /* Output procedure name */
            out_token_name(first_token);

            if (extern_proc) {
                out_str("()");

                if (param_list)
                    /* Parse parameter declarations */
                    parse_param_list(param_list, &decl_list,
                                     &extra_decl_list);

                out_char(';');
                /* Eat closing 'END [<proc name>];' */
                token_class = get_token(&token);
                if ((token_class != RESERVED) ||
                        (token.token_type != END)) {
                    parse_error("END expected");
                    return;
                }

                out_white_space(&token);
                token_class = get_token(&token);
                if (token_class == IDENTIFIER) {
                    token_class = get_token(&token);
                }

                if (token_class != END_OF_LINE) {
                    parse_error("';' expected");
                }

                return;
            } else

                if (param_list) {
                    out_token(&param_token);
                    /* Output parameter list */
                    param_ptr = param_list;
                    while (param_ptr) {
                        out_token(&param_ptr->param);
                        param_ptr = param_ptr->next_param;
                        if (param_ptr)
                            out_char(',');
                    }
                    out_char(')');

                    /* Parse parameter declarations */
                    parse_param_list(param_list, &decl_list,
                                     &extra_decl_list);

                    /* Output declarations */
                    if (decl_list) {
                        out_decl(decl_list);
                        /* Add declarations to context */
                        add_decl_to_context(decl_list);
                    }

                    out_str("\n{");		/* } for dumb vi */

                    if (extra_decl_list) {
                        out_decl(extra_decl_list);
                        /* Add declarations to context */
                        add_decl_to_context(extra_decl_list);
                    }

                    /* Discard declarations */
                    free_decl(decl_list);
                    free_decl(extra_decl_list);
                } else
                    /* No parameter list */
                    out_str("()\n{");	/* } for dumb vi */

            /* Create new context */
            new_context(PROCEDURE, first_token);
            /* Parse statements to END */
            parse_to_end();
            /* Pop procedure context */
            pop_context();
        } else {
            /*
             *	Label - add label name
             */
            out_token(first_token);
            /* Add colon */
            out_token(&token);

            /* Is this a defined label or a module? */
            if (find_symbol(first_token, &decl_ptr, &decl_id)) {
                if (decl_ptr->type->token_class == LABEL) {
                    /* Label - new context */
                    new_context(MODULE, first_token);
                    parse_statement(&next_token);
                    pop_context();
                } else {
                    parse_error("Illegal label name");
                    return;
                }
            } else
                parse_statement(&next_token);
        }
        return;
    }

    /* Assignment statement */
    text_ptr = tmp_text_ptr;
    token_copy(first_token, &token);
    token_class = parse_variable(&token, &decl_ptr, &decl_id);

    /* Check for multiple assignments */
    while (token_class == COMMA) {
        /* Print ' =' instead of ',' */
        out_str(" =");
        out_white_space(&token);
        /* Get identifier part of next assignment variable */
        token_class = get_token(&token);
        if (token_class != IDENTIFIER) {
            parse_error("Illegal assignment");
            return;
        }

        /* Parse remainder of variable (if any) */
        token_class = parse_variable(&token, &decl_ptr, &decl_id);
    }

    if (token_class == OPERATOR) {
        if (token.token_type != EQUAL) {
            parse_error("Illegal use of identifier");
            return;
        }

        out_token(&token);

        /* Check for POINTER assignment */
        if (decl_ptr->type->token_type == POINTER) {
            /* Yes - cast it */
            out_str(" (");
            out_str(TYPE_POINTER);
            out_str(" *) ");
        }

        if (parse_expression(&token) != END_OF_LINE)
            parse_error("';' expected");
        else
            out_token(&token);
        return;
    } else

        if (token_class != LABEL) {
            parse_error("Illegal use of identifier");
            return;
        }

}
Example #24
0
	void Environment::run(RunningContext *context)
	{
		const Instruction &ins = m_ipos;
		m_context = context;
		if (!context)
		{
			m_running = false;
		} else if (!m_running)
		{
			clear_vstore();
			TRACE_PRINTF(TRACE_VM, TRACE_INFO, "Entering running state with %p\n", context);
			m_running = true;
			const SourcePos *last_pos = NULL; // used for debug output below.
			const Instruction *ipos;
			while (m_context && (ipos = m_context->next()))
			{
				size_t output = -1;
				size_t expected = -1;
#				define CHECK_STACK(in, out) TRACE_OUT(TRACE_VM, TRACE_SPAM) {\
					assert(m_context->stack_count() >= (size_t)(in)); \
					if ((out) != -1) { assert((long)(expected = m_context->stack_count() - (size_t)(in) + (size_t)(out)) >= 0); } \
					tprintf("Stack info: before(%d), in(%d), out(%d), expected(%d)\n", (int)m_context->stack_count(), (int)(in), (int)(out), (int)expected); \
					output = (out); \
				}

				m_ipos = *ipos;

				TRACE_DO(TRACE_VM, TRACE_INFO) {
					const SourcePos &pos = m_context->m_instructions->source_pos(ipos);
					if (!last_pos || *last_pos != pos)
						tprintf("Source Position: %s:%d:%d (%s)\n", pos.file.c_str(), (int)pos.line_num, (int)pos.column, pos.annotation.c_str());
					last_pos = &pos;
				}
				TRACE_OUT(TRACE_VM, TRACE_SPAM) {
					tprintf("Instruction: %s@%d\n",
						inspect(ins).c_str(),
						(int)(ipos - &*m_context->instructions().begin())
						);
					tprintf("Stack: %d deep", (int)m_context->stack_count());

					const Value *it;
					for (it = m_context->stack_begin(); it != m_context->stack_pos(); it++)
					{
						tprintf("\n   %s", inspect(*it).c_str());
					}
					tprintf(" <--\n");
				}

				switch(ins.instruction)
				{
				case NOP:
					CHECK_STACK(0, 0);
					break;
				case DEBUGGER:
					CHECK_STACK(0, 0);
					{
						String *action = ptr<String>(ins.arg1);
						if (*action == "interrupt")
						{
							DO_DEBUG __asm__("int3");
						} else if (*action == "trace_enable") {
							trace_mute = false;
						} else if (*action == "trace_disable") {
							trace_mute = true;
						}
					}
					break;

				case POP:
					CHECK_STACK(1, 0);
					m_context->pop();
					break;
				case PUSH:
					CHECK_STACK(0, 1);
					m_context->push(ins.arg1);
					break;
				case SWAP: {
					CHECK_STACK(2, 2);
					Value tmp1 = m_context->top();
					m_context->pop();
					Value tmp2 = m_context->top();
					m_context->pop();
					m_context->push(tmp1);
					m_context->push(tmp2);
					}
					break;
				case DUP_TOP:
					CHECK_STACK(1, 2);
					m_context->push(m_context->top());
					break;

				case IS: {
					CHECK_STACK(1, 1);
					Value res = bvalue(ins.arg1 == m_context->top());
					m_context->pop();
					m_context->push(res);
					}
					break;
				case IS_EQ: {
					CHECK_STACK(2, 1);
					Value first = m_context->top();
					m_context->pop();
					Value second = m_context->top();
					m_context->pop();
					m_context->push(bvalue(first == second));
					}
					break;
				case IS_NOT: {
					CHECK_STACK(1, 1);
					Value res = bvalue(ins.arg1 != m_context->top());
					m_context->pop();
					m_context->push(res);
					}
					break;
				case IS_NOT_EQ:{
					CHECK_STACK(2, 1);
					Value first = m_context->top();
					m_context->pop();
					Value second = m_context->top();
					m_context->pop();
					m_context->push(bvalue(first != second));
					}
					break;
				case JMP:
					CHECK_STACK(0, 0);

					GC::safe_point();

					m_context->jump(ins.cache.machine_num);
					break;
				case JMP_IF:
					CHECK_STACK(1, 0);

					GC::safe_point();

					if (is_truthy(m_context->top()))
						m_context->jump(ins.cache.machine_num);
					m_context->pop();
					break;
				case JMP_IF_NOT:
					CHECK_STACK(1, 0);

					GC::safe_point();

					if (!is_truthy(m_context->top()))
						m_context->jump(ins.cache.machine_num);
					m_context->pop();
					break;

				case LEXICAL_CLEAN_SCOPE: {
					CHECK_STACK(0, 0);
					VariableFrame *frame = new_variable_frame(m_context->m_instructions);
					m_context->new_scope(frame);
					}
					break;
				case LEXICAL_LINKED_SCOPE: {
					CHECK_STACK(0, 0);
					VariableFrame *frame = new_variable_frame(m_context->m_instructions);
					frame->link_frame(m_context->m_lexicalvars);
					m_context->new_scope(frame);
					}
					break;
				case FRAME_GET: {
					CHECK_STACK(0, 1);
					size_t frameid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "Getting frame var %s (%d)\n", ptr<String>(ins.arg1)->c_str(), (int)frameid);
					m_context->push(m_context->get_framevar(frameid));
					}
					break;
				case FRAME_SET: {
					CHECK_STACK(1, 0);
					size_t frameid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "Setting frame var %s (%d) to: %s\n", ptr<String>(ins.arg1)->c_str(), (int)frameid, inspect(m_context->top()).c_str());
					m_context->set_framevar(frameid, m_context->top());
					m_context->pop();
					}
					break;
				case LOCAL_GET: {
					CHECK_STACK(0, 1);
					size_t localid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "Getting local var %s (%d)\n", ptr<String>(ins.arg1)->c_str(), (int)localid);
					m_context->push(m_context->get_localvar(localid));
					}
					break;
				case LOCAL_SET: {
					CHECK_STACK(1, 0);
					size_t localid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "Setting local var %s (%d) to: %s\n", ptr<String>(ins.arg1)->c_str(), (int)localid, inspect(m_context->top()).c_str());
					m_context->set_localvar(localid, m_context->top());
					m_context->pop();
					}
					break;
				case LEXICAL_GET: {
					CHECK_STACK(0, 1);
					size_t depth = ins.arg1.machine_num;
					size_t localid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "lexical_get %u@%u: %i\n", (unsigned)localid, (unsigned)depth, type(m_context->get_lexicalvar(localid, depth)));
					if (depth == 0)
						m_context->push(m_context->get_lexicalvar(localid));
					else
						m_context->push(m_context->get_lexicalvar(localid, depth));
					}
					break;
				case LEXICAL_SET: {
					CHECK_STACK(1, 0);
					size_t depth = ins.arg1.machine_num;
					size_t localid = (size_t)ins.cache.machine_num;
					TRACE_PRINTF(TRACE_VM, TRACE_SPAM, "lexical_set %u@%u: %i\n", (unsigned)localid, (unsigned)depth, type(m_context->top()));
					if (depth == 0)
						m_context->set_lexicalvar(localid, m_context->top());
					else
						m_context->set_lexicalvar(localid, depth, m_context->top());
					m_context->pop();
					}
					break;

				case CHANNEL_NEW: {
					CHECK_STACK(0, 1);
					const Value &octx = vstore(value(m_context));
					RunnableContext *nctx = new_context(octx);
					nctx->jump(ins.cache.machine_num);
					m_context->push(value(nctx));
					clear_vstore();
					}
					break;
				case CHANNEL_SPECIAL:
					CHECK_STACK(0, 1);
					m_context->push(special_channel(*ptr<String>(ins.arg1)));
					break;
				case CHANNEL_SEND: {
					CHECK_STACK(3, -1);

					GC::safe_point();

					const Value &val = vstore(m_context->top()); m_context->pop();
					const Value &ret = vstore(m_context->top()); m_context->pop();
					const Value &channel = vstore(m_context->top()); m_context->pop();

					// A context that's been channel_sended from should never be returned to,
					// so invalidate it.
					m_context->invalidate();
					channel_send(this, channel, val, ret);
					clear_vstore();
					}
					break;
				case CHANNEL_CALL:{
					CHECK_STACK(2, -1);

					GC::safe_point();

					const Value &val = vstore(m_context->top()); m_context->pop();
					const Value &channel = vstore(m_context->top()); m_context->pop();
					const Value &ret = vstore(value(m_context));

					channel_send(this, channel, val, ret);
					clear_vstore();
					}
					break;
				case CHANNEL_RET:{
					CHECK_STACK(2, -1);
					const Value &val = vstore(m_context->top()); m_context->pop();
					const Value &channel = vstore(m_context->top()); m_context->pop();

					// A context that's been channel_reted from should never be returned to,
					// so invalidate it.
					m_context->invalidate();
					channel_send(this, channel, val, value(&no_return_ctx));
					clear_vstore();
					}
					break;

				case MESSAGE_NEW: {
					long long id = ins.cache.machine_num;
					long long sysarg_count = ins.arg2.machine_num, sysarg_counter = sysarg_count - 1;
					long long arg_count = ins.arg3.machine_num, arg_counter = arg_count - 1;
					CHECK_STACK(sysarg_count + arg_count, 1);

					Message *msg = new_message(id, sysarg_count, arg_count);

					while (arg_count > 0 && arg_counter >= 0)
					{
						msg->args()[arg_counter] = m_context->top();
						m_context->pop();
						--arg_counter;
					}
					while (sysarg_count > 0 && sysarg_counter >= 0)
					{
						msg->sysargs()[sysarg_counter] = m_context->top();
						m_context->pop();
						--sysarg_counter;
					}

					m_context->push(value(msg));
					}
					break;
				case MESSAGE_SPLAT: {
					CHECK_STACK(2, 1);
					const Tuple &tuple = *ptr<Tuple>(m_context->top()); m_context->pop();
					const Message &msg = *ptr<Message>(m_context->top()); m_context->pop();

					Message *nmsg = new_message(msg.m_id, msg.sysarg_count(), msg.arg_count() + tuple.size());
					std::copy(msg.sysargs(), msg.sysargs_end(), nmsg->sysargs());
					std::copy(msg.args(), msg.args_end(), nmsg->args());
					std::copy(tuple.begin(), tuple.end(), nmsg->args() + msg.arg_count());
					m_context->push(value(nmsg));
					}
					break;
				case MESSAGE_ADD: {
					long long count = ins.arg1.machine_num, counter = 0;
					CHECK_STACK(1 + count, 1);
					const Message &msg = *ptr<Message>(*(m_context->stack_pos() - 1 - count));

					Message *nmsg = new_message(msg.m_id, msg.sysarg_count(), msg.arg_count() + count);
					std::copy(msg.sysargs(), msg.sysargs_end(), nmsg->sysargs());
					std::copy(msg.args(), msg.args_end(), nmsg->args());

					Message::iterator out = nmsg->args() + msg.arg_count();
					while (count > 0 && counter < count)
					{
						*out++ = m_context->top();
						m_context->pop();
						++counter;
					}
					m_context->pop(); // this is the message we pulled directly off the stack before.

					m_context->push(value(nmsg));
					}
					break;
				case MESSAGE_COUNT:
					CHECK_STACK(1, 2);
					m_context->push(value((long long)ptr<Message>(m_context->top())->arg_count()));
					break;
				case MESSAGE_IS:
					CHECK_STACK(1, 2);
					m_context->push(bvalue(ptr<Message>(m_context->top())->m_id == (uint64_t)ins.cache.machine_num));
					break;
				case MESSAGE_IS_PROTO:
					CHECK_STACK(1, 2);
					m_context->push(bvalue(ptr<Message>(m_context->top())->protocol_id() == (uint64_t)ins.cache.machine_num));
					break;
				case MESSAGE_ID:
					{
					CHECK_STACK(1, 2);
					Message *msg = ptr<Message>(m_context->top());
					m_context->push(value((long long)msg->m_id));
					}
					break;
				case MESSAGE_SPLIT_ID:
					{
					CHECK_STACK(1, 3);
					Message *msg = ptr<Message>(m_context->top());
					m_context->push(value((long long)msg->message_id()));
					m_context->push(value((long long)msg->protocol_id()));
					}
					break;
				case MESSAGE_CHECK:
					CHECK_STACK(1, 1);
					if (!is(m_context->top(), MESSAGE))
					{
						m_context->pop();
						m_context->push(False);
					}
					break;
				case MESSAGE_FORWARD: {
					CHECK_STACK(1, 1);

					long long id = ins.cache.machine_num;
					const Message &msg = *ptr<Message>(m_context->top());
					Message *nmsg = new_message(id, msg.sysarg_count(), msg.arg_count() + 1);
					std::copy(msg.sysargs(), msg.sysargs_end(), nmsg->sysargs());
					nmsg->args()[0] = value(new_string(msg.name()));
					std::copy(msg.args(), msg.args_end(), nmsg->args() + 1);
					m_context->pop();
					m_context->push(value(nmsg));
					break;
				}
				case MESSAGE_SYS_PREFIX: {
					long long count = ins.arg1.machine_num, counter = 0;
					CHECK_STACK(1 + count, 1);

					const Value *sdata = m_context->stack_pos() - 1 - count;
					const Message &msg = *ptr<Message>(*sdata++);
					Message *nmsg = new_message(msg.m_id, msg.sysarg_count() + count, msg.arg_count());
					Message::iterator to = nmsg->sysargs();
					while (counter++ < count)
					{
						*to++ = *sdata++;
					}
					std::copy(msg.sysargs(), msg.sysargs_end(), to);
					std::copy(msg.args(), msg.args_end(), nmsg->args());
					while (--counter != 0)
					{
						m_context->pop();
					}
					m_context->pop(); // message we read off stack before.
					m_context->push(value(nmsg));
					break;
				}
				case MESSAGE_SYS_UNPACK: {
					long long count = ins.arg1.machine_num, pos = count - 1;
					CHECK_STACK(1, 1 + count);

					const Message *msg = ptr<Message>(m_context->top());
					Message::const_iterator args = msg->sysargs();
					long long len = (long long)msg->sysarg_count();

					while (pos >= 0)
					{
						if (pos >= len)
							m_context->push(Undef);
						else
							m_context->push(args[pos]);

						pos -= 1;
					}
					}
					break;
				case MESSAGE_UNPACK: {
					long long first_count = ins.arg1.machine_num, first_counter = 0;
					long long splat = ins.arg2.machine_num;
					long long last_count = ins.arg3.machine_num, last_counter = 0;
					CHECK_STACK(1, 1 + first_count + last_count + (splat?1:0));

					const Message *msg = ptr<Message>(m_context->top());
					Message::const_iterator args = msg->args();
					long long len = (long long)msg->arg_count(), pos = len - 1;

					while (last_counter < last_count && pos >= first_count)
					{
						if (pos >= len)
							m_context->push(Nil);
						else
							m_context->push(args[pos]);

						pos -= 1;
						last_counter += 1;
					}

					if (splat != 0)
					{
						if (pos >= first_count)
						{
							Tuple *splat_tuple = new_tuple(pos - first_count + 1);
							Tuple::iterator out = splat_tuple->end();
							while (pos >= first_count)
							{
								--out;
								*out = args[pos];
								pos -= 1;
							}
							m_context->push(value(splat_tuple));
						} else {
							m_context->push(value(new_tuple(0)));
						}
					}

					pos = first_count - 1;

					while (first_counter < first_count && pos >= 0)
					{
						if (pos >= len)
							m_context->push(Nil);
						else
							m_context->push(args[pos]);

						pos -= 1;
						first_counter += 1;
					}
					}
					break;

				case STRING_COERCE: {
					const Value &coerce = ins.arg1;
					const Value &val = vstore(m_context->top());
					if (is(val, STRING))
					{
						CHECK_STACK(1, 2);
						// push a nil like we called the method.
						m_context->push(Nil);
					} else {
						CHECK_STACK(1, -1);
						m_context->pop();
						channel_send(this, val, value(new_message(coerce)), value(m_context));
					}
					}
					clear_vstore();
					break;

				case STRING_NEW: {
					long long count = ins.arg1.machine_num, counter = 0;
					CHECK_STACK(count, 1);
					const Value *sp = m_context->stack_pos() - 1;
					size_t len = 0;
					while (count > 0 && counter < count)
					{
						assert(is(sp[-counter], STRING));
						len += ptr<String>(sp[-counter])->length();
						++counter;
					}
					String *res = new_string(len);
					String::iterator out = res->begin();
					counter = 0;
					while (count > 0 && counter < count)
					{
						const String *val = ptr<String>(m_context->top());
						out = std::copy(val->begin(), val->end(), out);
						m_context->pop();
						++counter;
					}
					m_context->push(value(res));
					}
					break;

				case TUPLE_NEW: {
					long long count = ins.arg1.machine_num, counter = 0;
					CHECK_STACK(count, 1);
					Tuple *tuple = new_tuple(count);
					Tuple::iterator out = tuple->begin();
					while (count > 0 && counter < count)
					{
						*out++ = m_context->top();
						m_context->pop();
						++counter;
					}
					m_context->push(value(tuple));
					}
					break;
				case TUPLE_SPLAT: {
					CHECK_STACK(2, 1);
					const Tuple *tuple2 = ptr<Tuple>(m_context->top()); m_context->pop();
					const Tuple *tuple1 = ptr<Tuple>(m_context->top()); m_context->pop();
					Tuple *tuple = join_tuple(tuple1, tuple2);
					m_context->push(value(tuple));
					}
					break;
				case TUPLE_UNPACK: {
					long long first_count = ins.arg1.machine_num, first_counter = 0;
					long long splat = ins.arg2.machine_num;
					long long last_count = ins.arg3.machine_num, last_counter = 0;
					CHECK_STACK(1, 1 + first_count + last_count + (splat?1:0));

					const Tuple &tuple = *ptr<Tuple>(m_context->top());
					long long len = tuple.size(), pos = tuple.size() - 1;
					while (last_counter < last_count && pos >= first_count)
					{
						if (pos >= len)
							m_context->push(Nil);
						else
							m_context->push(tuple[pos]);

						pos -= 1;
						last_counter += 1;
					}

					if (splat != 0)
					{
						if (pos >= first_count)
						{
							Tuple *splat_tuple = new_tuple(pos - first_count + 1);
							Tuple::iterator out = splat_tuple->end();
							while (pos >= first_count)
							{
								--out;
								*out = tuple[pos];
								pos -= 1;
							}
							m_context->push(value(splat_tuple));
						} else {
							m_context->push(value(new_tuple(0)));
						}
					}

					pos = first_count - 1;

					while (first_counter < first_count && pos >= 0)
					{
						if (pos >= len)
							m_context->push(Nil);
						else
							m_context->push(tuple[pos]);

						pos -= 1;
						first_counter += 1;
					}
					}
					break;
				default:
					printf("Panic! Unknown instruction %d\n", ins.instruction);
					exit(1);
				}

				TRACE_OUT(TRACE_VM, TRACE_SPAM) {
					tprintf("Output: %d", (int)output);
					if ((long)output > 0)
					{
						const Value *it = std::max(
							m_context->stack_begin(), m_context->stack_pos() - output);
						for (; it != m_context->stack_pos(); it++)
						{
							tprintf("\n   %s", inspect(*it).c_str());
						}
					}
					tprintf(" <--\n");
					tprintf("----------------\n");
				}
Example #25
0
konoha_t konoha_open(const kplatform_t *platform)
{
	konoha_init();
	return (konoha_t)new_context(NULL, platform);
}
// Generate a new context that is valid in this environment
// Should be called *after* all variables are added to the environment
shared_ptr<ScopedVariableContext> ScopedVariableEnvironment::createNewContext(){
	shared_ptr<ScopedVariableContext> new_context( 
						new ScopedVariableContext(this));
	
	return new_context;
}
Example #27
0
bool solver_enumerationt::iterate(invariantt &_inv)
{
  tpolyhedra_domaint::templ_valuet &inv = 
    static_cast<tpolyhedra_domaint::templ_valuet &>(_inv);

  bool improved = false;

  literalt activation_literal = new_context();

  exprt inv_expr = tpolyhedra_domain.to_pre_constraints(inv);
  debug() << "pre-inv: " << from_expr(ns,"",inv_expr) << eom;

#ifndef DEBUG_FORMULA
  solver << or_exprt(inv_expr, literal_exprt(activation_literal));
#else
  debug() << "literal " << activation_literal << eom;
  literalt l = solver.convert(or_exprt(inv_expr, literal_exprt(activation_literal)));
  if(!l.is_constant()) 
  {
    debug() << "literal " << l << ": " << from_expr(ns,"",or_exprt(inv_expr, literal_exprt(activation_literal))) <<eom;
    formula.push_back(l);
  }
#endif

  exprt::operandst strategy_cond_exprs;
  tpolyhedra_domain.make_not_post_constraints(inv, 
    strategy_cond_exprs, strategy_value_exprs); 

#ifndef DEBUG_FORMULA
  solver << or_exprt(disjunction(strategy_cond_exprs),
		     literal_exprt(activation_literal));
#else

  exprt expr_act=
    or_exprt(disjunction(strategy_cond_exprs),
	       literal_exprt(activation_literal));

  l = solver.convert(expr_act);
  if(!l.is_constant()) 
  {
    debug() << "literal " << l << ": " << 
      from_expr(ns,"", expr_act) <<eom;
    formula.push_back(l);
  }
#endif

  debug() << "solve(): ";

#ifdef DEBUG_FORMULA
  bvt whole_formula = formula;
  whole_formula.insert(whole_formula.end(),activation_literals.begin(),activation_literals.end());
  solver.set_assumptions(whole_formula);
#endif

  if(solve() == decision_proceduret::D_SATISFIABLE) 
  { 
    debug() << "SAT" << eom;
      
    #if 0
    for(unsigned i=0; i<whole_formula.size(); i++) 
    {
      debug() << "literal: " << whole_formula[i] << " " << 
        solver.l_get(whole_formula[i]) << eom;
    }
          
    for(unsigned i=0; i<tpolyhedra_domain.template_size(); i++) 
    {
      exprt c = tpolyhedra_domain.get_row_constraint(i,inv[i]);
      debug() << "cond: " << from_expr(ns, "", c) << " " << 
          from_expr(ns, "", solver.get(c)) << eom;
      debug() << "guards: " << from_expr(ns, "", tpolyhedra_domain.templ.pre_guards[i]) << 
          " " << from_expr(ns, "", solver.get(tpolyhedra_domain.templ.pre_guards[i])) << eom;
      debug() << "guards: " << from_expr(ns, "", tpolyhedra_domain.templ.post_guards[i]) << " " 
          << from_expr(ns, "", solver.get(tpolyhedra_domain.templ.post_guards[i])) << eom; 	     	     }    
          
    for(replace_mapt::const_iterator
          it=renaming_map.begin();
          it!=renaming_map.end();    
          ++it)
          
    {
      debug() << "replace_map (1st): " << from_expr(ns, "", it->first) << " " << 
          from_expr(ns, "", solver.get(it->first)) << eom;
      debug() << "replace_map (2nd): " << from_expr(ns, "", it->second) << " " << 
          from_expr(ns, "", solver.get(it->second)) << eom;
    }
                  
    #endif
      
    tpolyhedra_domaint::templ_valuet new_value;
    tpolyhedra_domain.initialize(new_value);
    for(unsigned row=0;row<tpolyhedra_domain.template_size(); row++)
    {
      tpolyhedra_domaint::row_valuet v = 
	simplify_const(solver.get(strategy_value_exprs[row]));
      tpolyhedra_domain.set_row_value(row,v,new_value);

      debug() << "value: " << from_expr(ns,"",v) << eom;
    }
    tpolyhedra_domain.join(inv,new_value);

    improved = true;
  }
  else 
  {
    debug() << "UNSAT" << eom;

#ifdef DEBUG_FORMULA
    for(unsigned i=0; i<whole_formula.size(); i++) 
    {
      if(solver.is_in_conflict(whole_formula[i]))
        debug() << "is_in_conflict: " << whole_formula[i] << eom;
      else
        debug() << "not_in_conflict: " << whole_formula[i] << eom;
     }
#endif    
  }
  pop_context();

  return improved;
}
Example #28
0
File: main.c Project: gvlx/gawk
int
main(int argc, char **argv)
{
	/*
	 * The + on the front tells GNU getopt not to rearrange argv.
	 */
	const char *optlist = "+F:f:v:W;m:bcCd::D::e:E:gh:i:l:L:nNo::Op::MPrStVY";
	bool stopped_early = false;
	int old_optind;
	int i;
	int c;
	char *scan, *src;
	char *extra_stack;
	int have_srcfile = 0;
	SRCFILE *s;

	/* do these checks early */
	if (getenv("TIDYMEM") != NULL)
		do_flags |= DO_TIDY_MEM;

#ifdef HAVE_MCHECK_H
#ifdef HAVE_MTRACE
	if (do_tidy_mem)
		mtrace();
#endif /* HAVE_MTRACE */
#endif /* HAVE_MCHECK_H */

#if defined(LC_CTYPE)
	setlocale(LC_CTYPE, "");
#endif
#if defined(LC_COLLATE)
	setlocale(LC_COLLATE, "");
#endif
#if defined(LC_MESSAGES)
	setlocale(LC_MESSAGES, "");
#endif
#if defined(LC_NUMERIC) && defined(HAVE_LOCALE_H)
	/*
	 * Force the issue here.  According to POSIX 2001, decimal
	 * point is used for parsing source code and for command-line
	 * assignments and the locale value for processing input,
	 * number to string conversion, and printing output.
	 *
	 * 10/2005 --- see below also; we now only use the locale's
	 * decimal point if do_posix in effect.
	 *
	 * 9/2007:
	 * This is a mess. We need to get the locale's numeric info for
	 * the thousands separator for the %'d flag.
	 */
	setlocale(LC_NUMERIC, "");
	init_locale(& loc);
	setlocale(LC_NUMERIC, "C");
#endif
#if defined(LC_TIME)
	setlocale(LC_TIME, "");
#endif

#if MBS_SUPPORT
	/*
	 * In glibc, MB_CUR_MAX is actually a function.  This value is
	 * tested *a lot* in many speed-critical places in gawk. Caching
	 * this value once makes a speed difference.
	 */
	gawk_mb_cur_max = MB_CUR_MAX;
	/* Without MBS_SUPPORT, gawk_mb_cur_max is 1. */

	/* init the cache for checking bytes if they're characters */
	init_btowc_cache();
#endif

	(void) bindtextdomain(PACKAGE, LOCALEDIR);
	(void) textdomain(PACKAGE);

	(void) signal(SIGFPE, catchsig);
#ifdef SIGBUS
	(void) signal(SIGBUS, catchsig);
#endif

	(void) sigsegv_install_handler(catchsegv);
#define STACK_SIZE (16*1024)
	emalloc(extra_stack, char *, STACK_SIZE, "main");
	(void) stackoverflow_install_handler(catchstackoverflow, extra_stack, STACK_SIZE);
#undef STACK_SIZE

	myname = gawk_name(argv[0]);
	os_arg_fixup(&argc, &argv); /* emulate redirection, expand wildcards */

	if (argc < 2)
		usage(EXIT_FAILURE, stderr);

	/* initialize the null string */
	Nnull_string = make_string("", 0);

	/* Robustness: check that file descriptors 0, 1, 2 are open */
	init_fds();

	/* init array handling. */
	array_init();

	/* init the symbol tables */
	init_symbol_table();

	output_fp = stdout;

	/* we do error messages ourselves on invalid options */
	opterr = false;

	/* copy argv before getopt gets to it; used to restart the debugger */  
	save_argv(argc, argv);

	/* initialize global (main) execution context */
	push_context(new_context());

	/* option processing. ready, set, go! */
	for (optopt = 0, old_optind = 1;
	     (c = getopt_long(argc, argv, optlist, optab, NULL)) != EOF;
	     optopt = 0, old_optind = optind) {
		if (do_posix)
			opterr = true;

		switch (c) {
		case 'F':
			add_preassign(PRE_ASSIGN_FS, optarg);
			break;

		case 'E':
			disallow_var_assigns = true;
			/* fall through */
		case 'f':
			/*
			 * Allow multiple -f options.
			 * This makes function libraries real easy.
			 * Most of the magic is in the scanner.
			 *
			 * The following is to allow for whitespace at the end
			 * of a #! /bin/gawk line in an executable file
			 */
			scan = optarg;
			if (argv[optind-1] != optarg)
				while (isspace((unsigned char) *scan))
					scan++;
			src = (*scan == '\0' ? argv[optind++] : optarg);
			(void) add_srcfile((src && src[0] == '-' && src[1] == '\0') ?
					SRC_STDIN : SRC_FILE,
					src, srcfiles, NULL, NULL);

			break;

		case 'v':
			add_preassign(PRE_ASSIGN, optarg);
			break;

		case 'm':
			/*
			 * BWK awk extension.
			 *	-mf nnn		set # fields, gawk ignores
			 *	-mr nnn		set record length, ditto
			 *
			 * As of at least 10/2007, BWK awk also ignores it.
			 */
			if (do_lint)
				lintwarn(_("`-m[fr]' option irrelevant in gawk"));
			if (optarg[0] != 'r' && optarg[0] != 'f')
				warning(_("-m option usage: `-m[fr] nnn'"));
			break;

		case 'b':
			do_binary = true;
			break;

		case 'c':
			do_flags |= DO_TRADITIONAL;
			break;

		case 'C':
			copyleft();
			break;

		case 'd':
			do_flags |= DO_DUMP_VARS;
			if (optarg != NULL && optarg[0] != '\0')
				varfile = optarg;
			break;

		case 'D':
			do_flags |= DO_DEBUG;
			if (optarg != NULL && optarg[0] != '\0')
				command_file = optarg;
			break;

		case 'e':
			if (optarg[0] == '\0')
				warning(_("empty argument to `-e/--source' ignored"));
			else
				(void) add_srcfile(SRC_CMDLINE, optarg, srcfiles, NULL, NULL);
			break;

		case 'g':
			do_flags |= DO_INTL;
			break;

		case 'h':
			/* write usage to stdout, per GNU coding stds */
			usage(EXIT_SUCCESS, stdout);
			break;

		case 'i':
			(void) add_srcfile(SRC_INC, optarg, srcfiles, NULL, NULL);
			break;

		case 'l':
			(void) add_srcfile(SRC_EXTLIB, optarg, srcfiles, NULL, NULL);
			break;

		case 'L':
#ifndef NO_LINT
			do_flags |= DO_LINT_ALL;
			if (optarg != NULL) {
				if (strcmp(optarg, "fatal") == 0)
					lintfunc = r_fatal;
				else if (strcmp(optarg, "invalid") == 0) {
					do_flags &= ~DO_LINT_ALL;
					do_flags |= DO_LINT_INVALID;
				}
			}
			break;

		case 't':
			do_flags |= DO_LINT_OLD;
			break;
#else
		case 'L':
		case 't':
			break;
#endif

		case 'n':
			do_flags |= DO_NON_DEC_DATA;
			break;

		case 'N':
			use_lc_numeric = true;
			break;

		case 'O':
			do_optimize++;
			break;

		case 'p':
			do_flags |= DO_PROFILE;
			/* fall through */
		case 'o':
			do_flags |= DO_PRETTY_PRINT;
			if (optarg != NULL)
				set_prof_file(optarg);
			else
				set_prof_file(DEFAULT_PROFILE);
			break;

		case 'M':
#ifdef HAVE_MPFR
			do_flags |= DO_MPFR;
#endif
			break;

		case 'P':
			do_flags |= DO_POSIX;
			break;

		case 'r':
			do_flags |= DO_INTERVALS;
 			break;
 
		case 'S':
			do_flags |= DO_SANDBOX;
  			break;

		case 'V':
			do_version = true;
			break;

		case 'W':       /* gawk specific options - now in getopt_long */
			fprintf(stderr, _("%s: option `-W %s' unrecognized, ignored\n"),
				argv[0], optarg);
			break;

		case 0:
			/*
			 * getopt_long found an option that sets a variable
			 * instead of returning a letter. Do nothing, just
			 * cycle around for the next one.
			 */
			break;

		case 'Y':
#if defined(YYDEBUG) || defined(GAWKDEBUG)
			if (c == 'Y') {
				yydebug = 2;
				break;
			}
#endif
			/* if not debugging, fall through */
		case '?':
		default:
			/*
			 * If not posix, an unrecognized option stops argument
			 * processing so that it can go into ARGV for the awk
			 * program to see. This makes use of ``#! /bin/gawk -f''
			 * easier.
			 *
			 * However, it's never simple. If optopt is set,
			 * an option that requires an argument didn't get the
			 * argument. We care because if opterr is 0, then
			 * getopt_long won't print the error message for us.
			 */
			if (! do_posix
			    && (optopt == '\0' || strchr(optlist, optopt) == NULL)) {
				/*
				 * can't just do optind--. In case of an
				 * option with >= 2 letters, getopt_long
				 * won't have incremented optind.
				 */
				optind = old_optind;
				stopped_early = true;
				goto out;
			} else if (optopt != '\0') {
				/* Use POSIX required message format */
				fprintf(stderr,
					_("%s: option requires an argument -- %c\n"),
					myname, optopt);
				usage(EXIT_FAILURE, stderr);
			}
			/* else
				let getopt print error message for us */
			break;
		}
		if (c == 'E')	/* --exec ends option processing */
			break;
	}
out:

	if (do_nostalgia)
		nostalgia();

	/* check for POSIXLY_CORRECT environment variable */
	if (! do_posix && getenv("POSIXLY_CORRECT") != NULL) {
		do_flags |= DO_POSIX;
		if (do_lint)
			lintwarn(
	_("environment variable `POSIXLY_CORRECT' set: turning on `--posix'"));
	}

	if (do_posix) {
		use_lc_numeric = true;
		if (do_traditional)	/* both on command line */
			warning(_("`--posix' overrides `--traditional'"));
		else
			do_flags |= DO_TRADITIONAL;
			/*
			 * POSIX compliance also implies
			 * no GNU extensions either.
			 */
	}

	if (do_traditional && do_non_decimal_data) {
		do_flags &= ~DO_NON_DEC_DATA;
		warning(_("`--posix'/`--traditional' overrides `--non-decimal-data'"));
	}

	if (do_lint && os_is_setuid())
		warning(_("running %s setuid root may be a security problem"), myname);

#if MBS_SUPPORT
	if (do_binary) {
		if (do_posix)
			warning(_("`--posix' overrides `--characters-as-bytes'"));
		else
			gawk_mb_cur_max = 1;	/* hands off my data! */
#if defined(LC_ALL)
		setlocale(LC_ALL, "C");
#endif
	}
#endif

	if (do_debug)	/* Need to register the debugger pre-exec hook before any other */
		init_debug();

#ifdef HAVE_MPFR
	/* Set up MPFR defaults, and register pre-exec hook to process arithmetic opcodes */ 
	if (do_mpfr)
		init_mpfr(DEFAULT_PREC, DEFAULT_ROUNDMODE);
#endif

	/* load group set */
	init_groupset();

#ifdef HAVE_MPFR
	if (do_mpfr) {
		mpz_init(Nnull_string->mpg_i);
		Nnull_string->flags = (MALLOC|STRCUR|STRING|MPZN|NUMCUR|NUMBER);
	} else
#endif
	{
		Nnull_string->numbr = 0.0;
		Nnull_string->flags = (MALLOC|STRCUR|STRING|NUMCUR|NUMBER);
	}

	/*
	 * Tell the regex routines how they should work.
	 * Do this before initializing variables, since
	 * they could want to do a regexp compile.
	 */
	resetup();

	/* Set up the special variables */
	init_vars();

	/* Set up the field variables */
	init_fields();

	/* Now process the pre-assignments */
	for (i = 0; i <= numassigns; i++) {
		if (preassigns[i].type == PRE_ASSIGN)
			(void) arg_assign(preassigns[i].val, true);
		else	/* PRE_ASSIGN_FS */
			cmdline_fs(preassigns[i].val);
		efree(preassigns[i].val);
	}

	if (preassigns != NULL)
		efree(preassigns);

	if ((BINMODE & 1) != 0)
		if (os_setbinmode(fileno(stdin), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdin (%s)"), strerror(errno));
	if ((BINMODE & 2) != 0) {
		if (os_setbinmode(fileno(stdout), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdout (%s)"), strerror(errno));
		if (os_setbinmode(fileno(stderr), O_BINARY) == -1)
			fatal(_("can't set binary mode on stderr (%s)"), strerror(errno));
	}

#ifdef GAWKDEBUG
	setbuf(stdout, (char *) NULL);	/* make debugging easier */
#endif
	if (os_isatty(fileno(stdout)))
		output_is_tty = true;

	/* initialize API before loading extension libraries */
	init_ext_api();

	/* load extension libs */
        for (s = srcfiles->next; s != srcfiles; s = s->next) {
                if (s->stype == SRC_EXTLIB)
			load_ext(s->fullpath);
		else if (s->stype != SRC_INC)
			have_srcfile++;
        }

	/* do version check after extensions are loaded to get extension info */
	if (do_version)
		version();

	/* No -f or --source options, use next arg */
	if (! have_srcfile) {
		if (optind > argc - 1 || stopped_early) /* no args left or no program */
			usage(EXIT_FAILURE, stderr);
		(void) add_srcfile(SRC_CMDLINE, argv[optind], srcfiles, NULL, NULL);
		optind++;
	}

	/* Select the interpreter routine */
	init_interpret();

	init_args(optind, argc,
			do_posix ? argv[0] : myname,
			argv);

#if defined(LC_NUMERIC)
	/*
	 * FRAGILE!  CAREFUL!
	 * Pre-initing the variables with arg_assign() can change the
	 * locale.  Force it to C before parsing the program.
	 */
	setlocale(LC_NUMERIC, "C");
#endif
	/* Read in the program */
	if (parse_program(& code_block) != 0)
		exit(EXIT_FAILURE);
	
	if (do_intl)
		exit(EXIT_SUCCESS);

	if (do_lint)
		shadow_funcs();

	if (do_lint && code_block->nexti->opcode == Op_atexit)
		lintwarn(_("no program text at all!"));

	load_symbols();

	if (do_profile)
		init_profiling_signals();

#if defined(LC_NUMERIC)
	/*
	 * See comment above about using locale's decimal point.
	 *
	 * 10/2005:
	 * Bitter experience teaches us that most people the world over
	 * use period as the decimal point, not whatever their locale
	 * uses.  Thus, only use the locale's decimal point if being
	 * posixly anal-retentive.
	 *
	 * 7/2007:
	 * Be a little bit kinder. Allow the --use-lc-numeric option
	 * to also use the local decimal point. This avoids the draconian
	 * strictness of POSIX mode if someone just wants to parse their
	 * data using the local decimal point.
	 */
	if (use_lc_numeric)
		setlocale(LC_NUMERIC, "");
#endif
	
	init_io();
	output_fp = stdout;

	if (do_debug)
		debug_prog(code_block);
	else
		interpret(code_block);

	if (do_pretty_print) {
		dump_prog(code_block);
		dump_funcs();
	}

	if (do_dump_vars)
		dump_vars(varfile);

	if (do_tidy_mem)
		release_all_vars();
	
	/* keep valgrind happier */
	if (extra_stack)
		efree(extra_stack);

	final_exit(exit_val);
	return exit_val;	/* to suppress warnings */
}
Example #29
0
/*
 *	DO statement
 *	Handles DO;, DO CASE, DO WHILE, and iterative DO
 */
void
parse_do(TOKEN *first_token)
{
    TOKEN		token;
    int		token_class;
    int		case_line;
    char		case_statement[MAX_TOKEN_LENGTH];
    char		case_output[MAX_CASE_STATEMENT_SIZE];
    char		var_string[MAX_TOKEN_LENGTH];
    char		*temp_out_string, *temp_out_string1;
    DECL_MEMBER	*var_decl;
    DECL_ID		*var_decl_id;

    /* Create new context */
    new_context(DO, (TOKEN *) NULL);

    out_white_space(first_token);

    /* Determine what kind of DO statement */
    token_class = get_token(&token);

    switch (token_class) {

    case END_OF_LINE :
        /* DO; */
        out_white_space(&token);
        out_char('{');			/* } for dumb vi */
        parse_to_end();
        break;

    case IDENTIFIER :
        /* DO counter = start TO limit BY step */
        out_str("for");
        out_must_white(&token);
        out_char('(');

        /* Put full variable in var_string */
        var_string[0] = '\0';
        temp_out_string = out_string;
        out_string = var_string;
        token_class = parse_variable(&token, &var_decl, &var_decl_id);
        out_string = temp_out_string;

        /* Check for '=' */
        if ((token_class != OPERATOR) ||
                (token.token_type != EQUAL)) {
            parse_error("Missing '='");
            pop_context();
            return;
        }
        /* Send <ident> '=' <expr> */
        out_str(var_string);
        out_token(&token);
        token_class = parse_expression(&token);
        if ((token_class != RESERVED) ||
                (token.token_type != TO)) {
            parse_error("Missing TO");
            pop_context();
            return;
        }

        /* Send <ident> <= <limit> */
        out_str("; ");
        out_str(var_string);
        out_str(" <=");
        token_class = parse_expression(&token);
        out_str("; ");

        /* Parse increment */
        if ((token_class == RESERVED) &&
                (token.token_type == BY)) {

            /* Send <ident> += <step> */
            out_str(var_string);
            out_str(" +=");
            token_class = parse_expression(&token);
        } else {
            /* Send <ident>++ */
            out_str(var_string);
            out_str("++");
        }

        out_str(") {");		/* } for dumb vi */
        out_white_space(&token);

        if (token_class != END_OF_LINE) {
            parse_error("BY or ';' expected");
            pop_context();
            return;
        }

        parse_to_end();
        break;

    case RESERVED :
        switch (token.token_type) {

        case CASE :
            /* DO CASE <expr>; */
            out_str("switch (");
            if (parse_expression(&token) != END_OF_LINE) {
                parse_error("';' expected");
                pop_context();
                return;
            }
            out_white_space(&token);
            out_str(") {");		/* } for dumb vi */

            case_line = 0;
            while (1) {
                /* Place case statement in out_string */
                temp_out_string1 = out_string;
                case_output[0] = '\0';
                out_string = case_output;

                (void) snprintf(case_statement, sizeof(case_statement), "case %d :",
                                case_line++);
                token_class = parse_new_statement();
                if (token_class == END_OF_FILE) {
                    parse_error("Premature end-of-file");
                    exit(1);
                }
                if (token_class == END) {
                    out_string = temp_out_string1;
                    out_str(case_output);
                    break;
                }
                out_string = temp_out_string1;
                out_white_space(first_token);
                out_str(case_statement);
                out_str(case_output);
                out_white_space(first_token);
                out_str("break;\n");
            }
            break;

        case WHILE :
            /* DO WHILE <expr>; */
            out_str("while (");
            if (parse_expression(&token) != END_OF_LINE) {
                parse_error("';' expected");
                pop_context();
                return;
            }
            out_white_space(&token);
            out_str(") {");		/* } for dumb vi */

            parse_to_end();
            break;

        default:
            parse_error("Illegal DO clause");
            pop_context();
            return;
        }
        break;
    }

    /* End of context */
    pop_context();
}
Example #30
0
konoha_t konoha_open(void)
{
	konoha_init();
	return (konoha_t)new_context(NULL, K_PAGESIZE * 8);
}