Exemple #1
0
Handle<Script> ReadAndCompileScript(const char * filename)
{
	Handle<Script> script;
	// Create a string containing the JavaScript source code.
	FILE * sourceFile = fopen(filename,"rt");
	if( sourceFile == NULL )
	{
		printf("aborting!! Could not open file!");
		return script;
	}

	char buffer[20480];
	int bytesRead = fread( buffer, 1, 20480, sourceFile);
	if( bytesRead == -1 )
	{
		printf("aborting!! Could not read from file!");
		fclose(sourceFile);
		return script;
	}
	buffer[bytesRead]='\0';

	printf("Script, length=%d, source = \n%s\n",strlen(buffer),buffer);
	Handle<String> source = String::New(buffer);
	fclose(sourceFile);

	// Compile the source code.
	script = Script::Compile(source);
	script->Run();
	return script;
}
Exemple #2
0
void RUN(const char * jsstring){
  // Create a stack-allocated handle scope.
  HandleScope handle_scope;

  // Create a new context.
  Persistent<Context> context = Context::New();
  
  // Enter the created context for compiling and
  // running the hello world script. 
  Context::Scope context_scope(context);
  
  // Create a string containing the JavaScript source code.
  Handle<String> source = String::New(jsstring);

  // Compile the source code.
  Handle<Script> script = Script::Compile(source);
  
  // Run the script to get the result.
  Handle<Value> result = script->Run();
  
  // Dispose the persistent context.
  context.Dispose();

  // Convert the result to an ASCII string and print it.
  String::AsciiValue ascii(result);
  printf("%s\n", *ascii);
}
Exemple #3
0
void
test_Exception()
{
  HandleScope handle_scope;

  Persistent<Context> context = Context::New();
  Handle<Script> script = Script::New(String::New("function foo(x) { throw x; };"));

  Context::Scope scope(context);
  TryCatch trycatch;

  Handle<Value> v = script->Run();
  do_check_true(!v.IsEmpty());
  do_check_true(!trycatch.HasCaught());
  Handle<Function> fn = context->Global()->Get(String::NewSymbol("foo")).As<Function>();
  do_check_true(!fn.IsEmpty());
  Local<Value> args[1] = { Integer::New(4) };
  v = fn->Call(context->Global(), 1, args);
  do_check_true(v.IsEmpty());
  do_check_true(trycatch.HasCaught());
  Handle<Value> exn = trycatch.Exception();
  do_check_true(exn->IsInt32());
  do_check_eq(exn->Int32Value(), 4);

  context.Dispose();
}
SV*
V8Context::eval(SV* source, SV* origin) {
    HandleScope handle_scope;
    TryCatch try_catch;
    Context::Scope context_scope(context);

    Handle<Script> script = Script::Compile(
        sv2v8str(source),
        origin ? sv2v8str(origin) : String::New("EVAL")
    );

    if (try_catch.HasCaught()) {
        set_perl_error(try_catch);
        return &PL_sv_undef;
    } else {
        thread_canceller canceller(time_limit_);
        Handle<Value> val = script->Run();

        if (val.IsEmpty()) {
            set_perl_error(try_catch);
            return &PL_sv_undef;
        } else {
            sv_setsv(ERRSV,&PL_sv_undef);
            return v82sv(val);
        }
    }
}
JNIEXPORT jobject JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeEvalString
	(JNIEnv *env, jobject self, jstring source, jstring filename)
{
	ENTER_V8(V8Runtime::globalContext);
	titanium::JNIScope jniScope(env);

	Handle<Value> jsSource = TypeConverter::javaStringToJsString(env, source);
	if (jsSource.IsEmpty() || !jsSource->IsString()) {
		LOGE(TAG, "Error converting Javascript string, aborting evalString");
		return NULL;
	}

	Handle<Value> jsFilename = TypeConverter::javaStringToJsString(env, filename);

	TryCatch tryCatch;
	Handle<Script> script = Script::Compile(jsSource->ToString(), jsFilename);
	Local<Value> result = script->Run();

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(tryCatch);
		V8Util::reportException(tryCatch, true);
		return NULL;
	}

	return TypeConverter::jsValueToJavaObject(env, result);
}
Exemple #6
0
// parse string returned by $self->to_js() into function
void
V8Context::fixup_prototype(Handle<Object> prototype) {
    Handle<Value> val = prototype->Get(string_to_js);

    if (val.IsEmpty() || !val->IsFunction())
        return;

    TryCatch try_catch;

    Handle<Value> to_js = Handle<Function>::Cast(val)->Call(context->Global(), 0, NULL);
    Handle<Script> script = Script::Compile(to_js->ToString());

    if (try_catch.HasCaught()) {
        set_perl_error(try_catch);
    } else {
        Handle<Value> val = script->Run();

        if (val.IsEmpty() || !val->IsFunction()) {
            set_perl_error(try_catch);
        }
        else {
            prototype->Set(string_to_js, val);
        }
    }
}
Exemple #7
0
extern "C" Handle<Value> execute_string(Persistent<Context> context,
					const char* s,
					bool* is_exception) {
    // Create a stack-allocated handle scope.
    HandleScope handle_scope;

    // Enter the created context for compiling and
    // running the hello world script.
    Context::Scope context_scope(context);

    // Create a string containing the JavaScript source code.
    Handle<String> source = String::New(s);

    // Compile it
    Handle<Script> script = Script::Compile(source);

    // try-catch handler
    TryCatch trycatch;
    // Run it
    Persistent<Value> result = Persistent<Value>::New(script->Run());

    // Script->Run() returns an empty handle if the code threw an exception
    if (result.IsEmpty()) {
	*is_exception = true;
	Handle<Value> exception = trycatch.Exception();
	// String::AsciiValue exception_str(exception);
	return Persistent<Value>::New(exception);	
    }
    
    return result;
}
Exemple #8
0
void
test_obj_defprop() {
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();

  Context::Scope context_scope(context);

  Handle<Object> obj = Object::New();
  Handle<Value> data = Integer::New(2);
  obj->SetAccessor(String::New("myprop"), ReadTestVal, WriteTestVal, data);
  Local<Object> global = context->Global();
  global->Set(String::New("testobj"), obj);

  Handle<String> source = String::New("var n = testobj.myprop; testobj.myprop = (n+9); testobj.myprop");

  // Compile the source code.
  Handle<Script> script = Script::Compile(source);

  // Run the script to get the result.
  Handle<Value> result = script->Run();

  do_check_true(!result.IsEmpty());
  do_check_true(result->IsInt32());
  JSInt32 i = result->Int32Value();
  do_check_eq(12, i);
  context.Dispose();
}
Exemple #9
0
/**
Loads the config from JSON files
**/
void V8Config::load(string jsonFileName){

	LOG(ERROR) << "Loading configuration";

	string homeDirectory = fileSystem->getHomeDirectory() + "/Laser";
	string jsonConfigFile = fileSystem->readFile(homeDirectory + "/" + jsonFileName);


	//create the context
	context = Context::New();

	// Enter the created context for compiling and
	// running the script.
	Context::Scope context_scope(context);

	// Create a string containing the JavaScript source code.
	string evalStart("eval(");
	string evalEnd(");");
	string evalJson = evalStart + jsonConfigFile + evalEnd;
	Handle<String> source = String::New(evalJson.c_str());

	// Compile the source code.
	Handle<Script> script = Script::Compile(source);

	// Run the script to get the result.
	Handle<Value> result = script->Run();
	parseConfig(result);


	// Convert the result to an ASCII string and print it.
	String::AsciiValue ascii(result);

	LOG(ERROR) << *ascii;

}
Exemple #10
0
int v8main(char *js) {
 
// Create a new context.
//  static 
	  Persistent<Context> context = Context::New(0);

// Create a stack-allocated handle scope.
//  HandleScope handle_scope;
  
  // Enter the created context for compiling and
  // running the hello world script. 
  Context::Scope context_scope(context);

  // Create a string containing the JavaScript source code.
  Handle<String> source = String::NewFromUtf8( js );  //"'Hello' + ', World!'");

  // Compile the source code.
  Handle<Script> script = Script::Compile(source);
  
  // Run the script to get the result.
  Handle<Value> result = script->Run();
  
  // Dispose the persistent context.
//  context.Dispose();

  // Convert the result to an ASCII string and print it.

//  String::AsciiValue ascii(result);

//  if(*ascii){
//    printf("%s\n", *ascii);
//  }
  
  return 0;
}
// Executes a string within the current v8 context.
bool ExecuteString(Handle<String> source) 
{
	TryCatch tryCatch;
    
	Handle<Script> script = Script::Compile(source);
    
	if (script.IsEmpty()) {
        ReportException(&tryCatch);
		return false;
        
	} else {
		Handle<Value> result = script->Run();
		if (result.IsEmpty()) {
            ReportException(&tryCatch);
			return false;
            
		} else {
//			if(!result->IsUndefined()) {
//				// If all went well and the result wasn't undefined then print
//				// the returned value.
//				String::Utf8Value str(result);
//				const char* cstr = ToCString(str);
//				printf("%s\n", cstr);
//                delete cstr;
//			}
			return true;
		}
	}
}
Exemple #12
0
// [[Rcpp::export]]
std::string context_eval(std::string src, Rcpp::XPtr< v8::Persistent<v8::Context> > ctx){
  // Test if context still exists
  if(!ctx)
    throw std::runtime_error("Context has been disposed.");

  // Create a scope
  HandleScope handle_scope;
  Context::Scope context_scope(*ctx);

  // Compile source code
  TryCatch trycatch;
  Handle<Script> script = compile_source(src);
  if(script.IsEmpty()) {
    Local<Value> exception = trycatch.Exception();
    String::AsciiValue exception_str(exception);
    throw std::invalid_argument(*exception_str);
  }

  // Run the script to get the result.
  Handle<Value> result = script->Run();
  if(result.IsEmpty()){
    Local<Value> exception = trycatch.Exception();
    String::AsciiValue exception_str(exception);
    throw std::runtime_error(*exception_str);
  }

  // Convert result to UTF8.
  String::Utf8Value utf8(result);
  return *utf8;
}
bool SMJS_Plugin::RunString(const char* name, const char *source, bool asGlobal){
	HandleScope handle_scope(isolate);
	Context::Scope context_scope(context);

	TryCatch try_catch;
	v8::ScriptOrigin origin(String::New(name), v8::Integer::New(0), v8::Integer::New(0));
	Handle<Script> script;
	if(asGlobal){
		script = Script::Compile(v8::String::New(source), &origin);
	}else{
		char *buffer = new char[strlen(source) + 100];
		strcpy(buffer, "(function(global){");
		strcat(buffer, source);
		strcat(buffer, "})(this);");
		script = Script::Compile(v8::String::New(buffer), &origin);
		delete buffer;
	}

	if(script.IsEmpty()) {
		// Print errors that happened during compilation.
		ReportException(&try_catch);
		return false;
	} else {
		Handle<Value> result = script->Run();
		if (result.IsEmpty()) {
			ReportException(&try_catch);
			return false;
		}

		return true;
	}
}
Exemple #14
0
jsvalue JsContext::Execute(JsScript *jsscript)
{
    jsvalue v;

    Locker locker(isolate_);
    Isolate::Scope isolate_scope(isolate_);
    (*context_)->Enter();
        
    HandleScope scope;
    TryCatch trycatch;
   
	Handle<Script> script = (*jsscript->GetScript());

	if (!script.IsEmpty()) {
		Local<Value> result = script->Run();
	
		if (result.IsEmpty())
			v = engine_->ErrorFromV8(trycatch);
		else
			v = engine_->AnyFromV8(result);        
	}

    (*context_)->Exit();
	return v;     
}
Exemple #15
0
int main(int argc, char* argv[])
{
    // Get the default Isolate created at startup
    //Isolate* isolate = Isolate::GetCurrent();
    
    // create a stack-allocated handle scope;
    HandleScope handle_scope;
    
    // create a new context;
    Handle<Context> context = Context::New();// = Context::New(isolate);
    
    // Enter the context for compiling and running the hello world script.
    Context::Scope context_scope(context);
    
    // create a string containing the JavaScript source code.
    Handle<String> source = String::New("'Hello' + ', World!'");
    
    // Compile the source code.
    Handle<Script> script = Script::Compile(source);
    
    // Run the script to get the result.
    Handle<Value> result = script->Run();

    // Convert the result to an Utf8 string and print it.
    
    
    String::Utf8Value utf8(result);
    printf("%s\n", *utf8);
    
    return 0;
}
Exemple #16
0
extern "C" Handle<Value> create_function(Persistent<Context> context,
                                         char* source_s,
                                         char* name) {

    // Create a stack-allocated handle scope.
    HandleScope handle_scope;

    Context::Scope context_scope(context);

    // Create a string containing the JavaScript source code.
    Handle<String> source = String::New(source_s);
    // Compile the source code.
    Handle<Script> script = Script::Compile(source);

    // Run the script to get the result.
    Handle<Value> result = script->Run();

    // magic
    Handle<Object> global = context->Global();
    Handle<Value> value = global->Get(String::New(name));

    Handle<Function> func = v8::Handle<Function>::Cast(value);
    func->SetName(String::New(name));

    Persistent<Function> persistent_func = Persistent<Function>::New(func);
    return persistent_func;
}
Exemple #17
0
void
test_obj_propexn() {
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();

  Context::Scope context_scope(context);

  Handle<Object> obj = Object::New();
  obj->SetAccessor(String::New("myprop"), ReadExn, WriteExn);
  Local<Object> global = context->Global();
  global->Set(String::New("testobj"), obj);

  Handle<String> source = String::New("var n = 0;"
                                      "try { testobj.myprop; } catch (e) { n += e; };"
                                      "try { testobj.myprop = (n+9); } catch (e) { n += e; }; n");

  // Compile the source code.
  Handle<Script> script = Script::Compile(source);

  TryCatch trycatch;
  // Run the script to get the result.
  Handle<Value> result = script->Run();

  do_check_false(result.IsEmpty());
  do_check_true(result->IsInt32());
  do_check_false(trycatch.HasCaught());
  JSInt32 i = result->Int32Value();
  do_check_eq(13, i);
  context.Dispose();
}
Exemple #18
0
bool
WeechatJsV8::execScript()
{
    v8::TryCatch trycatch;

    this->context = Context::New(NULL, this->global);
    Context::Scope context_scope(this->context);
    Handle<Script> script = Script::Compile(this->source);

    if (script.IsEmpty())
    {
        PRINT_EXCEPTION;
        return false;
    }
    else
    {
        Local<Value> value = script->Run();
        if (value.IsEmpty())
        {
            PRINT_EXCEPTION;
            return false;
        }
    }

    return true;
}
void CanvasContextV8Bindings::executeJS(const std::string& _js)
{
	HandleScope handle_scope;
	Context::Scope context_scope(CanvasContextV8Bindings::contextV8);

	Handle<v8::String> source = v8::String::New(_js.c_str());
	Handle<Script> script = Script::Compile(source);
	Handle<Value> result = script->Run();
}
Exemple #20
0
int main(int argc, char* argv[]) {

    try {

        // Get user options
        TCLAP::CmdLine cmd("JSLint", ' ', "0.1");
        TCLAP::ValueArg<std::string> optionsArg("o", "options", "JSLint options", false, jslint::default_options(), "string", cmd);
        TCLAP::UnlabeledMultiArg<std::string> filesArg("files", "file names", true, "string", cmd);

        cmd.parse( argc, argv );

        std::string lint_options = optionsArg.getValue();
        std::vector<std::string> files = filesArg.getValue();

        for (int i=0; i < files.size(); i++) {

            std::string fileName = files[i];

            // Create a stack-allocated handle scope.
            HandleScope handle_scope;

            // Create a new context.
            Persistent<Context> context = Context::New();

            // Enter the created context for compiling and
            // running the jslint
            Context::Scope context_scope(context);

            try {
              // Create a string containing the JavaScript source code.

              Handle<String> source = jslint::load_source_js(const_cast<char *>(fileName.c_str()), lint_options);

              // Compile the source code.
              Handle<Script> script = Script::Compile(source);

              // Run the script to get the result.
              Handle<Value> result = script->Run();

              // Convert the result to an ASCII string and print it.
              String::AsciiValue ascii(result);
              printf("%s\n", *ascii);
            } catch(v8::Exception e) {
              // nothing
            }

            // Dispose the persistent context.
            context.Dispose();

        }

    } catch (TCLAP::ArgException &e) {
        std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    }

    return 0;
}
Handle<Value> TiRootObject::_require(void* userContext, TiObject* caller, const Arguments& args)
{
	HandleScope scope;
	Local<Object> globalObject = TitaniumRuntime::getContenxt()->Global();

	Handle<Value> nativeModule = TiModuleRegistry::GetModule(QString(*String::Utf8Value(args[0]->ToString())));
	if(!nativeModule->IsUndefined())
	{
		return scope.Close(nativeModule);
	}
	QString fileName = Ti::TiHelper::QStringFromValue(args[0]).append(".js");
	QString filePath = Ti::TiHelper::getAssetPath(fileName).prepend("app/native/");
	Local<Value> existingModule = globalObject->GetHiddenValue(Ti::TiHelper::ValueFromQString(fileName)->ToString());
	if(!existingModule.IsEmpty() && !existingModule->IsUndefined())
	{
		return scope.Close(existingModule);
	}

	QString js = readJsFile(filePath);
	if(js.isEmpty()) {
		ThrowException(String::New(
								QString("Module not found ").append(fileName).toLocal8Bit().constData()
						));
		return scope.Close(Undefined());
	}
	js.prepend("(function(){"
			"var __vars = {};"
			"__vars.exports = {};"
			"__vars.module = {exports:__vars.exports};"
			"var module = __vars.module;"
			"var exports = __vars.exports;");
	js.append("\nreturn __vars.module.exports;"
			"})();");


	Handle<Script> script = Script::Compile(Ti::TiHelper::ValueFromQString(js)->ToString() , Ti::TiHelper::ValueFromQString(fileName));
	TryCatch tryCatch;
	if (script.IsEmpty())
	{
    	Ti::TiErrorScreen::ShowWithTryCatch(tryCatch);
		return scope.Close(Undefined());
	}
	Persistent<Value> result = Persistent<Value>::New(script->Run());
	result.MarkIndependent();
	if (result.IsEmpty())
	{
    	Ti::TiErrorScreen::ShowWithTryCatch(tryCatch);
		return scope.Close(Undefined());
	}
	globalObject->SetHiddenValue(Ti::TiHelper::ValueFromQString(fileName)->ToString(), result);
	return scope.Close(result);
}
Exemple #22
0
/** Evaluation **/
bool cJavaScript::eval ( const std::string &in, std::string &out )  {
#ifdef ENABLE_JAVASCRIPT
  bool success = true;
  m_strError = "";

  Isolate::Scope isolate_scope ( isolate );

  // Create a stack-allocated handle scope.
  HandleScope handle_scope ( isolate );

  // Create a template for the global object.
  v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
  // Bind the global 'print' function to the C++ Print callback.
  global->Set(v8::String::NewFromUtf8(isolate, "print"),
              v8::FunctionTemplate::New(isolate, Print));

  // Create a new context.
  context = Context::New ( isolate, NULL, global );

  // Enter the context for compiling and running the hello world script.
  Context::Scope context_scope ( context );

  std::string str = m_strAiml + in;
  try {
    Handle<String> source = String::NewFromUtf8 ( isolate, str.c_str ( ) );
    // Compile the source code.
    Handle<Script> script = Script::Compile ( source );
    if ( script.IsEmpty ( ) )  {
      m_strError = "JavaScript Compilation error.";
    }
    else  {
      // Run the script to get the result.
      Handle<Value> result = script->Run ( );

      // Convert the result to an UTF8 string and print it.
      String::Utf8Value utf8 ( result );
      m_strEval = *utf8;
      success = true;
      // printf ( "result of %s =  %s\n", in.c_str ( ), str.c_str ( ) );
    }
  }
  catch (...)  {
    m_strError = "Failed to compile";
  }

  return success;
#else
  m_strError = "no JavaScript support";
  return false;
#endif
}
Exemple #23
0
void loadfile(std::string filename){
    Context::Scope context_scope(context);
	LOGI("Loading js file : %s",filename.c_str());

    std::string filepath = libdir + filename;
    // Create a string containing the JavaScript source code.
    Handle<String> source = ReadFile(filepath.c_str());
    // Compile the source code.
    Handle<Script> script = Script::Compile(source);
	
	script->Run();
	LOGI("Finished Loding file.");
	
}
Exemple #24
0
void
test_Constructor()
{
  HandleScope handle_scope;
  Handle<ObjectTemplate> templ = ObjectTemplate::New();
  Handle<FunctionTemplate> fnT = v8::FunctionTemplate::New(AddOne);
  templ->Set("AddOne", fnT);

  Persistent<Context> context = Context::New(NULL, templ);
  Handle<Script> script = Script::New(String::New("new AddOne(4);"));

  Context::Scope scope(context);
  script->Run();
}
Exemple #25
0
/* Runs a compiled script */
static Handle<Value> msV8RunScript(Handle<Script> script)
{
  if (script.IsEmpty()) {
    ThrowException(String::New("No script to run"));
    return Handle<Value>();
  }

  TryCatch try_catch;
  Handle<Value> result = script->Run();

  if (result.IsEmpty() && try_catch.HasCaught()) {
    msV8ReportException(&try_catch);
  }

  return result;
}
Exemple #26
0
void loadfile(const char * filename){
    Context::Scope context_scope(context);
	current_module_name = std::string(filename);
	std::string full_file_path = lib_dir_path + current_module_name;
	LOGI("Loading js file :");
	LOGI(full_file_path.c_str());

    // Create a string containing the JavaScript source code.
    Handle<String> source = ReadFile(full_file_path.c_str());
    // Compile the source code.
    Handle<Script> script = Script::Compile(source);
	
	script->Run();
	LOGI("Finished Loding file.");
	
	
}
// Load up the JS engine
void initJsEngine(){
    char path[1024];
    uint32_t size = sizeof(path);
    if (_NSGetExecutablePath(path, &size) != 0)
       printf("buffer too small; need size %u\n", size);
    
    string script_path;
    char *pch, *next_pch;
    pch = strtok(path, "/");
    next_pch = strtok(NULL, "/");
    //Rebuild the path, ommitting the last part (the exe name)
    while (next_pch != NULL) {
        script_path.append( "/" );
        script_path.append( pch );
        pch = next_pch;
        next_pch = strtok(NULL, "/");
    }
    script_path.append("/script.js");
    ifstream infile;
    
    infile.open (script_path.c_str(), ifstream::in);
    string file = "";
    while (infile.good()){
        file += (char) infile.get();
    }
    //Get rid of the of character
    file[file.length() - 1] = ' ';
    setJsFile( file.c_str() );
    infile.close();

    // Lock this v8 instance to this thread?
    Locker locker;
    HandleScope handle_scope;
    Persistent<Context> context = Context::New();
    Context::Scope context_scope(context);
    

    context->Global()->Set(String::New("System"), getSystemTemplate()->NewInstance() ); 
    context->Global()->Set(String::New("Player"), getPlayerTemplate()->NewInstance() );
    context->Global()->Set(String::New("Games"),  getGamesTemplate()->NewInstance() );
    
    Handle<String> source = String::New(js_file);
    Handle<Script> script = Script::Compile(source);
    Handle<Value> result = script->Run();
    context.Dispose();
}
Exemple #28
0
void Run(const char* jsString, int len, const char* origin) {
  HandleScope scope;

  // Allocates a new string from either utf-8 encoded or ascii data.
  // The second parameter 'length' gives the buffer length.
  // If the data is utf-8 encoded, the caller must be careful to supply the
  // length parameter. If it is not given, the function calls 'strlen' to
  // determine the buffer length, it might be wrong if 'data' contains a null
  // character.
  Handle<String> source = String::New(jsString, len);

  Handle<Script> script;
  if (origin == NULL)
    script = Script::Compile(source);
  else
    script = Script::Compile(source, String::New(origin));
  script->Run();
}
Exemple #29
0
V8Context::V8Context(
    int time_limit,
    const char* flags,
    bool enable_blessing_,
    const char* bless_prefix_
)
    : time_limit_(time_limit),
      bless_prefix(bless_prefix_),
      enable_blessing(enable_blessing_)
{
    isolate = Isolate::New();
    Isolate::Scope isolate_scope(isolate);
    Locker locker(isolate);
    HandleScope handle_scope;
    V8::SetFlagsFromString(flags, strlen(flags));
    context = Persistent<Context>::New(isolate, Context::New(isolate));
    Context::Scope context_scope(context);

    V8Thread::install(context->Global());

    Local<FunctionTemplate> tmpl = FunctionTemplate::New(PerlFunctionData::v8invoke);
    context->Global()->Set(
        String::New("__perlFunctionWrapper"),
        tmpl->GetFunction()
    );

    Handle<Script> script = Script::Compile(
        String::New(
            "(function(wrap) {"
            "    return function() {"
            "        var args = Array.prototype.slice.call(arguments);"
            "        args.unshift(wrap);"
            "        return __perlFunctionWrapper.apply(this, args)"
            "    };"
            "})"
        )
    );
    make_function = Persistent<Function>::New(isolate, Handle<Function>::Cast(script->Run()));

    string_wrap = Persistent<String>::New(isolate, String::New("wrap"));
    string_to_js = Persistent<String>::New(isolate, String::New("to_js"));

    number++;
}
Exemple #30
0
    bool V8Scope::exec( const string& code , const string& name , bool printResult , bool reportError , bool assertOnError, int timeoutMs ){

        if ( timeoutMs ){
            static bool t = 1;
            if ( t ){
                log() << "timeoutMs not support for v8 yet" << endl;
                t = 0;
            }
        }
        
        HandleScope handle_scope;
        TryCatch try_catch;
    
        Handle<Script> script = v8::Script::Compile( v8::String::New( code.c_str() ) , 
                                                     v8::String::New( name.c_str() ) );
        if (script.IsEmpty()) {
            stringstream ss;
            ss << "compile error: " << toSTLString( &try_catch );
            _error = ss.str();
            if (reportError)
                log() << _error << endl;
            if ( assertOnError )
                uassert( _error , 0 );
            return false;
        } 
    
        Handle<v8::Value> result = script->Run();
        if ( result.IsEmpty() ){
            _error = (string)"exec error: " + toSTLString( &try_catch );
            if ( reportError )
                log() << _error << endl;
            if ( assertOnError )
                uassert( _error , 0 );
            return false;
        } 
        
        _global->Set( v8::String::New( "__lastres__" ) , result );

        if ( printResult && ! result->IsUndefined() ){
            cout << toSTLString( result ) << endl;
        }
        
        return true;
    }