Ejemplo n.º 1
0
void
cndfs_local_setup   (run_t *run, wctx_t *ctx)
{
    cndfs_alg_local_t  *cloc = (cndfs_alg_local_t *) ctx->local;
    cloc->timer = RTcreateTimer ();
    ndfs_local_setup (run, ctx);
    size_t len = state_info_serialize_int_size (ctx->state);
    cloc->in_stack = dfs_stack_create (len);
    cloc->out_stack = dfs_stack_create (len);

    if ((get_strategy(run->alg) & Strat_TA) == 0) {
        cloc->pink = fset_create (sizeof(ref_t), sizeof(size_t), FSET_MIN_SIZE, 24);
    }

    if (get_strategy(run->alg) & Strat_CNDFS) return;

    if (run->shared->rec == NULL) {
        Abort ("Missing recursive strategy for %s!",
               key_search(strategies, get_strategy(run->alg)));
        return;
    }

    HREassert (ctx->global != NULL, "Run global before local init");

    // We also need to finalize the worker initialization:
    ctx->global->rec = run_init (run->shared->rec, ctx->model);

    // Recursive strategy maybe unaware of its caller, so here we update its
    // recursive bits (top-level strategy always has rec_bits == 0, which
    // is ensured by ndfs_local_setup):
    ctx->global->rec->local->rec_bits = run->shared->color_bit_shift;
    cloc->rec = ctx->global->rec->local;
}
Ejemplo n.º 2
0
gpointer                       
gtoy_object_new_with_size               (GToyObjectType *type, gsize size)
{
        gtoy_return_val_if_fail (gtoy_object_type_is (type), NULL, 
                                 GTOY_ERROR_INVALID_OBJECT_TYPE);
        gtoy_return_val_if_fail (size > 0, NULL, 
                                 GTOY_ERROR_NULL_OBJECT_SIZE);

        GToyObject *object = g_malloc (size);

        object->magic = GTOY_OBJECT_MAGIC;
        object->type = type;
        object->ref_count = 1;
        object->disposed = FALSE;

        // Try running the init...
        if (run_init (object))
                return object;
        else
                return NULL;
}
Ejemplo n.º 3
0
/*
 * Take one step along the current "run" path
 *
 * Called with a real direction to begin a new run, and with zero
 * to continue a run in progress.
 */
void mon_run_step(int dir)
{
	/* Start run */
	if (dir)
	{
		/* Initialize */
		run_init(dir);
	}

	/* Continue run */
	else
	{
		/* Update run */
		if (run_test())
		{
			/* Done */
			return;
		}
	}

}
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
	/* Command-line options and defaults */
	const char *console = "/dev/console";
	const char *realroot;
	const char *init;
	const char *error;
	const char *drop_caps = NULL;
	char **initargs;

	/* Variables... */
	int o;

	/* Parse the command line */
	program = argv[0];

	while ((o = getopt(argc, argv, "c:d:")) != -1) {
		if (o == 'c') {
			console = optarg;
		} else if (o == 'd') {
			drop_caps = optarg;
		} else {
			usage();
		}
	}

	if (argc - optind < 2)
		usage();

	realroot = argv[optind];
	init = argv[optind + 1];
	initargs = argv + optind + 1;

	error = run_init(realroot, console, drop_caps, init, initargs);

	/* If run_init returns, something went wrong */
	fprintf(stderr, "%s: %s: %s\n", program, error, strerror(errno));
	return 1;
}
Ejemplo n.º 5
0
/**
 * Take one step along the current "run" path
 *
 * Called with a real direction to begin a new run, and with zero
 * to continue a run in progress.
 */
void run_step(int dir)
{
    /* Start run */
    if (dir) {
	/* Paranoia */
	p_ptr->running_withpathfind = 0;

	/* Initialize */
	run_init(dir);

	/* Hack -- Set the run counter */
	p_ptr->running = (p_ptr->command_arg ? p_ptr->command_arg : 1000);

	/* Calculate torch radius */
	p_ptr->update |= (PU_TORCH);
    }

    /* Continue run */
    else {
	if (!p_ptr->running_withpathfind) {
	    /* Update run */
	    if (run_test()) {
		/* Disturb */
		disturb(0, 0);

		/* Done */
		return;
	    }
	}

	else {
	    /* Abort if we have finished */
	    if (pf_result_index < 0) {
		disturb(0, 0);
		p_ptr->running_withpathfind = FALSE;
		return;
	    }
	    /* Abort if we would hit a wall */
	    else if (pf_result_index == 0) {
		int y, x;

		/* Get next step */
		y = p_ptr->py + ddy[pf_result[pf_result_index] - '0'];
		x = p_ptr->px + ddx[pf_result[pf_result_index] - '0'];

		/* Known wall */
		if ((cave_info[y][x] & (CAVE_MARK)) && !is_valid_pf(y, x)) {
		    disturb(0, 0);
		    p_ptr->running_withpathfind = FALSE;
		    return;
		}
	    }
	    /* Hack -- walking stick lookahead. If the player has computed a
	     * path that is going to end up in a wall, we notice this and
	     * convert to a normal run. This allows us to click on unknown
	     * areas to explore the map. We have to look ahead two, otherwise
	     * we don't know which is the last direction moved and don't
	     * initialise the run properly. */
	    else if (pf_result_index > 0) {
		int y, x;

		/* Get next step */
		y = p_ptr->py + ddy[pf_result[pf_result_index] - '0'];
		x = p_ptr->px + ddx[pf_result[pf_result_index] - '0'];

		/* Known wall */
		if ((cave_info[y][x] & (CAVE_MARK)) && !is_valid_pf(y, x)) {
		    disturb(0, 0);
		    p_ptr->running_withpathfind = FALSE;
		    return;
		}

		/* Get step after */
		y = y + ddy[pf_result[pf_result_index - 1] - '0'];
		x = x + ddx[pf_result[pf_result_index - 1] - '0'];

		/* Known wall */
		if ((cave_info[y][x] & (CAVE_MARK)) && !is_valid_pf(y, x)) {
		    p_ptr->running_withpathfind = FALSE;

		    run_init(pf_result[pf_result_index] - '0');
		}
	    }

	    if (!player_is_crossing)
		p_ptr->run_cur_dir = pf_result[pf_result_index--] - '0';
	}
    }

    /* Decrease counter */
    p_ptr->running--;

    /* Take time */
    p_ptr->energy_use = 100;

    /* Move the player */
    move_player(p_ptr->run_cur_dir);
}
Ejemplo n.º 6
0
/**
 * Take one step along the current "run" path
 *
 * Called with a real direction to begin a new run, and with zero
 * to continue a run in progress.
 */
void run_step(int dir)
{
	int x, y;

	/* Start or continue run */
	if (dir) {
		/* Initialize */
		run_init(dir);

		/* Hack -- Set the run counter */
		player->upkeep->running = 1000;

		/* Calculate torch radius */
		player->upkeep->update |= (PU_TORCH);
	} else {
		/* Continue running */
		if (!player->upkeep->running_withpathfind) {
			/* Update regular running */
			if (run_test()) {
				/* Disturb */
				disturb(player, 0);
				return;
			}
		} else {
			/* Pathfinding */
			if (pf_result_index < 0) {
				/* Abort if the path is finished */
				disturb(player, 0);
				player->upkeep->running_withpathfind = FALSE;
				return;
			} else if (pf_result_index == 0) {
				/* Abort if we would hit a wall */
				y = player->py + ddy[pf_result[pf_result_index] - '0'];
				x = player->px + ddx[pf_result[pf_result_index] - '0'];

				/* Known wall */
				if (square_ismark(cave, y, x) &&
					!square_ispassable(cave, y, x)) {
					disturb(player, 0);
					player->upkeep->running_withpathfind = FALSE;
					return;
				}
			} else if (pf_result_index > 0) {
				/* If the player has computed a path that is going to end up
				 * in a wall, we notice this and convert to a normal run. This
				 * allows us to click on unknown areas to explore the map.
				 *
				 * We have to look ahead two, otherwise we don't know which is
				 * the last direction moved and don't initialise the run
				 * properly. */
				y = player->py + ddy[pf_result[pf_result_index] - '0'];
				x = player->px + ddx[pf_result[pf_result_index] - '0'];

				/* Known wall */
				if (square_ismark(cave, y, x) &&
					!square_ispassable(cave, y, x)) {
					disturb(player, 0);
					player->upkeep->running_withpathfind = FALSE;
					return;
				}

				/* Get step after */
				y = y + ddy[pf_result[pf_result_index - 1] - '0'];
				x = x + ddx[pf_result[pf_result_index - 1] - '0'];

				/* Known wall, so run the direction we were going */
				if (square_ismark(cave, y, x) &&
					!square_ispassable(cave, y, x)) {
					player->upkeep->running_withpathfind = FALSE;
					run_init(pf_result[pf_result_index] - '0');
				}
			}

			/* Now actually run the step if we're still going */
			run_cur_dir = pf_result[pf_result_index--] - '0';
		}
	}

	/* Decrease counter if it hasn't been cancelled */
	if (player->upkeep->running)
		player->upkeep->running--;

	/* Take time */
	player->upkeep->energy_use = z_info->move_energy;

	/* Move the player */
	move_player(run_cur_dir, TRUE);

	/* Prepare the next step */
	if (player->upkeep->running) {
		cmdq_push(CMD_RUN);
		cmd_set_arg_direction(cmdq_peek(), "direction", 0);
	}
}
Ejemplo n.º 7
0
Archivo: xyzsh.c Proyecto: ab25cq/xyzsh
void xyzsh_init(enum eAppType app_type, BOOL no_runtime_script)
{
    setenv("XYZSH_VERSION", "1.5.8", 1);
    setenv("XYZSH_DOCDIR", DOCDIR, 1);
    setenv("XYZSH_DATAROOTDIR", DOCDIR, 1);
    setenv("XYZSH_EXT_PATH", EXTDIR, 1);
    setenv("XYZSH_SYSCONFDIR", SYSCONFDIR, 1);

    char* home = getenv("HOME");
    if(home) {
        char home_library[PATH_MAX];
        snprintf(home_library, PATH_MAX, "%s/.xyzsh/lib/", home);

        char* ld_library_path = getenv("LD_LIBRARY_PATH");
        if(ld_library_path) {
            char ld_library_path2[512];
            snprintf(ld_library_path2, 512, "%s:%s:%s", ld_library_path, EXTDIR, home_library);

            setenv("LD_LIBRARY_PATH", ld_library_path2, 1);
        }
        else {
            char ld_library_path2[512];
            snprintf(ld_library_path2, 512, "%s:%s", EXTDIR, home_library);

            setenv("LD_LIBRARY_PATH", ld_library_path2, 1);
        }
    }
    else {
        char* ld_library_path = getenv("LD_LIBRARY_PATH");

        if(ld_library_path) {
            char ld_library_path2[512];
            snprintf(ld_library_path2, 512, "%s:%s", ld_library_path, EXTDIR);

            setenv("LD_LIBRARY_PATH", ld_library_path2, 1);
        }
        else {
            char ld_library_path2[512];
            snprintf(ld_library_path2, 512, "%s", EXTDIR);
            setenv("LD_LIBRARY_PATH", ld_library_path2, 1);
        }
    }

    setlocale(LC_ALL, "");

    stack_init(1);;
    stack_start_stack();

    gErrMsg = STRING_NEW_STACK("");

    gXyzshSigInt = FALSE;
    gXyzshSigUser = FALSE;
    gXyzshSigTstp = FALSE;
    gXyzshSigCont = FALSE;

    xyzsh_set_signal_other = NULL;

    gc_init(1);
    run_init(app_type);
    load_init();
    xyzsh_editline_init();

    gDirStack = VECTOR_NEW_GC(10, FALSE);
    uobject_put(gXyzshObject, "_dir_stack", gDirStack);

    char* term_env = getenv("TERM");
    if(term_env != NULL && strcmp(term_env, "") != 0) {
        mcurses_init();
    }

    if(!xyzsh_rehash("init", 0)) {
        fprintf(stderr, "run time error\n");
        fprintf(stderr, "%s", string_c_str(gErrMsg));
        exit(1);
    }

    if(!no_runtime_script) {
        xyzsh_read_rc();
    }
    else {
        xyzsh_read_rc_mini();
    }
}
Ejemplo n.º 8
0
int main(int argc, char *argv[])
{
	char **cmdv, **args;
	char *cmdlines[3];
	int i;
	const char *errmsg;
	int ret = 0;
	int cmdc;
	int fd;
	struct timeval now;
	char *mount_argv[] = {"mount_part", "rootfs", "/root"};
	pid_t pid;
	int nandboot = 0;

	gettimeofday(&now, NULL);
	srand48(now.tv_usec ^ (now.tv_sec << 24));

	/* Default parameters for anything init-like we execute */
	init_argc = argc;
	init_argv = alloca((argc+1)*sizeof(char *));
	memcpy(init_argv, argv, (argc+1)*sizeof(char *));

	/*
	 * omit /dev/console when generating initramfs,
	 * so we create it dynamically
	 */
	if (access("/dev/console", O_RDWR)) {
		mknod("/dev/console", S_IFCHR|0644, makedev(5, 1));
	}

	if ((fd = open("/dev/console", O_RDWR)) != -1) {
		dup2(fd, STDIN_FILENO);
		dup2(fd, STDOUT_FILENO);
		dup2(fd, STDERR_FILENO);

		if (fd > STDERR_FILENO) {
			close(fd);
		}
	}

	mnt_procfs = mount_sys_fs("/proc/cmdline", "/proc", "proc") >= 0;
	if (!mnt_procfs) {
		ret = 1;
		goto bail;
	}

	mnt_sysfs = mount_sys_fs("/sys/bus", "/sys", "sysfs") >= 0;
	if (!mnt_sysfs) {
		ret = 1;
		goto bail;
	}

	/* Construct the effective kernel command line.  The
	   effective kernel command line consists of /arch.cmd, if
	   it exists, /proc/cmdline, plus any arguments after an --
	   argument on the proper command line, in that order. */

	ret = readfile("/arch.cmd", &cmdlines[0]);
	if (ret < 0)
		cmdlines[0] = "";

	ret = readfile("/proc/cmdline", &cmdlines[1]);
	if (ret < 0) {
		fprintf(stderr, "%s: cannot read /proc/cmdline\n", progname);
		ret = 1;
		goto bail;
	}

	cmdlines[2] = NULL;

	/* Find an -- argument, and if so append to the command line */
	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "--")) {
			i++;
			break;
		}
	}
	args = &argv[i];	/* Points either to first argument past -- or
				   to the final NULL */

	/* Count the number of arguments */
	cmdc = split_cmdline(INT_MAX, NULL, argv[0], cmdlines, args);

	/* Actually generate the cmdline array */
	cmdv = (char **)alloca((cmdc+1)*sizeof(char *));
	if (split_cmdline(cmdc, cmdv, argv[0], cmdlines, args) != cmdc) {
		ret = 1;
		goto bail;
	}

	/* Debugging... */
	dump_args(cmdc, cmdv);

	{
		const char * root_device_name = get_arg(cmdc, cmdv, "root=");
		if (strncmp(root_device_name, "/dev/mtdblock", strlen("/dev/mtdblock")) == 0) {
			nandboot = 1;
			printf("kinit: NAND mode, check online upgrade flag\n");
			do_rootfs_OU();
		} else {
			nandboot = 0;
			printf("kinit: None-NAND mode, ignore online upgrade flag\n");
		}
	}

	/* Resume from suspend-to-disk, if appropriate */
	/* If successful, does not return */
	do_resume(cmdc, cmdv);

	/* Initialize networking, if applicable */
	do_ipconfig(cmdc, cmdv);

	check_path("/root");

	if (nandboot) {
		int index = 0;
		while (1) {
			char name[128];
			snprintf(name, sizeof(name), "/sys/block/mtdblock%d", index);
			if (access(name, F_OK) == 0) {
				snprintf(name, sizeof(name), "/dev/mtdblock%d", index);
				create_dev(name, name_to_dev_t(name));
				index++;
			} else {
				break;
			}
		}
		if((pid=fork())<0)
			fprintf(stderr, "fork error.\n");
		else if(pid == 0)
		{
			if((ret = execve("/bin/mount_part", mount_argv, NULL)) <0)
				perror("excute mount_part error\n");
		}
		if(waitpid(pid, NULL, 0) < 0)
			fprintf(stderr, "wait mount_part error.\n");
	} else {
		do_mounts(cmdc, cmdv);
	}

	if (mnt_procfs) {
		umount2("/proc", 0);
		mnt_procfs = 0;
	}

	if (mnt_sysfs) {
		umount2("/sys", 0);
		mnt_sysfs = 0;
	}

	make_devices();

	init_path = find_init("/root", get_arg(cmdc, cmdv, "init="));
	if (!init_path) {
		fprintf(stderr, "%s: init not found!\n", progname);
		ret = 2;
		goto bail;
	}
	DEBUG(("kinit: init_path = %s, init=%s\n", init_path, get_arg(cmdc, cmdv, "init=")));

	init_argv[0] = strrchr(init_path, '/') + 1;

	errmsg = run_init("/root", "/dev/console", init_path, init_argv);

	/* If run_init returned, something went bad */
	fprintf(stderr, "%s: %s: %s\n", progname, errmsg, strerror(errno));
	ret = 2;
	goto bail;

bail:
	if (mnt_procfs)
		umount2("/proc", 0);

	if (mnt_sysfs)
		umount2("/sys", 0);

	/*
	 * If we get here, something bad probably happened, and the kernel
	 * will most likely panic.  Drain console output so the user can
	 * figure out what happened.
	 */
	tcdrain(2);
	tcdrain(1);

	return ret;
}
Ejemplo n.º 9
0
int
main(int argc, char *argv[])
{
  path_t  cpp_opts = { 0 };
  int     p_flags = 0;
  int     i = 1;
  unsigned char *user = 0, *group = 0, *workdir = 0;
  const struct section_global_data *global = 0;
  time_t contest_finish_time = 0;

  start_set_self_args(argc, argv);

  if (argc == 1) goto print_usage;

  while (i < argc) {
    if (!strncmp(argv[i], "-D", 2)) {
      if (cpp_opts[0]) pathcat(cpp_opts, " ");
      pathcat(cpp_opts, argv[i++]);
    } else if (!strcmp(argv[i], "-f")) {
      i++;
      forced_mode = 1;
    } else if (!strcmp(argv[i], "-i")) {
      i++;
      initialize_mode = 1;
    } else if (!strncmp(argv[i], "-S", 2)) {
      int x = 0, n = 0;

      if (sscanf(argv[i] + 2, "%d%n", &x, &n) != 1
          || argv[i][n+2] || x < 0 || x > 10000) {
        err("invalid parameter for -S");
        return 1;
      }
      i++;
      cmdline_socket_fd = x;
    } else if (!strcmp(argv[i], "-u")) {
      if (++i >= argc) goto print_usage;
      user = argv[i++];
    } else if (!strcmp(argv[i], "-g")) {
      if (++i >= argc) goto print_usage;
      group = argv[i++];
    } else if (!strcmp(argv[i], "-C")) {
      if (++i >= argc) goto print_usage;
      workdir = argv[i++];
    } else break;
  }
  if (i >= argc) goto print_usage;

  if (!initialize_mode) {
    err("this program now supports only initialize mode");
    return 1;
  }

  if (start_prepare(user, group, workdir) < 0) return 1;

#if defined EJUDGE_XML_PATH
  if (!ejudge_xml_path) ejudge_xml_path = EJUDGE_XML_PATH;
#endif /* EJUDGE_XML_PATH */
  if (!ejudge_xml_path) {
    err("configuration file is not specified");
    return 1;
  }

  config = ejudge_cfg_parse(ejudge_xml_path, 1);
  if (!config) return 1;
  if (contests_set_directory(config->contests_dir) < 0) return 1;

  // initialize the current time to avoid some asserts
  serve_state.current_time = time(0);

  if (prepare(NULL, &serve_state, argv[i], p_flags, PREPARE_SERVE, cpp_opts,
              (cmdline_socket_fd >= 0), 0, 0) < 0) return 1;
  if (prepare_serve_defaults(NULL, &serve_state, &cur_contest) < 0) return 1;

  global = serve_state.global;
  l10n_prepare(global->enable_l10n, global->l10n_dir);

  if (create_dirs(&serve_state, PREPARE_SERVE) < 0) return 1;
  serve_state.teamdb_state = teamdb_init(cur_contest->id);
  serve_state.xuser_state = team_extra_open(config, cur_contest, global, NULL, 0);
  if (!serve_state.xuser_state) {
    err("xuser plugin failed to load");
    return 1;
  }
  if (!initialize_mode) {
    if (teamdb_open_client(serve_state.teamdb_state, global->socket_path, cur_contest->id) < 0)
      return 1;
  }
  serve_state.runlog_state = run_init(serve_state.teamdb_state);
  if (global->contest_finish_time > 0) {
    contest_finish_time = global->contest_finish_time;
  }
  if (contest_finish_time > 0
      && contest_finish_time <= serve_state.current_time) {
    contest_finish_time = 0;
  }
  if (run_open(serve_state.runlog_state, config, cur_contest, global, 0, 0,
               global->contest_time, cur_contest->sched_time,
               contest_finish_time) < 0) return 1;
  if (global->is_virtual
      && global->score_system != SCORE_ACM) {
    err("invalid score system for virtual contest");
    return 1;
  }
  serve_state.clarlog_state = clar_init();
  if (clar_open(serve_state.clarlog_state,
                config, cur_contest, global, 0, 0) < 0)
    return 1;
  serve_load_status_file(&serve_state);
  serve_build_compile_dirs(&serve_state);
  serve_build_run_dirs(&serve_state, cur_contest);
  if (serve_create_symlinks(&serve_state) < 0) return 1;
  serve_state.current_time = time(0);
  serve_update_status_file(&serve_state, 1);
  if (serve_state.xuser_state) {
    serve_state.xuser_state->vt->flush(serve_state.xuser_state);
  }
  return 0;

 print_usage:
  printf("Usage: %s [ OPTS ] config-file\n", argv[0]);
  printf("  -T     - print configuration and exit\n");
  printf("  -SSOCK - set a socket fd\n");
  printf("  -DDEF  - define a symbol for preprocessor\n");
  return 0;
}
Ejemplo n.º 10
0
/** Run in interactive mode.
 *
 * Repeatedly read in statements from the user and execute them.
 */
void imode_run(void)
{
	input_t *input;
	lex_t lex;
	parse_t parse;
	stree_program_t *program;
	stree_stat_t *stat;
	stree_proc_t *proc;
	stree_fun_t *fun;
	stree_symbol_t *fun_sym;
	stype_t stype;
	stype_block_vr_t *block_vr;
	list_node_t *bvr_n;
	rdata_item_t *rexpr;
	rdata_item_t *rexpr_vi;

	run_t run;
	run_proc_ar_t *proc_ar;

	bool_t quit_im;

	/* Create an empty program. */
	program = stree_program_new();
	program->module = stree_module_new();

	/* Declare builtin symbols. */
	builtin_declare(program);

	/* Process the library. */
	if (program_lib_process(program) != EOK)
		exit(1);

	/* Resolve ancestry. */
	ancr_module_process(program, program->module);

	/* Bind internal interpreter references to symbols. */
	builtin_bind(program->builtin);

	/* Resolve ancestry. */
	ancr_module_process(program, program->module);

	/* Construct typing context. */
	stype.program = program;
	stype.proc_vr = stype_proc_vr_new();
	list_init(&stype.proc_vr->block_vr);
	stype.current_csi = NULL;
	proc = stree_proc_new();

	fun = stree_fun_new();
	fun_sym = stree_symbol_new(sc_fun);
	fun_sym->u.fun = fun;
	fun->name = stree_ident_new();
	fun->name->sid = strtab_get_sid("$imode");
	fun->sig = stree_fun_sig_new();

	stype.proc_vr->proc = proc;
	fun->symbol = fun_sym;
	proc->outer_symbol = fun_sym;

	/* Create block visit record. */
	block_vr = stype_block_vr_new();
	intmap_init(&block_vr->vdecls);

	/* Add block visit record to the stack. */
	list_append(&stype.proc_vr->block_vr, block_vr);

	/* Construct run context. */
	run_gdata_init(&run);

	run.thread_ar = run_thread_ar_new();
	list_init(&run.thread_ar->proc_ar);
	run_proc_ar_create(&run, run.gdata, proc, &proc_ar);
	list_append(&run.thread_ar->proc_ar, proc_ar);

	printf("SBI interactive mode. ");
	os_input_disp_help();

	quit_im = b_false;
	while (quit_im != b_true) {
		parse.error = b_false;
		stype.error = b_false;
		run.thread_ar->exc_payload = NULL;
		run.thread_ar->bo_mode = bm_none;

		input_new_interactive(&input);

		/* Parse input. */
		lex_init(&lex, input);
		parse_init(&parse, program, &lex);

		if (lcur_lc(&parse) == lc_eof)
			break;

		stat = parse_stat(&parse);

		if (parse.error != b_false)
			continue;

		/* Type statement. */
		stype_stat(&stype, stat, b_true);

		if (stype.error != b_false)
			continue;

		/* Run statement. */
		run_init(&run);
		run.program = program;
		run_stat(&run, stat, &rexpr);

		/* Check for unhandled exceptions. */
		run_exc_check_unhandled(&run);

		if (rexpr != NULL) {
			/* Convert expression result to value item. */
			run_cvt_value_item(&run, rexpr, &rexpr_vi);
			rdata_item_destroy(rexpr);

			/* Check for unhandled exceptions. */
			run_exc_check_unhandled(&run);
		} else {
			rexpr_vi = NULL;
		}

		/*
		 * rexpr_vi can be NULL if either repxr was null or
		 * if the conversion to value item raised an exception.
		 */
		if (rexpr_vi != NULL) {
			assert(rexpr_vi->ic == ic_value);

			/* Print result. */
			printf("Result: ");
			rdata_value_print(rexpr_vi->u.value);
			printf("\n");

			rdata_item_destroy(rexpr_vi);
		}
	}

	run_proc_ar_destroy(&run, proc_ar);

	/* Remove block visit record from the stack, */
	bvr_n = list_last(&stype.proc_vr->block_vr);
	assert(list_node_data(bvr_n, stype_block_vr_t *) == block_vr);
	list_remove(&stype.proc_vr->block_vr, bvr_n);

	printf("\nBye!\n");
}
Ejemplo n.º 11
0
/**
 * Take one step along the current "run" path
 *
 * Called with a real direction to begin a new run, and with zero
 * to continue a run in progress.
 */
void run_step(int dir)
{
	/* Start or continue run */
	if (dir) {
		/* Initialize */
		run_init(dir);

		/* Hack -- Set the run counter */
		player->upkeep->running = 1000;

		/* Calculate torch radius */
		player->upkeep->update |= (PU_TORCH);
	} else {
		/* Continue running */
		if (!player->upkeep->running_withpathfind) {
			/* Update regular running */
			if (run_test()) {
				/* Disturb */
				disturb(player, 0);
				return;
			}
		} else if (pf_result_index < 0) {
			/* Pathfinding, and the path is finished */
			disturb(player, 0);
			player->upkeep->running_withpathfind = false;
			return;
		} else {
			int y = player->py + ddy[pf_result[pf_result_index] - '0'];
			int x = player->px + ddx[pf_result[pf_result_index] - '0'];

			if (pf_result_index == 0) {
				/* Known wall */
				if (square_isknown(cave, y, x) &&
					!square_ispassable(cave, y, x)) {
					disturb(player, 0);
					player->upkeep->running_withpathfind = false;
					return;
				}
			} else if (pf_result_index > 0) {
				struct object *obj;

				/* If the player has computed a path that is going to end up
				 * in a wall, we notice this and convert to a normal run. This
				 * allows us to click on unknown areas to explore the map.
				 *
				 * We have to look ahead two, otherwise we don't know which is
				 * the last direction moved and don't initialise the run
				 * properly. */
				y = player->py + ddy[pf_result[pf_result_index] - '0'];
				x = player->px + ddx[pf_result[pf_result_index] - '0'];

				/* Known wall */
				if (square_isknown(cave, y, x) &&
					!square_ispassable(cave, y, x)) {
					disturb(player, 0);
					player->upkeep->running_withpathfind = false;
					return;
				}

				/* Visible monsters abort running */
				if (cave->squares[y][x].mon > 0) {
					struct monster *mon = square_monster(cave, y, x);

					/* Visible monster */
					if (mflag_has(mon->mflag, MFLAG_VISIBLE)) {
						disturb(player, 0);
						player->upkeep->running_withpathfind = false;
						return;
					}
				}

				/* Visible objects abort running */
				for (obj = square_object(cave, y, x); obj; obj = obj->next)
					/* Visible object */
					if (obj->known && !ignore_item_ok(obj)) {
					disturb(player, 0);
					player->upkeep->running_withpathfind = false;
					return;
				}

				/* Get step after */
				y = y + ddy[pf_result[pf_result_index - 1] - '0'];
				x = x + ddx[pf_result[pf_result_index - 1] - '0'];

				/* Known wall, so run the direction we were going */
				if (square_isknown(cave, y, x) &&
					!square_ispassable(cave, y, x)) {
					player->upkeep->running_withpathfind = false;
					run_init(pf_result[pf_result_index] - '0');
				}
			}

			/* Now actually run the step if we're still going */
			run_cur_dir = pf_result[pf_result_index--] - '0';
		}
	}

	/* Decrease counter if it hasn't been cancelled */
	if (player->upkeep->running)
		player->upkeep->running--;
	else if (!player->upkeep->running_withpathfind)
		return;

	/* Take time */
	player->upkeep->energy_use = z_info->move_energy;

	/* Move the player; running straight into a trap == trying to disarm */
	move_player(run_cur_dir, dir ? true : false);

	/* Prepare the next step */
	if (player->upkeep->running) {
		cmdq_push(CMD_RUN);
		cmd_set_arg_direction(cmdq_peek(), "direction", 0);
	}
}
Ejemplo n.º 12
0
/** Main entry point.
 *
 * @return	Zero on success, non-zero on error.
 */
int main(int argc, char *argv[])
{
	stree_program_t *program;
	stype_t stype;
	run_t run;
	int rc;

	/* Store executable file path under which we have been invoked. */
	os_store_ef_path(*argv);

	argv += 1;
	argc -= 1;

	if (argc == 0) {
		/* Enter interactive mode */
		strtab_init();
		imode_run();
		return 0;
	}

	if (os_str_cmp(*argv, "-h") == 0) {
		syntax_print();
		return 0;
	}

	strtab_init();
	program = stree_program_new();
	program->module = stree_module_new();

	/* Declare builtin symbols. */
	builtin_declare(program);

	/* Process source files in the library. */
	if (program_lib_process(program) != EOK)
		return 1;

	/* Resolve ancestry. */
	ancr_module_process(program, program->module);

	/* Bind internal interpreter references to symbols. */
	builtin_bind(program->builtin);

	/* Process all source files specified in command-line arguments. */
	while (argc > 0) {
		rc = program_file_process(program, *argv);
		if (rc != EOK)
			return 1;

		argv += 1;
		argc -= 1;
	}

	/* Resolve ancestry. */
	ancr_module_process(program, program->module);

	/* Type program. */
	stype.program = program;
	stype.error = b_false;
	stype_module(&stype, program->module);

	/* Check for typing errors. */
	if (stype.error)
		return 1;

	/* Run program. */
	run_init(&run);
	run_program(&run, program);

	/* Check for run-time errors. */
	if (run.thread_ar->error)
		return 1;

	return 0;
}
Ejemplo n.º 13
0
int main(int argc, char *argv[])
{
int callrun;

#ifdef MTRACE_DEBUG
mtrace();
#endif
   /* Start initialisation:*/
   /* Pick out the number from the string "$Revision: 2.37 $":*/
   {/*Block begin*/
        char *tmp=currentrevision;
        for( tmp=currentrevision;(*tmp!=' ')&&(*tmp!='\0');tmp++);
        if(*tmp == ' ') tmp++;
        for( currentRevisionNumber=tmp;(*tmp!=' ')&&(*tmp!='\0');tmp++);
        *tmp='\0';
   }/*Block end*/

   /* Check here is there the request for the version information.
    * If so, output the revision number and quit, if there are no any
    * other option:
    */
   for(i=1; i<argc; i++)
      if( (s_cmp(argv[i],"-V")==0)||(s_cmp(argv[i],"-version")==0)){
        printf("%s\n",currentRevisionNumber);
        if(argc == 2) exit(0);
      }

   first_init();/*module init.c*/
   read_command_line(argc, argv);/*module cmd_line.c*/
   message(INITIALIZATION,NULL);
   /*End initialisation*/
   message(READINGCONFIG,config_name);
   scaner_init(config_name,cnf_comment);/*module init.c*/
   read_config_file_before_truns();/*module cnf_read.c*/
   if( is_bit_set(&mode,bitCHECKMOMENTABALANCE)&&
       (!is_bit_set(&mode,bitONLYINTERPRET))
    ){

       check_momenta_balance_on_each_topology();
   }
   message(DONE,NULL);

   /*Translation of the TM program:*/
   {char tmp[MAX_STR_LEN];

       if (
             (is_bit_set(&mode,bitONLYINTERPRET))||
             (!is_bit_set(&mode,bitBROWS))||
             (is_bit_set(&mode,bitVERIFY))||
             (is_bit_set(&mode,bitFORCEDTRUNSLATION))
          ){
             command_init();/*module truns.c*/
             if(!is_bit_set(&mode,bitONLYINTERPRET)){
                if (set_table==NULL)set_table=create_hash_table(
                      set_hash_size,str_hash,str_cmp,c_destructor);
                if(is_bit_set(&mode,bitBROWS))
                  install(new_str("_specmode"),new_str("browser"),set_table);
                else
                  install(new_str("_specmode"),new_str("common"),set_table);
             }
             message(BEGINTRUNS,NULL);
             do{
               if(truns(&current_number_of_trunslated_lines,
                           &current_array_of_trunslated_lines)){
                  number_of_trunslated_lines=
                                        current_number_of_trunslated_lines;
                  current_number_of_trunslated_lines=0;
                  array_of_trunslated_lines=
                                         current_array_of_trunslated_lines;
                  current_array_of_trunslated_lines=NULL;
               }
             }while(number_of_trunslated_lines==0);
             message(ENDTRUNS,NULL);
             mem_esc_char=esc_char;
             macro_done();/*module macro.c*/
             reject_proc();/*module truns.c*/
             command_done();/*module truns.c*/
             clear_defs();/*module truns.c*/
             clear_label_stack();/*module truns.c*/
             for_done();/*module truns.c*/
             IF_done();/*module truns.c*/
             if(s_scmp(sc_get_token(tmp),"translate"))
                halt(UNEXPECTED ,tmp);
       }
   }
   sc_done();/*module tools.c*/
   /*TM program is translated. The resulting code is in array_of_trunslated_lines*/

/*Keep the table up to the end of the program!:*/
#ifdef SKIP
   if (vectors_table!=NULL){
      hash_table_done(vectors_table);/*module hash.c*/
      vectors_table=NULL;
   }
#endif

   message(DONEINIT,NULL);

   if (is_bit_set(&mode,bitVERIFY)){
     message(ONLYVERIFY,NULL);
     errorlevel=0;halt(NOERROR,NULL);
   }

   if (g_ttnames != NULL){/*Topology tables were defined in the config file*/
      HASH_TABLE wrktrans;
      message(LOADINGTABLES,NULL);
      read_topology_tables();/*module utils.c*/
      free_mem(&g_ttnames);
      /*Create the working table:*/
      g_tt_wrk=tt_createNewTable(g_defaultTokenDictSize,g_defaultHashTableSize);

      /*Check success, if not, halt the system:*/
      checkTT(g_tt_wrk,FAILCREATINGWRKTABLE);

      /*Collect translations from all tables:*/
      wrktrans=tt_table[g_tt_wrk-1]->htrans;
      /*Full toplogies:*/
      for(i=0;i<g_tt_top_full;i++){
         HASH_TABLE  ttrans=tt_table[g_tt_full[i]-1]->htrans;
         if( ttrans!=NULL )
              binary_operations_under_hash_table(
                 ttrans,/*"from"*/
                 wrktrans,/*"to"*/
                 -1);/*see "hash.c"; op>0 -> add enties to "to" from "from", only if they
                 are absent in "to", op<0 -> rewrite entries in "to" by the corresponding
                 "from", op==0 -> remove all entries in "to" matching "from"*/
      }/*for(i=0;i<g_tt_top_full;i++)*/
      /*Internal topologies:*/
      for(i=0;i<g_tt_top_int;i++){
         HASH_TABLE  ttrans=tt_table[g_tt_int[i]-1]->htrans;
         if( ttrans!=NULL )
              binary_operations_under_hash_table(
                 ttrans,/*"from"*/
                 wrktrans,/*"to"*/
                 -1);/*see "hash.c"; op>0 -> add enties to "to" from "from", only if they
                 are absent in "to", op<0 -> rewrite entries in "to" by the corresponding
                 "from", op==0 -> remove all entries in "to" matching "from"*/
      }/*for(i=0;i<g_tt_top_int;i++)*/

      /*Override translations, if present, in wrk table; in loaded tables
        translations remain to be untranslated!:*/
      if( g_ttTokens_table!=NULL )
              binary_operations_under_hash_table(
                 g_ttTokens_table,/*"from"*/
                 wrktrans,/*"to"*/
                 -1);/*see "hash.c"; op>0 -> add enties to "to" from "from", only if they
                 are absent in "to", op<0 -> rewrite entries in "to" by the corresponding
                 "from", op==0 -> remove all entries in "to" matching "from"*/

      /*Now wrk table is ready*/
      /*Override translations, if present, in full toplogies:*/
      if( g_ttTokens_table!=NULL )for(i=0;i<g_tt_top_full;i++){
         HASH_TABLE  ttrans=tt_table[g_tt_full[i]-1]->htrans;
         if( ttrans!=NULL )/*BTW, it CANNOT be a NULL! See, how tt_createNewTableis invoked
                             in the beginning of tt_loadTable, file tt_load.c*/
              binary_operations_under_hash_table(
                 g_ttTokens_table,/*"from"*/
                 ttrans,/*"to"*/
                 -1);/*see "hash.c"; op>0 -> add enties to "to" from "from", only if they
                 are absent in "to", op<0 -> rewrite entries in "to" by the corresponding
                 "from", op==0 -> remove all entries in "to" matching "from"*/
      }/*for(i=0;i<g_tt_top_full;i++)*/
      message(DONE,NULL);
   }/*if (g_ttnames != NULL)*/

   /*If only interpret, we need not analyse diagrams:*/
   if(is_bit_set(&mode,bitONLYINTERPRET)){
    int exitcode;
      run_init(1);/*module init.c*/
      esc_char=mem_esc_char;
      islast=1;
      g_nocurrenttopology=1;/*Similar to islast, but specially for topologies.*/
      message(CALLTOINTERPRETER,NULL);
      exitcode=run(number_of_trunslated_lines,array_of_trunslated_lines);
      message(DONE,NULL);
      {char endmessage[MAX_STR_LEN];
         sprintf(endmessage,EXITCODEFROMINTERPRETER,exitcode);
         errorlevel=exitcode;
         halt(endmessage,NULL);
      }
      /*Stop running...*/
   }/*if(is_bit_set(&mode,bitONLYINTERPRET)*/

   /*ok, if we are here then we have to read diagrams...*/
   detect_last_diagram_number();/*module last_num.c*/
   message(LOOKINGFORFIRRSTDIAGRAM,NULL);
   scaner_init(input_name,0);/*module init.c*/
   skip_until_first_actual_diagram();/*module read_inp.c*/
   create_table(&dbuf,&dtable,MAX_VERTEX,MAX_I_LINE,ext_lines);/*module utils.c*/
   create_table(&wrkbuf,&wrktable,MAX_VERTEX,MAX_I_LINE,ext_lines);
   message(DONE,NULL);
   message(READDIAGRAMS,NULL);

   for(i=start_diagram;!(i>finish_diagram);i++){/*begin main loop*/
      skip_to_new_diagram();/* module read_inp.c Reads until '['*/

      if(i % STEP_INDICATOR == 0){
        char mes[MAX_STR_LEN];
          sprintf(mes,INDICATE_MESSAGE,i,finish_diagram);
          message(mes,NULL);
      }/*if(i % STEP_INDICATOR == 0)*/

      /* Check should we process this diagram:*/
      if (set_in(i % 250,dmask[i / 250])) continue;

      new_diagram();/*module read_inp.c. Some initializations
                                                       before each diagram.*/

      detect_number_and_coefficient();/*module read_inp.c
                                        This function must receive from
                                        scaner exactly 'd###'*/
      if(i!=diagram_count)
         halt(CURRUPTEDINPUT,input_name);
      create_primary_diagram_table();/*module read_inp.c*/

      if ( skiptadpoles && thisistadpole )
         continue;
      define_topology();/*module read_inp.c*/
      /*compare_topology() returns 1 if topology is not actual.
      If topology is undefined, this procedure will call
      'out_undefined_topology();' (if bitBROWS is not set) and set bitTERROR.
      */
      if(compare_topology())/*module read_inp.c*/
         continue;

      create_diagram_table();/*module read_inp.c*/

      define_prototype();/*module read_inp.c*/
      if(!is_bit_set(&mode,bitFORCEDTRUNSLATION))
          if(skip_prototype())/*module utils.c*/
            continue;
      create_indices_table();/*module read_inp.c*/
      if(must_diagram_be_skipped())/*module utils.c*/
         continue;
      if (is_bit_set(&mode,bitBROWS))
         fill_up_diagram_array(count);/*module read_inp.c*/
      count++;
      if(is_bit_set(&mode,bitFORCEDTRUNSLATION)){
         if(g_tt_try_loaded>0)/*Automatic momenta distribution mechanism*/
            callrun=1;
         else if(   ( is_bit_set(&mode,bitTERROR) )&&(!is_bit_set(&mode,bitBROWS)))
           callrun=0;
         else
           callrun=1;
      }else{
         callrun=(
              (!is_bit_set(&mode,bitTERROR) )&&
              (!is_bit_set(&mode,bitBROWS) )
         );
      }
      /*Run the interpreter:*/
      if(callrun){
         build_form_input();/*module read_inp.c*/
         run_init(0);/*module init.c*/
         esc_char=mem_esc_char;
         if(run(number_of_trunslated_lines,array_of_trunslated_lines)==HALT)
             set_bit(&mode,bitRUNSIGNAL);
         run_clear();/*module init.c*/
         if(is_bit_set(&mode, bitSKIP)){
            unset_bit(&mode,bitSKIP);
            count--;
         }else if((is_bit_set(&mode,bitFORCEDTRUNSLATION))&&
                            (skip_prototype()/*module utils.c*/)){
            count--;
         }else{
            if(g_topologyLabel!=NULL){/*First occurence, otherwise will be NULL*/
               /*Mark topology as occurred*/
               set_bit(g_topologyLabel,0);
               if(g_tt_try_loaded>0){/*Table were loaded*/

                  if( topologies[cn_topol].orig==NULL )/*Undefined topology*/
                     process_topol_tables(0);/*try to find momenta, read_inp.c*/

                  if(topologies[cn_topol].coordinates_ok==0)/*No coords*/
                     process_topol_tables(1);/*try to find coordinates, read_inp.c*/
                  /*Now current topology is marked, and wrk toable is built.*/
               }else{
                  if( topologies[cn_topol].orig==NULL ){/*Undefined topology*/
                     if( automatic_momenta_group(NULL,cn_topol)==1)
                        /*Now momenta are distributed automatically:*/
                        set_bit(g_topologyLabel,2);
                        /*Bit 0: 0, if topology not occures, or 1;
                          bit 1: 1, if topology was produced form generic, or 0.
                          bit 2: 1, automatic momenta is implemented, or 0
                        */
                  }/*if( topologies[cn_topol].orig==NULL )*/
               }/*if(g_tt_try_loaded>0)...else...*/
            }/*if(g_topologyLabel!=NULL)*/
            output_common_protocol(count);/*module read_inp.c*/
         }/*if(is_bit_set(&mode, bitSKIP)) ... else ... else*/
         if(is_bit_set(&mode,bitRUNSIGNAL)){
            sc_done();
            errorlevel=0;
            halt(RUNSIGNAL,NULL);
         }/*if(is_bit_set(&mode,bitRUNSIGNAL))*/
      }/*if(callrun)*/
   }/*end main loop*/

   sc_done();
   message(DONEDIAGRAMS,NULL);

   /*Check should we run the interpreter once more:*/
   if(is_bit_set(&mode,bitEND)){
      /*To use some of specmode operators during "extra call":*/
      new_diagram();

      run_init(1);
      esc_char=mem_esc_char;
      islast=1;

      g_nocurrenttopology=1;/*Similar to islast, but specially for topologies.*/
      cn_topol=top_topol;/*Indicate that there is no special topology */
      message(EXTRACALL,NULL);
      if(run(number_of_trunslated_lines,array_of_trunslated_lines)==HALT){
         errorlevel=0;
         halt(RUNSIGNAL,NULL);
      }
      message(DONE,NULL);
   }/*if(is_bit_set(&mode,bitEND))*/

   if (is_bit_set(&mode,bitBROWS)){
      message(BROWSERMODEDETECT,NULL);
      out_browse_head(count);/*module browser.c*/
      message(SORTINGDIAGRAMS,NULL);
      sort_diargams(count);/*module browser.c*/
      message(DONE,NULL);
      message(PRINTINGDIAGRAMS,NULL);
      print_diagrams(count);/*module browser.c*/
      message(DONE,NULL);
      sort_prototypes();/*module browser.c*/
      print_prototypes();/*module browser.c*/
      print_all_found_topologies();/*module browser.c*/
      print_not_found_topologies();/*module browser.c*/
      print_undefined_topologies();/*module browser.c*/
   }/*if (is_bit_set(&mode,bitBROWS))*/
   errorlevel=0;
   halt(NOERROR,NULL);
   return(0);/*Actually, the control can't reach this point*/
}/*main*/