Example #1
0
int32 interpreter::load_card_script(uint32 code) {
	char class_name[20];
	char script_name[64];
	sprintf(class_name, "c%d", code);
	lua_getglobal(current_state, class_name);
	//if script is not loaded, create and load it
	if (lua_isnil(current_state, -1)) {
		lua_pop(current_state, 1);
		//create a table & set metatable
		lua_createtable(current_state, 0, 0);
		lua_setglobal(current_state, class_name);
		lua_getglobal(current_state, class_name);
		lua_getglobal(current_state, "Card");
		lua_setmetatable(current_state, -2);
		lua_pushstring(current_state, "__index");
		lua_pushvalue(current_state, -2);
		lua_rawset(current_state, -3);
		//load special and extra scripts first
		sprintf(script_name, "./specials/c%d.lua", code);
		if (!load_script(script_name)) {
			sprintf(script_name, "./expansions/script/c%d.lua", code);
			if (!load_script(script_name)) {
				sprintf(script_name, "./script/c%d.lua", code);
				if (!load_script(script_name)) {
					return OPERATION_FAIL;
				}
			}
		}
	}
	return OPERATION_SUCCESS;
}
Example #2
0
/* attempts to open a file, tokenize and then process it as a haserl script */
int
h_lua_loadfile (lua_State * L)
{
  script_t *scriptchain;
  token_t *tokenchain;
  buffer_t script_text;
  int status;

  /* get the filename */
  const char *filename = luaL_checkstring (L, 1);


  scriptchain = load_script ((char *) filename, NULL);
  tokenchain = build_token_list (scriptchain, NULL);
  preprocess_token_list (tokenchain);
  process_token_list (&script_text, tokenchain);
  free_token_list (tokenchain);
  free_script_list (scriptchain);

  /* script_text has the include file */
  status = luaL_loadbuffer (L, (char *) script_text.data,
			    script_text.ptr - script_text.data, filename);
  buffer_destroy (&script_text);
  if (status)
    {
      lua_error (L);
    }
  return (1);			/* we return one value, the buffer, as a function */
}
Example #3
0
File: lua.c Project: Cynede/hexchat
static void check_deferred(script_info *info)
{
	info->status &= ~STATUS_ACTIVE;
	if(info->status & STATUS_DEFERRED_UNLOAD)
	{
		run_unload_hooks(info, NULL);
		g_ptr_array_remove_fast(scripts, info);
	}
	else if(info->status & STATUS_DEFERRED_RELOAD)
	{
		if(info == interp)
		{
			run_unload_hooks(interp, NULL);
			destroy_interpreter();
			create_interpreter();
		}
		else
		{
			char *filename = g_strdup(info->filename);
			run_unload_hooks(info, NULL);
			g_ptr_array_remove_fast(scripts, info);
			load_script(filename);
			g_free(filename);
		}
	}
}
Example #4
0
static void load_list_of_scripts(WnckScreen *screen, WnckWindow *window,
											GSList *file_list)
{
	GSList *temp_file_list = file_list;
	// set the window to work on
	set_current_window(window);

	// for every file in the folder - load the script
	if (file_window_open_list != NULL) {

		while(temp_file_list) {
			gchar *filename = (gchar*)temp_file_list->data;

			// is it a LUA file?
			if (g_str_has_suffix((gchar*)filename,".lua")) {

				// init the script, run it
				if (!load_script(global_lua_state, filename)) {
				}

				run_script(global_lua_state);

			}
			temp_file_list=temp_file_list->next;
		}
	}
	return;

}
Example #5
0
bool am_run_script(lua_State *L, const char *script, int len, const char *name) {
    if (load_script(L, script, len, name)) {
        lua_newtable(L); // module table - discarded afterwards.
        return am_call(L, 1, 0);
    } else {
        return false;
    }
}
Example #6
0
/* reload the scrip on rehash */
void rehash_myruby(int check)
{
  if (check) {
    check_script(gdata.ruby_script);
    return;
  }
  load_script(gdata.ruby_script);
}
Example #7
0
File: exec.c Project: jmgc/noah
int
do_exec(const char *elf_path, int argc, char *argv[], char **envp)
{
  int err;
  int fd;
  struct stat st;
  char *data;
  
  if ((err = do_access(elf_path, X_OK)) < 0) {
    return err;
  }
  if ((fd = vkern_open(elf_path, LINUX_O_RDONLY, 0)) < 0) {
    return fd;
  }
  if (proc.nr_tasks > 1) {
    warnk("Multi-thread execve is not implemented yet\n");
    return -LINUX_EINVAL;
  }

  /* Now do exec */
  fstat(fd, &st);
  if (!S_ISREG(st.st_mode)) {
    vkern_close(fd);
    return -LINUX_EACCES;
  }

  prepare_newproc();

  data = mmap(0, st.st_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);

  vkern_close(fd);

  drop_privilege();

  if (4 <= st.st_size && memcmp(data, ELFMAG, 4) == 0) {
    if ((err = load_elf((Elf64_Ehdr *) data, argc, argv, envp)) < 0)
      return err;
    if (st.st_mode & 04000) {
      elevate_privilege();
    }
  }
  else if (2 <= st.st_size && data[0] == '#' && data[1] == '!') {
    if ((err = load_script(data, st.st_size, elf_path, argc, argv, envp)) < 0)
      return err;
  }
  /*else if (4 <= st.st_size && memcmp(data, "\xcf\xfa\xed\xfe", 4) == 0) {
    // Mach-O
    return syswrap(execve(elf_path, argv, envp));
  }*/
  else {
    return -LINUX_ENOEXEC;                  /* unsupported file type */
  }

  munmap(data, st.st_size);
  proc.mm->current_brk = proc.mm->start_brk;

  return 0;
}
Example #8
0
File: lua.c Project: Cynede/hexchat
static int command_load(char *word[], char *word_eol[], void *userdata)
{
	if(is_lua_file(word[2]))
	{
		load_script(word[2]);
		return HEXCHAT_EAT_ALL;
	}
	else
		return HEXCHAT_EAT_NONE;
}
Example #9
0
void module_always_has_primary_output()
{
    test_write_fake_file("module.ca", 1, "1");

    Block block;
    load_script(&block, "module.ca");

    test_assert(get_output_placeholder(&block, 0) != NULL);
    test_assert(get_output_placeholder(&block, 0)->input(0) == NULL);
}
interpreter::interpreter(duel* pd): coroutines(256) {
	lua_state = luaL_newstate();
	current_state = lua_state;
	pduel = pd;
	no_action = 0;
	call_depth = 0;
	set_duel_info(lua_state, pd);
	//Initial
	luaL_openlibs(lua_state);
	lua_pushnil(lua_state);
	lua_setglobal(lua_state, "file");
	lua_pushnil(lua_state);
	lua_setglobal(lua_state, "io");
	lua_pushnil(lua_state);
	lua_setglobal(lua_state, "os");
	lua_getglobal(lua_state, "bit32");
	lua_setglobal(lua_state, "bit");
	//open all libs
	luaL_newlib(lua_state, cardlib);
	lua_pushstring(lua_state, "__index");
	lua_pushvalue(lua_state, -2);
	lua_rawset(lua_state, -3);
	lua_setglobal(lua_state, "Card");
	luaL_newlib(lua_state, effectlib);
	lua_pushstring(lua_state, "__index");
	lua_pushvalue(lua_state, -2);
	lua_rawset(lua_state, -3);
	lua_setglobal(lua_state, "Effect");
	luaL_newlib(lua_state, grouplib);
	lua_pushstring(lua_state, "__index");
	lua_pushvalue(lua_state, -2);
	lua_rawset(lua_state, -3);
	lua_setglobal(lua_state, "Group");
	luaL_newlib(lua_state, duellib);
	lua_setglobal(lua_state, "Duel");
	luaL_newlib(lua_state, debuglib);
	lua_setglobal(lua_state, "Debug");
	//extra scripts
	load_script((char*) "./scripts/constant.lua");
	load_script((char*) "./scripts/utility.lua");
	load_script((char*) "./scripts/ai.lua");
}
Example #11
0
static void load(Block* block, std::string const& filename)
{
    if (filename == "") {
        clear_block(block);
        return;
    }

    load_script(block, filename.c_str());
    if (has_static_errors(block))
        print_static_errors_formatted(block, std::cout);
}
Example #12
0
static void load(Branch* branch, std::string const& filename)
{
    if (filename == "") {
        clear_branch(branch);
        return;
    }

    load_script(branch, filename.c_str());
    if (has_static_errors(branch))
        print_static_errors_formatted(branch, std::cout);
}
Example #13
0
void ProjectInfo(void)
{
  char fn[FNLEN]; 

  /* Try theme script first: */
  if (!settings.use_english)
    sprintf( fn, "%s/scripts/projectInfo.xml", settings.theme_data_path);

  if (load_script( fn ) == 0) /* meaning successful load */
  {
    run_script();
    return;
  }

  /* If unsuccessful, fall back to default (English) script: */
  sprintf( fn, "%s/scripts/projectInfo.xml", settings.default_data_path);
  if (load_script( fn ) != 0)
    return; // bail if any errors occur

  run_script();
}
Example #14
0
int main(int argc, char *argv[])
{
    signed int entrypoint;

    if (argc < 2) {
        printf("Usage: %s <script name>\n", argv[0]);
        exit(-1);
    }

    tape_init();
    entrypoint = load_script(argv[1]);
    interpret(entrypoint);

    return 0;
}
Example #15
0
File: lua.c Project: Cynede/hexchat
static void autoload_scripts(void)
{
	char *path = g_build_filename(hexchat_get_info(ph, "configdir"), "addons", NULL);
	GDir *dir = g_dir_open(path, 0, NULL);
	if(dir)
	{
		char const *filename;
		while((filename = g_dir_read_name(dir)))
		{
			if(is_lua_file(filename))
				load_script(filename);
		}
		g_dir_close(dir);
	}
	g_free(path);
}
Example #16
0
void winbox::on_timer()
{
	m_frame++;
	time_t filetime = get_file_time(g_entry);
	if (filetime != m_entry_time)
	{
		m_entry_time = filetime;
		load_script();
	}

	InvalidateRect(m_hwnd, nullptr, false);

	std::string err;
	lua_guard g(m_lvm);
	lua_call_object_function(err, m_lvm, this, "on_timer");
	log_err(err.c_str());
}
Example #17
0
void run_generate_cpp(caValue* args)
{
    if (list_length(args) < 2) {
        std::cout << "Expected 2 arguments";
        return;
    }

    const char* source_file = as_cstring(list_get(args, 0));
    const char* output_file = as_cstring(list_get(args, 1));

    std::cout << "Loading source from: " << source_file << std::endl;
    std::cout << "Will write to: " << output_file << std::endl;

    Block block;
    load_script(&block, source_file);
    write_program_to_file(&block, output_file);
}
bool system_desktop_application_execute_init(const char* app_root_path,const char* app_name) {
    char app_init_code_file[FILE_NAME_LENGTH]={0};
    FIL* app_init_code_file_=NULL;

    memcpy(app_init_code_file,app_root_path,APP_PATH_LENGTH);
    strcat(app_init_code_file,"/");
    strcat(app_init_code_file,app_name);
    strcat(app_init_code_file,"/");
    strcat(app_init_code_file,APP_MAIN_CODE_EXTENSION);
    if (file_open(app_init_code_file,app_init_code_file_)) {
        if (MAX_CODE_LENGTH>=file_length(app_init_code_file_)) {
            file_close(app_init_code_file_);
            return load_script(app_init_code_file);
        }
        file_close(app_init_code_file_);
    }
    return false;
}
Example #19
0
void winbox::on_create(HWND hwnd)
{
	RECT rect;

	m_hwnd = hwnd;
	GetClientRect(m_hwnd, &rect);
	m_width = (float)rect.right;
	m_height =(float)rect.bottom;

	float x = (float)(rect.right / 4), y = (float)(rect.bottom / 4);
	float w = (float)(rect.right / 2), h = (float)(rect.bottom / 2);
	m_log_box = Gdiplus::RectF(x, y, w, h);

	luaL_openlibs(m_lvm);
	lua_push_object(m_lvm, this);
	lua_setglobal(m_lvm, "window");
	load_script();
}
Example #20
0
int main ()
{
  printf ("Results of mathlib_performance test:\n");
  
  try
  {
    Environment env;
    
    Shell shell ("lua", env);

    xtl::com_ptr<IInterpreter> script (shell.Interpreter ());            

    env.Library ("global").Register ("typename", make_invoker (&get_typename));
  
    env.BindLibraries ("Math");
    load_script       (*script, SCRIPT_FILE_NAME);

    printf ("Test c++ performance:\n");
    
    size_t start_time = common::milliseconds ();

    float test_result = test ();
    
    printf ("Duration = %u ms, result = %f\n", common::milliseconds () - start_time, test_result);
    
    printf ("Test lua performance:\n");

    start_time = common::milliseconds ();
    
    test_result = invoke<float> (*script, "test");
    
    printf ("Duration = %u ms, result = %f\n", common::milliseconds () - start_time, test_result);
  }
  catch (xtl::bad_any_cast& exception)
  {
    printf ("%s: %s -> %s\n", exception.what (), exception.source_type ().name (), exception.target_type ().name ());
  }    
  catch (std::exception& exception)
  {
    printf ("exception: %s\n", exception.what ());
  }

  return 0;
}
Example #21
0
void lua_scripts::load_all_scripts_in_dir(lua_State *L, const char *dirname) {
    if (dirname == nullptr) {
        return;
    }

    DIR *d = opendir(dirname);
    if (d == nullptr) {
        gcs().send_text(MAV_SEVERITY_INFO, "Lua: Could not find a scripts directory");
        return;
    }

    // load anything that ends in .lua
    for (struct dirent *de=readdir(d); de; de=readdir(d)) {
        uint8_t length = strlen(de->d_name);
        if (length < 5) {
            // not long enough
            continue;
        }

        if (strncmp(&de->d_name[length-4], ".lua", 4)) {
            // doesn't end in .lua
            continue;
        }

        // FIXME: because chunk name fetching is not working we are allocating and storing an extra string we shouldn't need to
        size_t size = strlen(dirname) + strlen(de->d_name) + 2;
        char * filename = (char *) hal.util->heap_realloc(_heap, nullptr, size);
        if (filename == nullptr) {
            continue;
        }
        snprintf(filename, size, "%s/%s", dirname, de->d_name);

        // we have something that looks like a lua file, attempt to load it
        script_info * script = load_script(L, filename);
        if (script == nullptr) {
            hal.util->heap_realloc(_heap, filename, 0);
            continue;
        }
        reschedule_script(script);

    }
    closedir(d);
}
Example #22
0
static void check_script(const char *name)
{
  struct stat st;

  updatecontext();

  if (!name)
    return;

  if (stat(name, &st) < 0) {
    myruby_loaded = -1;
    outerror(OUTERROR_TYPE_WARN_LOUD,
             "cannot access '%s', ignoring: %s",
             name, strerror(errno));
    return;
  }
  if (myruby_time == st.st_mtime)
    return;

  load_script(name);
}
Example #23
0
File: lua.c Project: Cynede/hexchat
static int reload_script(char const *filename)
{
	script_info *script = get_script_by_file(filename);

	if (!script)
		return 0;

	if(script->status & STATUS_ACTIVE)
	{
		script->status |= STATUS_DEFERRED_RELOAD;
	}
	else
	{
		char *filename = g_strdup(script->filename);
		run_unload_hooks(script, NULL);
		g_ptr_array_remove_fast(scripts, script);
		load_script(filename);
		g_free(filename);
	}

	return 1;
}
Example #24
0
int main(int argc, char *argv[])
{
    // start Lua
    L = luaL_newstate();
    luaL_openlibs(L);
    // load Lua data
    if(!load_script("luac.out"))
    {
        printf("load failed!\n");
        lua_error(L);
    }
    // C++ object
    NPC * king = new NPC();

    // Lua object
    lua_getglobal(L, "king");
    if(lua_istable(L, -1))
    {
        lua_getfield(L, -1, "get_name");
        if(lua_isfunction(L, -1))
        {
            lua_pushvalue(L, -2); // push 'king' as first arg in 'get_name()'
            lua_call(L, 1, 1); // one arg(king) and one return
            // store king:get_name() in king->name
            king->set_name(lua_tostring(L, -1));
            std::cout << king->get_name() << "\n";
        }
        else
            std::cout << "(ERROR): not a valid function\n";
    }
    else
        std::cout << "not a valid table.\n";

    // close Lua
    lua_close(L);
    system("pause");
    return 0;
}
Example #25
0
/******************************************************************
 *      InternetInitializeAutoProxyDll (jsproxy.@)
 */
BOOL WINAPI JSPROXY_InternetInitializeAutoProxyDll( DWORD version, LPSTR tmpfile, LPSTR mime,
                                                    AutoProxyHelperFunctions *callbacks,
                                                    LPAUTO_PROXY_SCRIPT_BUFFER buffer )
{
    BOOL ret = FALSE;

    TRACE( "%u, %s, %s, %p, %p\n", version, debugstr_a(tmpfile), debugstr_a(mime), callbacks, buffer );

    if (callbacks) FIXME( "callbacks not supported\n" );

    EnterCriticalSection( &cs_jsproxy );

    if (buffer && buffer->dwStructSize == sizeof(*buffer) && buffer->lpszScriptBuffer)
    {
        DWORD i, len = 0;
        for (i = 0; i < buffer->dwScriptBufferSize; i++)
        {
            if (!buffer->lpszScriptBuffer[i]) break;
            len++;
        }
        if (len == buffer->dwScriptBufferSize)
        {
            SetLastError( ERROR_INVALID_PARAMETER );
            LeaveCriticalSection( &cs_jsproxy );
            return FALSE;
        }
        heap_free( global_script->text );
        if ((global_script->text = strdupAW( buffer->lpszScriptBuffer, len ))) ret = TRUE;
    }
    else
    {
        heap_free( global_script->text );
        if ((global_script->text = load_script( tmpfile ))) ret = TRUE;
    }

    LeaveCriticalSection( &cs_jsproxy );
    return ret;
}
Example #26
0
int main ()
{
  printf ("Results of common_string_tree_test:\n");
  
  try
  {
    common::LogFilter filter ("script.binds.*", &log_handler);

    Environment env;
    
    InvokerRegistry lib = env.CreateLibrary ("Utils");

    lib.Register ("PrintIndent", make_invoker (&print_indent));

    Shell shell ("lua", env);

    xtl::com_ptr<IInterpreter> script (shell.Interpreter ());                

    env.BindLibraries ("Common");

    load_script (*script, SCRIPT_FILE_NAME);
    
    printf ("Test library:\n");

    invoke<void> (*script, "test");
  }
  catch (xtl::bad_any_cast& exception)
  {
    printf ("%s: %s -> %s\n", exception.what (), exception.source_type ().name (), exception.target_type ().name ());
  }    
  catch (std::exception& exception)
  {
    printf ("exception: %s\n", exception.what ());
  }

  return 0;
}
Example #27
0
/* load the interpreter and the script */
void startup_myruby(void)
{
  int rc;

  RUBY_INIT_STACK;
  ruby_init();
  ruby_init_loadpath();
  /* dumps the version info to stdout */
  ruby_show_version();
  /* set working dir for includes */
  rb_eval_string_protect("$: << '.'", &rc); /* NOTRANSLATE */
#if USE_RUBYVERSION < 19
#else
  rb_enc_find_index("encdb"); /* NOTRANSLATE */
#endif

  myruby_loaded = 0;

  //define that callback below
  rb_define_global_function("iroffer_input", cie_inputline, 0); /* NOTRANSLATE */
  rb_define_global_function("iroffer_privmsg", cie_privmsg, 2); /* NOTRANSLATE */
  Init_IrofferEvent();
  load_script(gdata.ruby_script);
}
Example #28
0
/******************************************************************
 *      InternetInitializeAutoProxyDll (jsproxy.@)
 */
BOOL WINAPI JSPROXY_InternetInitializeAutoProxyDll( DWORD version, LPSTR tmpfile, LPSTR mime,
                                                    AutoProxyHelperFunctions *callbacks,
                                                    LPAUTO_PROXY_SCRIPT_BUFFER buffer )
{
    BOOL ret = FALSE;

    TRACE( "%u, %s, %s, %p, %p\n", version, debugstr_a(tmpfile), debugstr_a(mime), callbacks, buffer );

    if (callbacks) FIXME( "callbacks not supported\n" );

    EnterCriticalSection( &cs_jsproxy );

    if (global_script->text)
    {
        LeaveCriticalSection( &cs_jsproxy );
        return FALSE;
    }
    if (buffer && buffer->dwStructSize == sizeof(*buffer) && buffer->lpszScriptBuffer &&
        (global_script->text = strdupAW( buffer->lpszScriptBuffer, buffer->dwScriptBufferSize ))) ret = TRUE;
    else if ((global_script->text = load_script( tmpfile ))) ret = TRUE;

    LeaveCriticalSection( &cs_jsproxy );
    return ret;
}
Example #29
0
int run_command_line(caWorld* world, caValue* args)
{
    RawOutputPrefs rawOutputPrefs;
    bool printRaw = false;
    bool printState = false;
    bool dontRunScript = false;
    bool printTrace = false;

    // Prepended options
    while (true) {

        if (list_length(args) == 0)
            break;

        if (string_eq(list_get(args, 0), "-break-on")) {
            DEBUG_BREAK_ON_TERM = atoi(as_cstring(list_get(args, 1)));

            list_remove_index(args, 0);
            list_remove_index(args, 0);
            std::cout << "breaking on creation of term: " << DEBUG_BREAK_ON_TERM << std::endl;
            continue;
        }

        if (string_eq(list_get(args, 0), "-path")) {
            // Add a module path
            module_add_search_path(world, as_cstring(list_get(args, 1)));
            list_remove_index(args, 0);
            list_remove_index(args, 0);
            continue;
        }

        if (string_eq(list_get(args, 0), "-p")) {
            printRaw = true;
            list_remove_index(args, 0);
            continue;
        }

        if (string_eq(list_get(args, 0), "-pp")) {
            printRaw = true;
            rawOutputPrefs.showProperties = true;
            list_remove_index(args, 0);
            continue;
        }

        if (string_eq(list_get(args, 0), "-b") || string_eq(list_get(args, 0), "-pb")) {
            printRaw = true;
            rawOutputPrefs.showBytecode = true;
            list_remove_index(args, 0);
            continue;
        }

        if (string_eq(list_get(args, 0), "-n")) {
            dontRunScript = true;
            list_remove_index(args, 0);
            continue;
        }
        if (string_eq(list_get(args, 0), "-print-state")) {
            printState = true;
            list_remove_index(args, 0);
            continue;
        }
        if (string_eq(list_get(args, 0), "-t")) {
            printTrace = true;
            list_remove_index(args, 0);
            continue;
        }

        if (string_eq(list_get(args, 0), "-load")) {
            caValue* filename = list_get(args, 1);

            Value moduleName;
            module_get_default_name_from_filename(filename, &moduleName);

            list_remove_index(args, 0);
            list_remove_index(args, 0);
            continue;
        }

        break;
    }

    // No arguments remaining
    if (list_length(args) == 0) {
        print_usage();
        return 0;
    }
    
    Block* mainBlock = fetch_module(world, "main");

    // Check to handle args[0] as a dash-command.

    // Print help
    if (string_eq(list_get(args, 0), "-help")) {
        print_usage();
        return 0;
    }

    // Eval mode
    if (string_eq(list_get(args, 0), "-e")) {
        list_remove_index(args, 0);

        Value command;
        set_string(&command, "");

        bool firstArg = true;
        while (!list_empty(args)) {
            if (!firstArg)
                string_append(&command, " ");
            string_append(&command, list_get(args, 0));
            list_remove_index(args, 0);
            firstArg = false;
        }

        caValue* result = term_value(mainBlock->eval(as_cstring(&command)));
        std::cout << to_string(result) << std::endl;
        return 0;
    }

    // Start repl
    if (string_eq(list_get(args, 0), "-repl")) {
        run_repl_stdin(world);
        return 0;
    }

    if (string_eq(list_get(args, 0), "-call")) {
        Symbol loadResult = load_script(mainBlock, as_cstring(list_get(args, 1)));

        if (loadResult == sym_Failure) {
            std::cout << "Failed to load file: " <<  as_cstring(list_get(args, 1)) << std::endl;
            return -1;
        }

        block_finish_changes(mainBlock);

        caStack* stack = circa_alloc_stack(world);

        // Push function
        caBlock* func = circa_find_function_local(mainBlock, as_cstring(list_get(args, 2)));
        circa_push_function(stack, func);

        // Push inputs
        for (int i=3, inputIndex = 0; i < circa_count(args); i++) {
            caValue* val = circa_input(stack, inputIndex++);
            circa_parse_string(as_cstring(list_get(args, i)), val);
        }

        circa_run(stack);

        if (circa_has_error(stack)) {
            circa_print_error_to_stdout(stack);
        }

        // Print outputs
        for (int i=0;; i++) {
            caValue* out = circa_output(stack, i);
            if (out == NULL)
                break;

            std::cout << to_string(circa_output(stack, i)) << std::endl;
        }
        
        circa_dealloc_stack(stack);
    }

    // Start debugger repl
    if (string_eq(list_get(args, 0), "-d"))
        return run_debugger_repl(as_cstring(list_get(args, 1)));

    // Generate cpp headers
    if (string_eq(list_get(args, 0), "-gh")) {
        load_script(mainBlock, as_cstring(list_get(args, 1)));
        std::cout << generate_cpp_headers(mainBlock);
        return 0;
    }

    // Run file checker
    if (string_eq(list_get(args, 0), "-check"))
        return run_file_checker(as_cstring(list_get(args, 1)));

    // Export parsed information
    if (string_eq(list_get(args, 0), "-export")) {
        const char* filename = "";
        const char* format = "";
        if (list_length(args) >= 2)
            format = as_cstring(list_get(args, 1));
        if (list_length(args) >= 3)
            filename = as_cstring(list_get(args, 2));
        return run_exporting_parser(format, filename);
    }

    // Build tool
    if (string_eq(list_get(args, 0), "-build")) {
        return run_build_tool(args);
    }

    // C++ gen
    if (string_eq(list_get(args, 0), "-cppgen")) {
        Value remainingArgs;
        list_slice(args, 1, -1, &remainingArgs);
        run_generate_cpp(&remainingArgs);
        return 0;
    }

    // Command reader (from stdin)
    if (string_eq(list_get(args, 0), "-run-stdin")) {
        run_commands_from_stdin();
        return 0;
    }

    // Reproduce source text
    if (string_eq(list_get(args, 0), "-source-repro")) {
        load_script(mainBlock, as_cstring(list_get(args, 1)));
        std::cout << get_block_source_text(mainBlock);
        return 0;
    }

    // Rewrite source, this is useful for upgrading old source
    if (string_eq(list_get(args, 0), "-rewrite-source")) {
        load_script(mainBlock, as_cstring(list_get(args, 1)));
        std::string contents = get_block_source_text(mainBlock);
        write_text_file(as_cstring(list_get(args, 1)), contents.c_str());
        return 0;
    }

    // Default behavior with no flags: run args[0] as a script filename.

    // Add the script's folder to module search paths.
    caValue* filename = list_get(args, 0);
    Value directory;
    get_directory_for_filename(filename, &directory);
    module_add_search_path(world, as_cstring(&directory));

    load_script(mainBlock, as_cstring(filename));
    block_finish_changes(mainBlock);
    refresh_bytecode(mainBlock);

    if (printRaw)
        print_block(mainBlock, &rawOutputPrefs, std::cout);

    if (dontRunScript)
        return 0;

    Stack* stack = alloc_stack(world);

    push_frame(stack, mainBlock);

    run_interpreter(stack);

    if (printState)
        std::cout << to_string(&stack->state) << std::endl;

    if (error_occurred(stack)) {
        std::cout << "Error occurred:\n";
        print_error_stack(stack, std::cout);
        std::cout << std::endl;
        std::cout << "Stack:\n";
        dump(stack);
        return 1;
    }

    return 0;
}
Example #30
0
void do_admin_command(caValue* input, caValue* reply)
{
    // Identify the command
    int first_space = string_find_char(input, 0, ' ');
    if (first_space == -1)
        first_space = string_length(input);

    Value command;
    string_slice(input, 0, first_space, &command);

    set_null(reply);

    if (equals_string(&command, "add_lib_path")) {
        //List args;
        //parse_tokens_as_argument_list(&tokens, &args);

    } else if (equals_string(&command, "file")) {

        List args;
        parse_string_as_argument_list(input, &args);
        do_file_command(&args, reply);

    } else if (equals_string(&command, "echo")) {

        List args;
        parse_string_as_argument_list(input, &args);
        do_echo(&args, reply);

    } else if (equals_string(&command, "write_block")) {

        int nextSpace = string_find_char(input, first_space+1, ' ');
        if (nextSpace == -1) {
            set_string(reply, "Syntax error, not enough arguments");
            return;
        }
        
        Value blockName;
        string_slice(input, first_space+1, nextSpace, &blockName);

        Value contents;
        string_slice(input, nextSpace+1, -1, &contents);

        do_write_block(&blockName, &contents, reply);

    } else if (equals_string(&command, "update_file")) {

        int nextSpace = string_find_char(input, first_space+1, ' ');
        if (nextSpace == -1) {
            set_string(reply, "Syntax error, not enough arguments");
            return;
        }
        
        Value filename;
        string_slice(input, first_space+1, nextSpace, &filename);

        Value contents;
        string_slice(input, nextSpace+1, -1, &contents);

        do_update_file(&filename, &contents, reply);

    } else if (equals_string(&command, "source_repro")) {
        List args;
        parse_string_as_argument_list(input, &args);
        Block block;
        load_script(&block, as_cstring(args[1]));
        std::cout << get_block_source_text(&block);
    } else if (equals_string(&command, "dump_stats")) {

        perf_stats_dump();
        std::cout << ":done" << std::endl;

    } else {

        set_string(reply, "Unrecognized command: ");
        string_append(reply, &command);
    }
}