Example #1
0
static int
client_init(char * remotehost, char * port) 
{
	int result = 1;
	int ret, sock;
	struct addrinfo * ai;
	struct addrinfo hints;
	
	memset (&hints, '\0', sizeof(hints));
	hints.ai_flags = AI_ADDRCONFIG;
	hints.ai_socktype = SOCK_STREAM;
	
	if(ret = getaddrinfo (remotehost, port, &hints, &ai))
		printf_die(stderr, "[ERROR] getaddrinfo('%s', '%s'): %s\n", EXIT_FAILURE, remotehost, port, gai_strerror(ret));
	if(!ai)
		printf_die(stderr, "[ERROR] getaddrinf(): couldn't fill the struct!\n", EXIT_FAILURE);
	struct addrinfo *runp = ai;
	while (runp) {
		sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
		if (sock != -1) {
			ndprintf(stdout, "[NETWORK] Connecting to server...\n");
			if(connect (sock, runp->ai_addr, runp->ai_addrlen) == 0) {
				ndprintf(stdout, "[NETWORK] connected to server\n");
				serverfd = sock;
				result = get_resp_value(0);
				break;
			}
			close(sock);
		}
		runp = runp->ai_next;
	}
	freeaddrinfo(ai);
	return result;
}
Example #2
0
NODE *lpprop(NODE *args)
   {
   NODE *plname, *pname, *newval, *plist, *val = NIL;

   plname = string_arg(args);
   pname = string_arg(cdr(args));
   newval = car(cddr(args));
   if (NOT_THROWING)
      {
      plname = intern(plname);
      if (flag__caseobj(plname, PLIST_TRACED))
         {
         ndprintf(writestream, "Pprop %s %s %s", maybe_quote(plname),
            maybe_quote(pname), maybe_quote(newval));
         if (ufun != NIL)
            ndprintf(writestream, " in %s\n%s", ufun, this_line);
         new_line(writestream);
         }
      plist = plist__caseobj(plname);
      if (plist != NIL)
         val = getprop(plist, pname, FALSE);
      if (val != NIL)
         setcar(cdr(val), newval);
      else
         setplist__caseobj(plname, cons(pname, cons(newval, plist)));
      }
   return (UNBOUND);
   }
Example #3
0
void
server_start (char *hostname, char *port)
{
	int sockd, ret, fd, i, opt = 1;
	struct addrinfo *ai, *runp, hints;
	struct sockaddr *addr;
	socklen_t addrlen = sizeof(addr);
	double start, end;
    
	memset (&hints, 0x0, sizeof (hints));
	hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
	hints.ai_socktype = SOCK_STREAM;

	ndprintf(stdout, "[SERVER] Starting Server at %s:%s\n[INFO] Number of players: %d\n", hostname, port, max_robots);

	if ((ret = getaddrinfo(hostname, port, &hints, &ai)))
		ndprintf_die(stderr, "[ERROR] getaddrinfo('%s', '%s'): %s\n", hostname, port, gai_strerror(ret));
	if (!ai)
		ndprintf_die(stderr, "[ERROR] getaddrinf(): couldn't fill the struct!\n");

	runp = ai;
	do {
		sockd = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
		if (sockd != -1)
			break;
		runp = runp->ai_next;
	} while (runp);
	if (sockd == -1)
		ndprintf_die(stderr, "[ERROR] socket(): Couldn't create socket!\n");

	/* To close the port after closing the socket */
	if (setsockopt(sockd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt)) == -1)
		ndprintf_die(stderr, "[ERROR] setsockopt(): %s\n", strerror(errno));
	if (bind(sockd, runp->ai_addr, runp->ai_addrlen))
		ndprintf_die(stderr, "[ERROR] bind(): %s\n", strerror(errno));
	if (listen(sockd, max_robots))
		ndprintf_die(stderr, "[ERROR] listen(): %s\n", strerror(errno));
	if (!(fds = (struct pollfd *) malloc (max_robots * sizeof(struct pollfd))))
		ndprintf_die(stderr, "[ERROR] Coulnd't malloc space for fds!\n");
	
	while (1) { /* Wait for all the clients to connect */
		fd = accept(sockd, (struct sockaddr *) &addr, &addrlen);
		if (!create_client(fd))
			sockwrite(fd, ERROR, "Couldn't duplicate the FD\n");
		if (current_robots >= max_robots)
			break;
	}
	ndprintf(stdout, "[GAME] Starting. All clients connected!\n");
	for (i = 0; i < max_robots; i++)
		sockwrite(fds[i].fd, START, "Let's play!");

	signal (SIGALRM, raise_timer);
}
Example #4
0
int server_process_connections(event_t event)
{
	int fd, i;
	struct sockaddr *addr;
	socklen_t addrlen = sizeof(addr);
	int res = 0;

	if (max_passive_cycles && current_passive_cycles >= max_passive_cycles)
		ndprintf_die(stdout, "[INFO] Terminated on client connection timeout\n");
	current_passive_cycles++;

	charge_timer();
	update_display();
	update_display_msg("Waiting for connections");
	process_robots(0);

	/* TODO: This is horrible. We should just poll for an incoming
	 * connection, data on existing fd, a keypress, or X event, not
	 * looping like hell. */
	fd = accept(sockd, (struct sockaddr *) &addr, &addrlen);
	if (fd >= 0) {
		if (max_robots == MAX_ROBOTS) {
			ndprintf(stdout, "[INFO] Ignoring excessive connection\n");
			close(fd);
		} else {
			if (!create_client(fd))
				sockwrite(fd, ERROR, "Internal error");
			else
				sockwrite(fd, OK, "%d %d %d", game_type,
					  (int)(shot_speed / SPEED_RATIO), max_cycles);
			if (autostart_robots > 0 && max_robots == autostart_robots)
				res = 1;
		}
	}

	if (event == EVENT_START)
		res = 1;

	if (res) {
		ndprintf(stdout, "[GAME] Starting. All clients connected!\n");
		/* notify all robots that are passively waiting for game start */
		for (i = 0; i < max_robots; i++) {
			if (!all_robots[i]->waiting)
				continue;
			all_robots[i]->waiting = 0;
			sockwrite(fds[i].fd, OK, "1");
		}

		gettimeofday(&game_start, NULL);
		current_passive_cycles = 0;
	}
	return res;
}
Example #5
0
int checksum_test()
{
	int ret = 0, send_times =0;
	udt_pocketbuf packet;
	u_32 check_sum,cs_tmp ;
	
	int nReadNum = rand() %(_READ_SIZE-10) +1 ;
	char *paddr ;

	FILE *pf = fopen("3.pdf", "r+b") ;
	
	if(!pf) {
		printf("open file error!\n") ;
		return -1;
	}

	init_udt_pocket(&(packet.pocket)) ;
	
	paddr =pocket_data(&(packet.pocket));
	POCKET_TYPE(&(packet.pocket)) = 3 ;
	while(nReadNum=fread(paddr,1,nReadNum,pf)) {
		
		calc_cs(&packet ,nReadNum) ;
		nd_sleep(1);

		check_sum =	POCKET_CHECKSUM(&(packet.pocket))  ;
		POCKET_CHECKSUM(&(packet.pocket)) = 0 ;

		
		nReadNum += ndt_header_size(&(packet.pocket)) ;
		cs_tmp = nd_checksum((NDUINT16*)&(packet.pocket),nReadNum) ;
		if(cs_tmp!=check_sum) {
			ndprintf("test checksum error check_sum=%d cs_tmp=%d\n", check_sum,cs_tmp);
			getch() ;
			exit(1);
		}
		else{
			ndprintf("test check OK\n", ++send_times,ret);
		}

		nReadNum = rand() %(_READ_SIZE-10) +1 ;
		
	}
	
	
	fclose(pf) ;
	
	//nd_connector_send(connect_handle,&msg_buf,ESF_URGENCY) ;

	return 0;	
}
Example #6
0
void rd_print_prompt(char *str) {
#ifdef ibm
#if defined(__RZTC__) || defined(WIN32)
    if (in_graphics_mode && !in_splitscreen)
#else
#ifndef _MSC_VER
    if (in_graphics_mode && ibm_screen_top == 0)
#endif /* _MSC_VER */
#endif
	lsplitscreen(NIL);
#endif
	
#ifdef HAVE_WX
	if(in_graphics_mode && !in_splitscreen)
		lsplitscreen(NIL);
#endif

#ifdef mac
    extern int in_fscreen(void);
    if (in_fscreen())
	lsplitscreen(NIL);
#endif

    ndprintf(stdout,"%t",str);
#if defined(__RZTC__) && !defined(WIN32) /* sowings */
    zflush();
#endif
}
Example #7
0
void server_cycle (SDL_Event *event)
{
	int i;
	if (current_cycles >= max_cycles) {
		for (i = 0; i < max_robots; i++) {
			if (fds[i].fd != -1) {
				sockwrite(fds[i].fd, DRAW, "Max cycles reached!\n");
				close(fds[i].fd);
			}
		}
		ndprintf(stdout, "[GAME] Ended - Draw!\n");
		exit(EXIT_SUCCESS);
	}
	current_cycles++;
	struct itimerval itv;
	itv.it_interval.tv_sec = 0;
	itv.it_interval.tv_usec = 0;
	itv.it_value.tv_sec = 0;
	itv.it_value.tv_usec = 10000;
	setitimer (ITIMER_REAL, &itv, NULL);
	timer = 0;
	cycle();
	update_display(event);
	process_robots();
}
Example #8
0
static int client_init(char *remotehost, char *port)
{
	int ret, sock = -1;
	struct addrinfo *ai, *runp;
	struct addrinfo hints;

#ifdef WIN32
	WSADATA wd;
	int err = WSAStartup(MAKEWORD(2,2), &wd);
	fprintf(stderr, "WSA startup: %d\n", err);
	if (err != 0)
		printf_die(stderr, "[ERROR] windows socket init failed: %d\n", EXIT_FAILURE, err);
#endif

	memset(&hints, '\0', sizeof(hints));
	hints.ai_flags = AI_ADDRCONFIG;
	hints.ai_socktype = SOCK_STREAM;

	ret = getaddrinfo(remotehost, port, &hints, &ai);
	if (ret)
		printf_die(stderr, "[ERROR] getaddrinfo('%s', '%s'): %s (%d)\n",
			   EXIT_FAILURE, remotehost, port, gai_strerror(ret), ret);
	if (!ai)
		printf_die(stderr, "[ERROR] getaddrinfo(): no address returned\n",
			   EXIT_FAILURE);

	runp = ai;
	while (runp) {
		sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
		if (sock != -1) {
			ndprintf(stdout, "[NETWORK] Connecting to server...\n");
			if (connect(sock, runp->ai_addr, runp->ai_addrlen) == 0) {
				ndprintf(stdout, "[NETWORK] Connected.\n");
				serverfd = sock;
				receive_config();
				break;
			}
			close(sock);
			sock = -1;
		}
		runp = runp->ai_next;
	}
	freeaddrinfo(ai);
	return (sock < 0);
}
Example #9
0
void server_start(char *hostname, char *port)
{
	int ret, opt = 1;
	struct addrinfo *ai, *runp, hints;

	memset(&hints, 0x0, sizeof (hints));
	hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
	hints.ai_socktype = SOCK_STREAM;

	ndprintf(stdout, "[SERVER] Starting Server at %s:%s\n", hostname, port);
	if (autostart_robots > 0)
		ndprintf(stdout, "[INFO] Number of players: %d\n", autostart_robots);

	if ((ret = getaddrinfo(hostname, port, &hints, &ai)))
		ndprintf_die(stderr, "[ERROR] getaddrinfo('%s', '%s'): %s\n",
			     hostname, port, gai_strerror(ret));
	if (!ai)
		ndprintf_die(stderr, "[ERROR] getaddrinf(): couldn't fill the struct!\n");

	runp = ai;
	do {
		sockd = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
		if (sockd != -1)
			break;
		runp = runp->ai_next;
	} while (runp);
	if (sockd == -1)
		ndprintf_die(stderr, "[ERROR] socket(): Couldn't create socket!\n");

	/* To close the port after closing the socket */
	if (setsockopt(sockd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt)) == -1)
		ndprintf_die(stderr, "[ERROR] setsockopt(): %s\n", strerror(errno));
	if (fcntl(sockd, F_SETFL, O_NONBLOCK))
		ndprintf_die(stderr, "[ERROR] fcntl(): %s\n", strerror(errno));
	if (bind(sockd, runp->ai_addr, runp->ai_addrlen))
		ndprintf_die(stderr, "[ERROR] bind(): %s\n", strerror(errno));
	if (listen(sockd, MAX_ROBOTS))
		ndprintf_die(stderr, "[ERROR] listen(): %s\n", strerror(errno));
	if (!(fds = (struct pollfd *) malloc (MAX_ROBOTS * sizeof(struct pollfd))))
		ndprintf_die(stderr, "[ERROR] Coulnd't malloc space for fds!\n");
}
Example #10
0
int thmsg_test()
{
	struct nd_thsrv_createinfo srv_info = {0} ;
	
	srv_info.run_module =SUBSRV_MESSAGE;					//srv_entry run module (ref e_subsrv_runmod)
	srv_info.srv_entry =NULL;		//service entry
	srv_info.srv_param = NULL ;					//param of srv_entry 
	
	ndstrcpy(srv_info.srv_name, "receiver") ;

	_recv_id = nd_thsrv_create(&srv_info) ;
	if(-1==_recv_id) {
		nd_logfatal("create recv server error !") ;
		exit(1) ;
	}
	
	srv_info.run_module =SUBSRV_RUNMOD_LOOP;					//srv_entry run module (ref e_subsrv_runmod)
	srv_info.srv_entry =sender;		//service entry
	srv_info.srv_param = NULL ;					//param of srv_entry 
	
	ndstrcpy(srv_info.srv_name, "sender") ;
	_send_id = nd_thsrv_create(&srv_info);
	if(-1== _send_id) {
		nd_logfatal("create sender server error !") ;
		exit(1) ;
	}
	nd_thsrv_hook(nd_thsrv_gethandle(_send_id),_msg_func) ;
	nd_thsrv_hook(nd_thsrv_gethandle(_recv_id),_msg_func) ;

	nd_thsrv_wait(_send_id) ;
	nd_thsrv_wait(_recv_id) ;
	/*context = nd_thsrv_gethandle(_send_id) ;
	if(context->th_handle)
		nd_waitthread(context->th_handle) ;

	//fprintf(stderr, "wait for received thread!\n") ;
	//nd_waitthread(_recv_id) ;
	context = nd_thsrv_gethandle(_recv_id) ;
	if(context)
		nd_waitthread(context->th_handle) ;
	*/

	ndprintf("wait received success exit!\n") ;
	
	nd_thsrv_release_all() ;
	
	nd_timer_destroy(__s_timer,0) ;
	nd_timer_destroy(__r_timer,0) ;
//	nd_common_release() ;
	
//	getch();
	return 0;
}
Example #11
0
int image(char *path)
{
	FILE *f;
	void *data;
	long fsize;
	int ret = 0;

	f = fopen(path, "rb");
	if (!f) {
		ndprintf(stderr, "[WARNING] Cannot find file %s\n", path);
		return 0;
	}
	fseek(f, 0, SEEK_END);
	fsize = ftell(f);
	if (fsize < 0 || fsize > MAX_IMAGE_BYTES) {
		ndprintf(stderr, "[WARNING] File %s longer than %d bytes\n",
			 path, MAX_IMAGE_BYTES);
		goto out_close;
	}
	rewind(f);
	data = malloc(fsize);
	if (!data) {
		ndprintf(stderr, "[WARNING] Cannot allocate memory\n");
		goto out_close;
	}
	if (fread(data, 1, fsize, f) != (size_t)fsize) {
		ndprintf(stderr, "[WARNING] Error reading from %s\n", path);
		goto out_free;
	}
	ret = sockwrite(serverfd, IMAGE, "%ld", fsize);
	get_resp_value(ret);
	ret = write(serverfd, data, fsize);
	get_resp_value(ret);
out_free:
	free(data);
out_close:
	fclose(f);
	return ret;
}
Example #12
0
/* representation of an object */
NODE *lrepresentation(NODE *args) {
    NODE *license, *binding, *classbind;
    char buffer[200];
    char *old_stringptr = print_stringptr;
    int old_stringlen = print_stringlen;

    print_stringlen = 200;
    print_stringptr = buffer;

    license = assoc(theName(Name_licenseplate), getvars(current_object));

    ndprintf(NULL, "${Object %p", getobject(license));
    binding = assoc(theName(Name_name), getvars(current_object));
    if (binding != NIL && getobject(binding) != UNBOUND) {
	ndprintf(NULL, ": %p", getobject(binding));
    }
    classbind = assoc(theName(Name_class), getvars(current_object));
    if (classbind != NIL) {
	if (binding == NIL || getobject(binding) == UNBOUND) {
	    ndprintf(NULL, ":");
	}else {
	    ndprintf(NULL, ",");
	}
	ndprintf(NULL, " the class %p", getobject(classbind));
    } else {
        classbind = varInObjectHierarchy(theName(Name_class), FALSE);
        if (classbind != UNBOUND && classbind != (NODE *)(-1)) {
            if (binding == NIL) {
                ndprintf(NULL, ":");
            } else {
                ndprintf(NULL, ",");
            }
            ndprintf(NULL, " a %p", classbind);
        }
    }
    ndprintf(NULL, "}");
    print_stringptr* = '\0';
    print_stringptr = old_stringptr;
    print_stringlen = old_stringlen;
    return make_strnode(buffer, NULL, strlen(buffer), STRING, strnzcpy);
}
Example #13
0
FILE *open_file(NODE *arg, char *access) {
    char *fnstr;
    FILE *tstrm;
    char *old_stringptr = print_stringptr;
    int old_stringlen = print_stringlen;

    if (is_list(arg)) { /* print to string */
	if (*access != 'w') {
	    err_logo(BAD_DATA_UNREC, arg);
	    return NULL;
	} else {
	    FIXNUM i = int_arg(cdr(arg));
	    if (NOT_THROWING && i > 0 && cddr(arg) == NIL) {
		char *tmp = (char *)malloc(i);
		*tmp = '\0';
		return (FILE *)tmp;
	    }
	    err_logo(BAD_DATA_UNREC, car(arg));
	    return NULL;
	}
    }

    arg = cnv_node_to_strnode(arg);
    if (arg == UNBOUND) return(NULL);
    if (file_prefix != NIL) {
	print_stringlen = getstrlen(file_prefix) +
			    getstrlen(arg) + 2;
	fnstr = (char *)malloc((size_t)print_stringlen + 1);
    } else
	fnstr = (char *) malloc((size_t)getstrlen(arg) + 1);
    if (fnstr == NULL) {
	err_logo(FILE_ERROR, make_static_strnode(message_texts[MEM_LOW]));
	print_stringptr = old_stringptr;
	print_stringlen = old_stringlen;
	return NULL;
    }
    if (file_prefix != NIL) {
	print_stringptr = fnstr;
	ndprintf((FILE *)NULL, "%p%t%p", file_prefix, separator, arg);
	*print_stringptr = '\0';
	print_stringptr = old_stringptr;
	print_stringlen = old_stringlen;
    } else
	noparity_strnzcpy(fnstr, getstrptr(arg), getstrlen(arg));
    tstrm = fopen(fnstr, access);
    free(fnstr);
    return(tstrm);
}
void silent_load(NODE *arg, char *prefix)
{
    FILE *tmp_stream;
    NODE *tmp_line, *exec_list;
    char load_path[200];
    NODE *st = valnode__caseobj(Startup);
    int sv_val_status = val_status;

    /* This procedure is called three ways:
     *    silent_load(NIL,*argv)	loads *argv
     *    silent_load(proc,logolib)     loads logolib/proc
     *    silent_load(proc,NULL)	loads proc.lg
     * The "/" or ".lg" is supplied by this procedure as needed.
     */

    if (prefix == NULL && arg == NIL) return;
    strcpy(load_path, (prefix == NULL ? "" : prefix));
    if (arg != NIL) {
	arg = cnv_node_to_strnode(arg);
	if (arg == UNBOUND) return;
#ifdef unix
	if (prefix != NULL) strcat(load_path, "/");
#endif
	noparitylow_strnzcpy(load_path + (int)strlen(load_path),
			     getstrptr(arg), getstrlen(arg));
	if (prefix == NULL) strcat(load_path, ".lg");
	gcref(arg);
    }
    tmp_stream = loadstream;
    tmp_line = vref(current_line);
    loadstream = fopen(load_path, "r");
    if (loadstream != NULL) {
	while (!feof(loadstream) && NOT_THROWING) {
	    current_line = reref(current_line, reader(loadstream, ""));
	    exec_list =parser(current_line, TRUE);
	    val_status = 0;
	    if (exec_list != NIL) eval_driver(exec_list);
	}
	fclose(loadstream);
	runstartup(st);
	val_status = sv_val_status;
    } else if (arg == NIL) ndprintf(stdout,"File not found: %t\n", prefix);
    loadstream = tmp_stream;
    deref(current_line);
    current_line = tmp_line;
}
Example #15
0
int server_cycle(event_t event)
{
	int res;

	if (current_cycles >= max_cycles || event == EVENT_FINISH) {
		ndprintf(stdout, "[GAME] Ended - Draw!\n");
		res = 1;
	} else {
		current_cycles++;
		charge_timer();
		cycle();
		update_display();
		res = process_robots(1);
	}
	if (res) {
		gettimeofday(&game_end, NULL);
		complete_ranking();
	}
	return res;
}
NODE *lkeyp()
{
    long nc;
#ifdef mac
    int c;
#endif

    if (readstream == stdin && interactive) {
	charmode_on();
	fflush(stdout);
#ifdef __ZTC__
	zflush();
#endif
#if defined(mac)
	csetmode(C_RAW, stdin);
	c = ungetc(getc(readstream), readstream);
	csetmode(C_ECHO, stdin);
	return(c == EOF ? False : True);
#elif defined(ibm)
	return(kbhit() ? True : False);
#else
#ifdef FIONREAD
	ioctl(0,FIONREAD,(char *)(&nc));
#else
	ndprintf(stdout,"Can't KEYP, no FIONREAD on this system\n");
	nc = 1;    /* pretend there's a char so we don't loop */
#endif
	if (nc > 0)
	    return(True);
	else
	    return(False);
#endif
    }
    ungetc(getc(readstream),readstream);
    if (feof(readstream))
	return(True);
    else
	return(False);
}
Example #17
0
/* An explicit control evaluator, taken almost directly from SICP, section
 * 5.2.  list is a flat list of expressions to evaluate.  where is a label to
 * begin at.  Return value depends on where.
 */ 
NODE *evaluator(NODE *list, enum labels where) {

    /* registers */
    NODE    *exp    = NIL,  /* the current expression */
	    *val    = NIL,  /* the value of the last expression */
	    *proc   = NIL,  /* the procedure definition */
	    *argl   = NIL,  /* evaluated argument list */
	    *unev   = NIL,  /* list of unevaluated expressions */
	    *stack  = NIL,  /* register stack */
	    *parm   = NIL,  /* the current formal */
	    *catch_tag = NIL,
	    *arg    = NIL;  /* the current actual */

/* registers that don't get reference counted, so we pretend they're ints */
FIXNUM	    vsp    = 0,		/* temp ptr into var_stack */
	    cont   = 0,		/* where to go next */
	    formals = (FIXNUM)NIL; /* list of formal parameters */

    int i, nargs;
    BOOLEAN tracing;	    /* are we tracing the current procedure? */
    FIXNUM oldtailcall;	    /* in case of reentrant use of evaluator */
    FIXNUM repcount;	    /* count for repeat */
    FIXNUM old_ift_iff;

    oldtailcall = tailcall;
    old_ift_iff = ift_iff_flag;
    save2(var,this_line);
    assign(var, var_stack);
    save2(fun,ufun);
    cont = (FIXNUM)all_done;
    numsave((FIXNUM)cont);
    newcont(where);
    goto fetch_cont;
    
begin_line:
    ref(list);
    assign(this_line, list);
    newcont(end_line);
begin_seq:
    make_tree(list);
    if (!is_tree(list)) {
	assign(val, UNBOUND);
	goto fetch_cont;
    }
    assign(unev, tree__tree(list));
    assign(val, UNBOUND);
    goto eval_sequence;

end_line:
    if (val != UNBOUND) {
	if (NOT_THROWING) err_logo(DK_WHAT, val);
	deref(val);
    }
    val = NIL;
    deref(list);
    goto fetch_cont;


/* ----------------- EVAL ---------------------------------- */

tail_eval_dispatch:
    tailcall = 1;
eval_dispatch:
    switch (nodetype(exp)) {
	case QUOTE:			/* quoted literal */
	    assign(val, node__quote(exp));
	    goto fetch_cont;
	case COLON:			/* variable */
	    assign(val, valnode__colon(exp));
	    while (val == UNBOUND && NOT_THROWING)
		assign(val, err_logo(NO_VALUE, node__colon(exp)));
	    goto fetch_cont;
	case CONS:			/* procedure application */
	    if (tailcall == 1 && is_macro(car(exp)) &&
				 is_list(procnode__caseobj(car(exp)))) {
		/* tail call to user-defined macro must be treated as non-tail
		 * because the expression returned by the macro
		 * remains to be evaluated in the caller's context */
		assign(unev, NIL);
		goto non_tail_eval;
	    }
	    assign(fun, car(exp));
	    if (cdr(exp) != NIL)
		goto ev_application;
	    else
		goto ev_no_args;
	default:
	    assign(val, exp);		/* self-evaluating */
	    goto fetch_cont;
    }

ev_no_args:
    /* Evaluate an application of a procedure with no arguments. */
    assign(argl, NIL);
    goto apply_dispatch;    /* apply the procedure */

ev_application:
    /* Evaluate an application of a procedure with arguments. */
    assign(unev, cdr(exp));
    assign(argl, NIL);
    mixsave(tailcall,var);
    num2save(val_status,ift_iff_flag);
    save2(didnt_get_output,didnt_output_name);
eval_arg_loop:
    if (unev == NIL) goto eval_args_done;
    assign(exp, car(unev));
    if (exp == Not_Enough_Node) {
	if (NOT_THROWING)
	    err_logo(NOT_ENOUGH, NIL);
	goto eval_args_done;
    }
    save(argl);
    save2(unev,fun);
    save2(ufun,last_ufun);
    save2(this_line,last_line);
    assign(var, var_stack);
    tailcall = -1;
    val_status = 1;
    assign(didnt_get_output,
	   cons_list(0,fun,ufun,this_line,END_OF_LIST));
    assign(didnt_output_name, NIL);
    newcont(accumulate_arg);
    goto eval_dispatch;	    /* evaluate the current argument */

accumulate_arg:
    /* Put the evaluated argument into the argl list. */
    reset_args(var);
    restore2(this_line,last_line);
    restore2(ufun,last_ufun);
    assign(last_call, fun);
    restore2(unev,fun);
    restore(argl);
    while (NOT_THROWING && val == UNBOUND) {
	assign(val, err_logo(DIDNT_OUTPUT, NIL));
    }
    push(val, argl);
    pop(unev);
    goto eval_arg_loop;

eval_args_done:
    restore2(didnt_get_output,didnt_output_name);
    num2restore(val_status,ift_iff_flag);
    mixrestore(tailcall,var);
    if (stopping_flag == THROWING) {
	assign(val, UNBOUND);
	goto fetch_cont;
    }
    assign(argl, reverse(argl));
/* --------------------- APPLY ---------------------------- */
apply_dispatch:
    /* Load in the procedure's definition and decide whether it's a compound
     * procedure or a primitive procedure.
     */
    proc = procnode__caseobj(fun);
    if (is_macro(fun)) {
	num2save(val_status,tailcall);
	val_status = 1;
	newcont(macro_return);
    }
    if (proc == UNDEFINED) {
	if (ufun != NIL) {
	    untreeify_proc(ufun);
	}
	if (NOT_THROWING)
	    assign(val, err_logo(DK_HOW, fun));
	else
	    assign(val, UNBOUND);
	goto fetch_cont;
    }
    if (is_list(proc)) goto compound_apply;
    /* primitive_apply */
    if (NOT_THROWING)
	assign(val, (*getprimfun(proc))(argl));
    else
	assign(val, UNBOUND);
#define do_case(x) case x: goto x;
fetch_cont:
    {
	enum labels x = (enum labels)cont;
	cont = (FIXNUM)car(stack);
	numpop(&stack);
	switch (x) {
	    do_list(do_case)
	    default: abort();
	}
    }

compound_apply:
#ifdef mac
    check_mac_stop();
#endif
#ifdef ibm
    check_ibm_stop();
#endif
    if (tracing = flag__caseobj(fun, PROC_TRACED)) {
	for (i = 0; i < trace_level; i++) print_space(writestream);
	trace_level++;
	ndprintf(writestream, "( %s ", fun);
    }
/* Bind the actuals to the formals */
    vsp = (FIXNUM)var_stack;	/* remember where we came in */
    for (formals = (FIXNUM)formals__procnode(proc);
    	 formals != (FIXNUM)NIL;
	 formals = (FIXNUM)cdr((NODE *)formals)) {
	    parm = car((NODE *)formals);
	    if (nodetype(parm) == INT) break;	/* default # args */
	    if (argl != NIL) {
		arg = car(argl);
		if (tracing) {
		    print_node(writestream, maybe_quote(arg));
		    print_space(writestream);
		}
	    } else
		arg = UNBOUND;
	    if (nodetype(parm) == CASEOBJ) {
		if (not_local(parm,(NODE *)vsp)) {
		    push(parm, var_stack);
		    setobject(var_stack, valnode__caseobj(parm));
		}
		tell_shadow(parm);
		setvalnode__caseobj(parm, arg);
	    } else if (nodetype(parm) == CONS) {
		/* parm is optional or rest */
		if (not_local(car(parm),(NODE *)vsp)) {
		    push(car(parm), var_stack);
		    setobject(var_stack, valnode__caseobj(car(parm)));
		}
		tell_shadow(car(parm));
		if (cdr(parm) == NIL) {		    /* parm is rest */
		    setvalnode__caseobj(car(parm), argl);
		    break;
		}
		if (arg == UNBOUND) {		    /* use default */
		    save2(fun,var);
		    save2(ufun,last_ufun);
		    save2(this_line,last_line);
		    save2(didnt_output_name,didnt_get_output);
		    num2save(ift_iff_flag,val_status);
		    assign(var, var_stack);
		    tailcall = -1;
		    val_status = 1;
		    mixsave(formals,argl);
		    numsave(vsp);
		    assign(list, cdr(parm));
		    if (NOT_THROWING)
			make_tree(list);
		    else
			assign(list, NIL);
		    if (!is_tree(list)) {
			assign(val, UNBOUND);
			goto set_args_continue;
		    }
		    assign(unev, tree__tree(list));
		    assign(val, UNBOUND);
		    newcont(set_args_continue);
		    goto eval_sequence;

set_args_continue:
		    numrestore(vsp);
		    mixrestore(formals,argl);
		    parm = car((NODE *)formals);
		    reset_args(var);
		    num2restore(ift_iff_flag,val_status);
		    restore2(didnt_output_name,didnt_get_output);
		    restore2(this_line,last_line);
		    restore2(ufun,last_ufun);
		    restore2(fun,var);
		    arg = val;
		}
		setvalnode__caseobj(car(parm), arg);
	    }
	    if (argl != NIL) pop(argl);
    }
    if (check_throwing) {
	assign(val, UNBOUND);
	goto fetch_cont;
    }
    vsp = 0;
    if (tracing = flag__caseobj(fun, PROC_TRACED)) {
	if (NOT_THROWING) print_char(writestream, ')');
	new_line(writestream);
	save(fun);
	newcont(compound_apply_continue);
    }
    assign(val, UNBOUND);
    assign(last_ufun, ufun);
    assign(ufun, fun);
    assign(last_line, this_line);
    assign(this_line, NIL);
    proc = procnode__caseobj(fun);
    assign(list, bodylist__procnode(proc));	/* get the body ... */
    make_tree_from_body(list);
    if (!is_tree(list)) {
	goto fetch_cont;
    }
    assign(unev, tree__tree(list));
    if (NOT_THROWING) stopping_flag = RUN;
    assign(output_node, UNBOUND);
    if (val_status == 1) val_status = 2;
    else if (val_status == 5) val_status = 3;
    else val_status = 0;
eval_sequence:
    /* Evaluate each expression in the sequence.  Stop as soon as
     * val != UNBOUND.
     */
    if (!RUNNING || val != UNBOUND) {
	goto fetch_cont;
    }
    if (nodetype(unev) == LINE) {
	assign(this_line, unparsed__line(unev));
	if (flag__caseobj(ufun, PROC_STEPPED)) {
	    char junk[20];

	    if (tracing) {
		int i = 1;
		while (i++ < trace_level) print_space(stdout);
	    }
	    print_node(stdout, this_line);
	    ndprintf(stdout, " >>> ");
	    input_blocking++;
#ifndef TIOCSTI
	    if (!setjmp(iblk_buf))
#endif
#ifdef __ZTC__
		ztc_getcr();
#else
		fgets(junk, 19, stdin);
#endif
	    input_blocking = 0;
	    update_coords('\n');
	}
    }
    assign(exp, car(unev));
    pop(unev);
    if (is_list(exp) && (is_tailform(procnode__caseobj(car(exp))))) {
      if (nameis(car(exp),Output) || nameis(car(exp),Op)) {
	assign(didnt_get_output,
	       cons_list(0,car(exp),ufun,this_line,END_OF_LIST));
	assign(didnt_output_name, NIL);
	if (val_status == 2 || val_status == 3) {
	    val_status = 1;
	    assign(exp, cadr(exp));
	    goto tail_eval_dispatch;
	} else if (ufun == NIL) {
	    err_logo(AT_TOPLEVEL,car(exp));
	    assign(val, UNBOUND);
	    goto fetch_cont;
	} else if (val_status < 4) {
	    val_status = 1;
	    assign(exp, cadr(exp));
	    assign(unev, NIL);
	    goto non_tail_eval;	    /* compute value then give error */
	}
      } else if (nameis(car(exp),Stop)) {
	if (ufun == NIL) {
	    err_logo(AT_TOPLEVEL,car(exp));
	    assign(val, UNBOUND);
	    goto fetch_cont;
	} else if (val_status == 0 || val_status == 3) {
	    assign(val, UNBOUND);
	    goto fetch_cont;
	} else if (val_status < 4) {
	    assign(didnt_output_name, fun);
	    assign(val, UNBOUND);
	    goto fetch_cont;
	}
      } else { /* maybeoutput */
	assign(exp, cadr(exp));
	val_status = 5;
	goto tail_eval_dispatch;
      }
    }
    if (unev == NIL) {
	if (val_status == 2 || val_status == 4) {
	    assign(didnt_output_name, fun);
	    assign(unev, UNBOUND);
	    goto non_tail_eval;
	} else {
	    goto tail_eval_dispatch;
	}
    }
    if (is_list(car(unev)) && nameis(car(car(unev)),Stop)) {
	if ((val_status == 0 || val_status == 3) && ufun != NIL) {
	    goto tail_eval_dispatch;
	} else if (val_status < 4) {
	    assign(didnt_output_name, fun);
	    goto tail_eval_dispatch;
	}
    }
non_tail_eval:
    save2(unev,fun);
    num2save(ift_iff_flag,val_status);
    save2(ufun,last_ufun);
    save2(this_line,last_line);
    save(var);
    assign(var, var_stack);
    tailcall = 0;
    newcont(eval_sequence_continue);
    goto eval_dispatch;

eval_sequence_continue:
    reset_args(var);
    restore(var);
    restore2(this_line,last_line);
    restore2(ufun,last_ufun);
    if (dont_fix_ift) {
	num2restore(dont_fix_ift,val_status);
	dont_fix_ift = 0;
    } else
	num2restore(ift_iff_flag,val_status);
    restore2(unev,fun);
    if (stopping_flag == MACRO_RETURN) {
	if (unev == UNBOUND) assign(unev, NIL);
	assign(unev, append(val, unev));
	assign(val, UNBOUND);
	stopping_flag = RUN;
	if (unev == NIL) goto fetch_cont;
    } else if (val_status < 4) {
	if (STOPPING || RUNNING) assign(output_node, UNBOUND);
	if (stopping_flag == OUTPUT || STOPPING) {
	    stopping_flag = RUN;
	    assign(val, output_node);
	    if (val != UNBOUND && val_status < 2 && NOT_THROWING) {
		assign(didnt_output_name,Output);
		err_logo(DIDNT_OUTPUT,Output);
	    }
	    if (val == UNBOUND && val_status == 1 && NOT_THROWING) {
		assign(didnt_output_name,Stop);
		err_logo(DIDNT_OUTPUT,Output);
	    }
	    goto fetch_cont;
	}
    }
    if (val != UNBOUND) {
	err_logo((unev == NIL ? DK_WHAT_UP : DK_WHAT), val);
	assign(val, UNBOUND);
    }
    if (NOT_THROWING && (unev == NIL || unev == UNBOUND)) {
	if (val_status != 4)  err_logo(DIDNT_OUTPUT,NIL);
	goto fetch_cont;
    }
    goto eval_sequence;

compound_apply_continue:
    /* Only get here if tracing */
    restore(fun);
    --trace_level;
    if (NOT_THROWING) {
	for (i = 0; i < trace_level; i++) print_space(writestream);
	print_node(writestream, fun);
	if (val == UNBOUND)
	    ndprintf(writestream, " stops\n");
	else {
	    ref(val);
	    ndprintf(writestream, " outputs %s\n", maybe_quote(val));
	    deref(val);
	}
    }
    goto fetch_cont;

/* --------------------- MACROS ---------------------------- */

macro_return:
    num2restore(val_status,tailcall);
    while (!is_list(val) && NOT_THROWING) {
	assign(val,err_logo(ERR_MACRO,val));
    }
    if (NOT_THROWING) {
	if (is_cont(val)) {
	    newcont(cont__cont(val));
	    val->n_car = NIL;
	    assign(val, val__cont(val));
	    goto fetch_cont;
	}
macro_reval:
	if (tailcall == 0) {
	    make_tree(val);
	    stopping_flag = MACRO_RETURN;
	    if (!is_tree(val)) assign(val, NIL);
	    else assign(val, tree__tree(val));
	    goto fetch_cont;
	}
	assign(list,val);
	goto begin_seq;
    }
    assign(val, UNBOUND);
    goto fetch_cont;

runresult_continuation:
    assign(list, val);
    newcont(runresult_followup);
    val_status = 5;
    goto begin_seq;

runresult_followup:
    if (val == UNBOUND) {
	assign(val, NIL);
    } else {
	assign(val, cons(val, NIL));
    }
    goto fetch_cont;

repeat_continuation:
    assign(list, cdr(val));
    repcount = getint(car(val));
repeat_again:
    assign(val, UNBOUND);
    if (repcount == 0) goto fetch_cont;
    mixsave(repcount,list);
    num2save(val_status,tailcall);
    val_status = 4;
    newcont(repeat_followup);
    goto begin_seq;

repeat_followup:
    if (val != UNBOUND && NOT_THROWING) {
	ref(val);
	err_logo(DK_WHAT, val);
	unref(val);
    }
    num2restore(val_status,tailcall);
    mixrestore(repcount,list);
    if (val_status < 4 && tailcall != 0) {
	if (STOPPING || RUNNING) assign(output_node, UNBOUND);
	if (stopping_flag == OUTPUT || STOPPING) {
	    stopping_flag = RUN;
	    assign(val, output_node);
	    if (val != UNBOUND && val_status < 2) {
		err_logo(DK_WHAT_UP,val);
	    }
	    goto fetch_cont;
	}
    }
    if (repcount > 0)    /* negative means forever */
	--repcount;
#ifdef mac
    check_mac_stop();
#endif
#ifdef ibm
    check_ibm_stop();
#endif
    if (RUNNING) goto repeat_again;
    assign(val, UNBOUND);
    goto fetch_cont;

catch_continuation:
    assign(list, cdr(val));
    assign(catch_tag, car(val));
    if (compare_node(catch_tag,Error,TRUE) == 0) {
	push(Erract, var_stack);
	setobject(var_stack, valnode__caseobj(Erract));
	setvalnode__caseobj(Erract, UNBOUND);
    }
    save(catch_tag);
    save2(didnt_output_name,didnt_get_output);
    num2save(val_status,tailcall);
    newcont(catch_followup);
    val_status = 5;
    goto begin_seq;

catch_followup:
    num2restore(val_status,tailcall);
    restore2(didnt_output_name,didnt_get_output);
    restore(catch_tag);
    if (val_status < 4 && tailcall != 0) {
	if (STOPPING || RUNNING) assign(output_node, UNBOUND);
	if (stopping_flag == OUTPUT || STOPPING) {
	    stopping_flag = RUN;
	    assign(val, output_node);
	    if (val != UNBOUND && val_status < 2) {
		err_logo(DK_WHAT_UP,val);
	    }
	}
    }
    if (stopping_flag == THROWING &&
	compare_node(throw_node, catch_tag, TRUE) == 0) {
	    throw_node = reref(throw_node, UNBOUND);
	    stopping_flag = RUN;
	    assign(val, output_node);
    }
    goto fetch_cont;

begin_apply:
    /* This is for lapply. */
    assign(fun, car(val));
    while (nodetype(fun) == ARRAY && NOT_THROWING)
	assign(fun, err_logo(APPLY_BAD_DATA, fun));
    assign(argl, cadr(val));
    assign(val, UNBOUND);
    while (!is_list(argl) && NOT_THROWING)
	assign(argl, err_logo(APPLY_BAD_DATA, argl));
    if (NOT_THROWING && fun != NIL) {
	if (is_list(fun)) {		    /* template */
	    if (is_list(car(fun)) && cdr(fun) != NIL) {
		/* lambda form */
		formals = (FIXNUM)car(fun);
		numsave(tailcall);
		tailcall = 0;
		llocal((NODE *)formals);    /* bind the formals locally */
		numrestore(tailcall);
		for ( ;
		     formals && argl && NOT_THROWING;
		     formals = (FIXNUM)cdr((NODE *)formals),
		     assign(argl, cdr(argl)))
			setvalnode__caseobj(car((NODE *)formals), car(argl));
		assign(val, cdr(fun));
		goto macro_reval;
	    } else {		/* question-mark form */
		save(qm_list);
		assign(qm_list, argl);
		assign(list, fun);
		make_tree(list);
		if (list == NIL || !is_tree(list)) {
		    goto qm_failed;
		}
		assign(unev, tree__tree(list));
		save2(didnt_output_name,didnt_get_output);
		num2save(val_status,tailcall);
		newcont(qm_continue);
		val_status = 5;
		goto eval_sequence;

qm_continue:
		num2restore(val_status,tailcall);
		restore2(didnt_output_name,didnt_get_output);
		if (val_status < 4 && tailcall != 0) {
		    if (STOPPING || RUNNING) assign(output_node, UNBOUND);
		    if (stopping_flag == OUTPUT || STOPPING) {
			stopping_flag = RUN;
			assign(val, output_node);
			if (val != UNBOUND && val_status < 2) {
			    err_logo(DK_WHAT_UP,val);
			}
		    }
		}
qm_failed:
		restore(qm_list);
		goto fetch_cont;
	    }
	} else {    /* name of procedure to apply */
	    int min, max, n;
	    NODE *arg;
	    assign(fun, intern(fun));
	    if (procnode__caseobj(fun) == UNDEFINED && NOT_THROWING &&
		fun != Null_Word)
		    silent_load(fun, NULL);    /* try ./<fun>.lg */
	    if (procnode__caseobj(fun) == UNDEFINED && NOT_THROWING &&
		fun != Null_Word)
		    silent_load(fun, logolib); /* try <logolib>/<fun> */
	    proc = procnode__caseobj(fun);
	    while (proc == UNDEFINED && NOT_THROWING) {
		assign(val, err_logo(DK_HOW_UNREC, fun));
	    }
	    if (NOT_THROWING) {
		if (nodetype(proc) == CONS) {
		    min = getint(minargs__procnode(proc));
		    max = getint(maxargs__procnode(proc));
		} else {
		    if (getprimdflt(proc) < 0) {	    /* special form */
			err_logo(DK_HOW_UNREC, fun);    /* can't apply */
			goto fetch_cont;
		    } else {
			min = getprimmin(proc);
			max = getprimmax(proc);
		    }
		}
		for (n = 0, arg = argl; arg != NIL; n++, arg = cdr(arg));
		if (n < min) {
		    err_logo(NOT_ENOUGH, NIL);
		} else if (n > max && max >= 0) {
		    err_logo(TOO_MUCH, NIL);
		} else {
		    goto apply_dispatch;
		}
	    }
	}
    }
    goto fetch_cont;

all_done:
    tailcall = oldtailcall;
    ift_iff_flag = old_ift_iff;
    restore2(fun,ufun);
    reset_args(var);
    restore2(var,this_line);
    deref(argl);deref(unev);deref(stack);deref(catch_tag);deref(exp);
    return(val);
}
Example #18
0
void
process_robots ()
{
	int i, ret, rfd;
	struct pollfd *pfd;
	result_t result;
	char buf[STD_BUF];
	struct robot *robot;
	int to_talk;

	for (i = 0; i < max_robots; i++)
		fds[i].events = POLLIN | POLLOUT;

	do {
		to_talk = 0;
		rfd = -1;
		for (i = 0; i < max_robots; i++) {
			if (fds[i].fd != -1) {
				to_talk++;
				rfd = fds[i].fd;
			}
		}

		if (to_talk == 0) {
			if (winner)
				ndprintf(stdout, "[GAME] Winner found\n");
			else
				ndprintf(stdout, "[GAME] Ended - No winner\n");
			exit(EXIT_SUCCESS);
		}
		else if (to_talk == 1)
			winner = 1;

		poll(fds, max_robots, 10);
		for (i = 0; i < max_robots; i++) {
			robot = all_robots[i];
			pfd = &fds[i];
			if (pfd->fd == -1) // Dead robot
				continue;
			if (pfd->events == 0)
				to_talk--;

			if (pfd->revents & (POLLERR | POLLHUP)) { /* Error or disconnected robot -> kill */
				close(pfd->fd);
				pfd->fd = -1;
				kill_robot(robot);
				continue;
			}
			if (robot->damage >= 100) {
				sockwrite(pfd->fd, DEAD, "Sorry!");
				close(pfd->fd);
				pfd->fd = -1;
				continue;
			}

			if (!(pfd->revents & POLLIN))
				continue;

			if (!(pfd->revents & POLLOUT)) {
				close(pfd->fd);
				pfd->fd = -1;
				kill_robot(robot);
				continue;
			}

			ret = read(pfd->fd, buf, STD_BUF);
			switch (ret) {
				case -1:
					close(pfd->fd);
					pfd->fd = -1;
					kill_robot(robot);
					break;
				case 0:
					abort ();
				default:
					buf[ret] = '\0';
					result = execute_cmd(robot, buf);
					if (result.error) {
						sockwrite(pfd->fd, ERROR, "Violation of the protocol!\n");
						close(pfd->fd);
						pfd->fd = -1;
						kill_robot(robot);
					}
					else {
						if (result.cycle)
							pfd->events = 0;
						if (winner && pfd->fd == rfd)
							sockwrite(pfd->fd, END, "%d", result.result);
						else
							sockwrite(pfd->fd, OK, "%d", result.result);
					}
					break;
			}
		}
	} while (to_talk && !timer);
}
Example #19
0
int  start (int argc,char ** argv) {
#else
int main(int argc, char *argv[]) {
#endif
    NODE *exec_list = NIL;
    NODE *cl_tail = NIL;
    int argc2;
    char **argv2;

#ifdef SYMANTEC_C
    extern void (*openproc)(void);
    extern void __open_std(void);
    openproc = &__open_std;
#endif

#ifdef mac
    init_mac_memory();
#endif

    bottom_stack = &exec_list; /*GC*/

#ifndef HAVE_WX
#ifdef x_window
    x_window_init(argc, argv);
#endif
#endif
    (void)addseg();
    term_init();
    init();

    math_init();

#ifdef ibm
    signal(SIGINT, SIG_IGN);
#if defined(__RZTC__) && !defined(WIN32) /* sowings */
    _controlc_handler = do_ctrl_c;
    controlc_open();
#endif
#else /* !ibm */
    signal(SIGINT, logo_stop);
#endif /* ibm */
#ifdef mac
    signal(SIGQUIT, SIG_IGN);
#else /* !mac */
	//signal(SIGQUIT, logo_pause);
#endif
    /* SIGQUITs never happen on the IBM */

    if (argc < 2) {
#ifndef WIN32
      if (1 || isatty(1))   // fix this.  for interactive from menu bar.
#endif
      {
#ifdef HAVE_WX
	extern char *SVN;
#endif
	char version[20];
	lcleartext(NIL);
#ifdef HAVE_WX
	strcpy(version,"6.0");
	strcat(version,SVN);
#else
	strcpy(version,"5.6");
#endif
	ndprintf(stdout, message_texts[WELCOME_TO], version);
	new_line(stdout);
      }
    }

#ifdef HAVE_WX
    setvalnode__caseobj(LogoVersion, make_floatnode(6.0));
#else
    setvalnode__caseobj(LogoVersion, make_floatnode(5.6));
#endif
    setflag__caseobj(LogoVersion, VAL_BURIED);

    argv2 = argv; argc2 = argc;

    if (!strcmp(*argv+strlen(*argv)-4, "logo")) {
	argv++;
	while (--argc > 0 && strcmp(*argv, "-") && NOT_THROWING) {
	    argv++;
	}
    }

    argv++;
    while (--argc > 0) {
	if (command_line == NIL) 
	    cl_tail = command_line = cons(make_static_strnode(*argv++), NIL);
	else {
	    setcdr(cl_tail, cons(make_static_strnode(*argv++), NIL));
	    cl_tail = cdr(cl_tail);
	}
    }

    setvalnode__caseobj(CommandLine, command_line);

    silent_load(Startuplg, logolib);
    silent_load(Startup, NULL); /* load startup.lg */
    if (!strcmp(*argv2+strlen(*argv2)-4, "logo")) {
	argv2++;
	while (--argc2 > 0 && strcmp(*argv2, "-") && NOT_THROWING) {
	    silent_load(NIL,*argv2++);
	    }
    }

    for (;;) {
	if (NOT_THROWING) {
	    check_reserve_tank();
	    current_line = reader(stdin,"? ");
#ifdef __RZTC__
		(void)feof(stdin);
		if (!in_graphics_mode)
		    printf(" \b");
		fflush(stdout);
#endif

#ifndef WIN32
	    if (feof(stdin) && !isatty(0)) lbye(NIL);
#endif

#ifdef __RZTC__
	    if (feof(stdin)) clearerr(stdin);
#endif
	    if (NOT_THROWING) {
		exec_list = parser(current_line, TRUE);
		if (exec_list != NIL) eval_driver(exec_list);
	    }
	}
#ifdef HAVE_WX
	if (wx_leave_mainloop) {
	  break;
	}
#endif	
	if (stopping_flag == THROWING) {
	    if (isName(throw_node, Name_error)) {
		err_print(NULL);
	    } else if (isName(throw_node, Name_system))
		break;
	    else if (!isName(throw_node, Name_toplevel)) {
		err_logo(NO_CATCH_TAG, throw_node);
		err_print(NULL);
	    }
	    stopping_flag = RUN;
	}
	if (stopping_flag == STOP || stopping_flag == OUTPUT) {
	/*    ndprintf(stdout, "%t\n", message_texts[CANT_STOP]);   */
	    stopping_flag = RUN;
	}
    }
    //prepare_to_exit(TRUE);
    exit(0);
    return 0;
}
Example #20
0
NODE *reader(FILE *strm, char *prompt) {
    int c = 0, dribbling, vbar = 0, paren = 0;
    int bracket = 0, brace = 0, p_pos, contin=1, insemi=0, raw=0;
    char *phys_line, *lookfor = ender;
    NODETYPES this_type = STRING;
    NODE *ret;
    char *old_stringptr = print_stringptr;
    int old_stringlen = print_stringlen;

    fix_turtle_shownness();

    //readingInstruction = !strcmp(prompt, "? ");
    readingInstruction = (strm == stdin);
#ifdef HAVE_WX
    wx_refresh();
    if(readingInstruction) {
      wx_enable_scrolling();
    }
#endif

    print_stringptr = ender;
    print_stringlen = 99;
    ndprintf(NULL, "\n%p\n", theName(Name_end));
    *print_stringptr = '\0';
    print_stringptr = old_stringptr;
    print_stringlen = old_stringlen;

    if (!strcmp(prompt, "RW")) {	/* called by readword */
	    prompt = "";
	    contin = 0;
    }
    if (!strcmp(prompt, "RAW")) {	/* called by readrawline */
	    prompt = "";
	    contin = 0;
	    raw = 1;
    }
charmode_off();
#ifdef WIN32
    dribbling = 0;
#else
    dribbling = (dribblestream != NULL && strm == stdin);
#endif
    if (p_line == 0) {
    	p_line = malloc(MAX_PHYS_LINE);
	if (p_line == NULL) {
	    err_logo(OUT_OF_MEM, NIL);
		    return UNBOUND;
	}
    	p_end = &p_line[MAX_PHYS_LINE-1];
    }
    phys_line = p_line;
    if (strm == stdin && *prompt) {
	if (interactive) {
	  rd_print_prompt(prompt);
#ifdef WIN32
	  win32_update_text();
#endif
	}
    }
    if (strm == stdin) {
	input_blocking++;
	erract_errtype = FATAL;
    }

#ifndef TIOCSTI
    if (!setjmp(iblk_buf)) {
#endif
    c = rd_getc(strm);
/*    if ((c=='\b' || c=='\127') && strm==stdin && interactive) {
	silent_load(LogoLogo, logolib);
	c = rd_getc(strm);
    } */   /* 6.0 */
#ifdef mac
    if (c == '\r') c = '\n';	/* seen in raw mode by keyp, never read */
#endif
    while (c != EOF && (vbar || paren || bracket || brace || c != '\n')
		    && NOT_THROWING) {
	if (dribbling) rd_putc(c, dribblestream);
	if (!raw && c == '\\' && (c = rd_getc(strm)) != EOF) {
	    if (dribbling) rd_putc(c, dribblestream);
	    c = setparity(c);
	    this_type = BACKSLASH_STRING;
	    if (c == setparity('\n') && strm == stdin) {
		if (interactive) zrd_print_prompt("\\ ");
	    }
	}
	if (c != EOF) into_line(c);
	if (raw) {
	    c = rd_getc(strm);
	    continue;
	}
	if (*prompt && (c&0137) == ((*lookfor)&0137)) {
		lookfor++;
		if (*lookfor == 0) {
		    if (deepend_proc_name != NIL)
			err_logo(DEEPEND, deepend_proc_name);
		    else
			err_logo(DEEPEND_NONAME, NIL);
		    break;
		}
	} else lookfor = ender;
	if (c == '|' && !insemi) {
	    vbar = !vbar;
	    this_type = VBAR_STRING;
	} else if (contin && !vbar && !insemi) {
		if (c == '(') paren++;
		else if (paren && c == ')') paren--;
		else if (c == '[') bracket++;
		else if (bracket && c == ']') bracket--;
		else if (c == '{') brace++;
		else if (brace && c == '}') brace--;
		else if (c == ';') insemi++;
	}

	if (this_type == STRING && strchr(special_chars, c))
	    this_type = VBAR_STRING;
	if (/* (vbar || paren ...) && */ c == '\n') {
	    insemi = 0;
	    if (strm == stdin) {
		if (interactive) zrd_print_prompt(vbar ? "| " : "~ ");
	    }
	}
	while (!vbar && c == '~' && (c = rd_getc(strm)) != EOF) {
	    int gotspc = 0;
	    while (c == ' ' || c == '\t') {
		gotspc = 1;
		c = rd_getc(strm);
	    }
	    if (dribbling) rd_putc(c, dribblestream);
	    if (c != '\n' && gotspc) into_line(' ');
	    into_line(c);
	    if (c == '\n') {
		insemi = 0;
		if (interactive && strm == stdin) zrd_print_prompt("~ ");
	    }
	    else if (c == '(') paren++;
	    else if (paren && c == ')') paren--;
	    else if (c == '[') bracket++;
	    else if (bracket && c == ']') bracket--;
	    else if (c == '{') brace++;
	    else if (brace && c == '}') brace--;
	    else if (c == ';') insemi++;
	}
	if (c != EOF) c = rd_getc(strm);
    }
#ifndef TIOCSTI
    }
#endif
    *phys_line = '\0';
    input_blocking = 0;
#if defined(__RZTC__) && !defined(WIN32) /* sowings */
    fix_cursor();
    if (interactive && strm == stdin) newline_bugfix();
#endif
    if (dribbling)
	rd_putc('\n', dribblestream);
    if (c == EOF && strm == stdin) {
	if (interactive) clearerr(stdin);
	rd_print_prompt("\n");
    }
    if (phys_line == p_line) return(Null_Word); /* so emptyp works */
    ret = make_strnode(p_line, (struct string_block *)NULL, (int)strlen(p_line),
		       this_type, strnzcpy);
#if 0
    if (strm == stdin && !strcmp(prompt, "? ")){
	char *histline = malloc(1+strlen(p_line));
	strcpy(histline, p_line);
	*hist_inptr++ = histline;
	if (hist_inptr >= &cmdHistory[HIST_MAX]) {
	    hist_inptr = cmdHistory;
	}
	if (*hist_inptr) {
	    free(*hist_inptr);
	    *hist_inptr = 0;
	}
	hist_outptr = hist_inptr;
    }
#endif

    //added (evan)
    readingInstruction = 0;
    return(ret);
}
Example #21
0
static void _srv_clean(void) 
{
	ndprintf(_NDT("eixt %d\n"),nd_thread_self()) ;
}
Example #22
0
File: scan.c Project: Ntools/n
tool(void)
{
	char buf[BUFSIZ],*p;
	unsigned short div2(char *,char **);
	struct KEY kk,*kp;
	size_t cnt;
	FILE *fp;
	int i,sts;

	keyptr = key;
	ininame = "keys.ini";
	if((fp= fopen(ininame,"r")) == NULL) {  /* Curent directory */
		if((p= getenv("KEYS")) != NULL) {
			fp= fopen(p,"r");  /* Env val directory */
		}
	}
	if(fp == NULL) {
#ifndef UNIX
		_searchenv(ininame,"PATH",buf);
#else
		sprintf(buf,"/usr/local/etc/%s", ininame);
#endif
		if((fp= fopen(buf,"r")) == NULL) return(NG);  /* PATH directory */
	}
	if((keyptr = (struct KEY *)calloc(KEYDEFMAX,sizeof(struct KEY))) == NULL)
		abort();
	cnt= 0;
	while(fgets(buf,BUFSIZ,fp) != NULL) {
		crcut(buf);
		if(buf[0] == ';' || buf[0] == '*' || buf[0] == '#') continue;
		if((kk.code = div2(buf,&p)) == 0xffff) {
			keyptr = key; break;
		}
		kk.keyword = buf;
		kp = lfind(&kk, key, &key_count,sizeof(struct KEY),cpkey);
		if(kp == NULL) {
			if(othset(&kk,buf,p) == NG) {
				ndprintf("Keyword not found [%s]!\n",buf);
				if(ynchk("Continue ?") != YES) {
#if (defined TEXT98)
					popscrn();
#elif (defined UNIX)
					ttclose();
#else
					batch("///",NULL);
#endif
					exit(1);
				}
			}
			continue;
		}
		kk.func = kp->func;
		kk.helpmsg = kp->helpmsg;
		if(key_count < KEYDEFMAX) {
			if(cnt) kp = lfind(&kk, keyptr, &cnt,sizeof(struct KEY), codekey);
			else kp= NULL;
			if(kp == NULL) {
				kk.keyword= memgets(buf);
				lsearch(&kk, keyptr, &cnt, sizeof(struct KEY), codekey);
			}
		}
	}
	key_count= cnt;
	fclose(fp);
}
int main(int argc, char *argv[]) {
	NODE *exec_list = NIL;
	NODE *cl_tail = NIL;
	int argc2;
	char **argv2;

	bottom_stack = &exec_list; /*GC*/


	(void) addseg();
	term_init();
	init();

	math_init();
	my_init();

	signal(SIGINT, logo_stop);

	if (argc < 2) {
		if (1 || isatty(1)) // fix this.  for interactive from menu bar.
		{
			char version[20];
			lcleartext(NIL);
			strcpy(version, "5.6");
			ndprintf(stdout, message_texts[WELCOME_TO], version);
			new_line(stdout);
		}
	}

	setvalnode__caseobj(LogoVersion, make_floatnode(5.6));
	setflag__caseobj(LogoVersion, VAL_BURIED);

	argv2 = argv;
	argc2 = argc;

	if (!strcmp(*argv + strlen(*argv) - 4, "logo")) {
		argv++;
		while (--argc > 0 && strcmp(*argv, "-") && NOT_THROWING) {
			argv++;
		}
	}

	argv++;
	while (--argc > 0) {
		if (command_line == NIL)
			cl_tail = command_line = cons(make_static_strnode(*argv++), NIL);
		else {
			setcdr(cl_tail, cons(make_static_strnode(*argv++), NIL));
			cl_tail = cdr(cl_tail);
		}
	}

	setvalnode__caseobj(CommandLine, command_line);

	silent_load(Startuplg, logolib);
	silent_load(Startup, NULL); /* load startup.lg */
	if (!strcmp(*argv2 + strlen(*argv2) - 4, "logo")) {
		argv2++;
		while (--argc2 > 0 && strcmp(*argv2, "-") && NOT_THROWING) {
			silent_load(NIL, *argv2++);
		}
	}

	for (;;) {
		if (NOT_THROWING) {
			check_reserve_tank();
			current_line = reader(stdin, "? ");

			if (feof(stdin) && !isatty(0))
				lbye(NIL);

			if (NOT_THROWING) {
				exec_list = parser(current_line, TRUE);
				if (exec_list != NIL)
					eval_driver(exec_list);
			}
		}
		if (stopping_flag == THROWING) {
			if (isName(throw_node, Name_error)) {
				err_print(NULL);
			} else if (isName(throw_node, Name_system))
				break;
			else if (!isName(throw_node, Name_toplevel)) {
				err_logo(NO_CATCH_TAG, throw_node);
				err_print(NULL);
			}
			stopping_flag = RUN;
		}
		if (stopping_flag == STOP || stopping_flag == OUTPUT) {
			/*    ndprintf(stdout, "%t\n", message_texts[CANT_STOP]);   */
			stopping_flag = RUN;
		}
	}
	//prepare_to_exit(TRUE);
	my_finish();
	exit(0);
	return 0;
}