Пример #1
0
Файл: V8.cpp Проект: kenahoo/V8
// [[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;
}
Пример #2
0
/* static */
void V8Runtime::bootstrap(Local<Object> global)
{
	EventEmitter::Initialize();
	krollGlobalObject = Persistent<Object>::New(Object::New());

	DEFINE_METHOD(krollGlobalObject, "log", krollLog);
	DEFINE_METHOD(krollGlobalObject, "binding", KrollBindings::getBinding);
	DEFINE_TEMPLATE(krollGlobalObject, "EventEmitter", EventEmitter::constructorTemplate);

	krollGlobalObject->Set(String::NewSymbol("runtime"), String::New("v8"));

	LOG_TIMER(TAG, "Executing kroll.js");

	TryCatch tryCatch;
	Handle<Value> result = V8Util::executeString(KrollBindings::getMainSource(), String::New("kroll.js"));

	if (tryCatch.HasCaught()) {
		V8Util::reportException(tryCatch, true);
	}
	if (!result->IsFunction()) {
		LOGF(TAG, "kroll.js result is not a function");
		V8Util::reportException(tryCatch, true);
	}

	Handle<Function> mainFunction = Handle<Function>::Cast(result);
	Local<Value> args[] = { Local<Value>::New(krollGlobalObject) };
	mainFunction->Call(global, 1, args);

	if (tryCatch.HasCaught()) {
		V8Util::reportException(tryCatch, true);
		LOGE(TAG, "Caught exception while bootstrapping Kroll");
	}
}
Пример #3
0
int __stdcall wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPTSTR lpCmdLine,int nCmdShow){
	int rt = -1;
	initContext();
	HandleScope store;
	runJSRes(IDR_JS_STRUCT,L"app.lib");
	Handle<Value> result = runJSFile(L"main.js",L"utf-8");
	if(!result.IsEmpty()){//只有出错的时候才会返回Empty, 否则即使没有返回值, result仍然是Undefined.
		Local<Object> gObj = getGlobal();
		Local<Function> main = GetJSVariant<Function>(gObj,L"main");
		if(main.IsEmpty()){
			//InnerMsg(L"没有发现 main 函数",MT_ERROR);
		}else if(!main->IsFunction()){
			//InnerMsg(L"main 不是函数",MT_ERROR);
		}else{
			TryCatch err;
			Handle<Value> args[1];
			args[0] = String::New((uint16_t*)lpCmdLine);
			Local<Value> r = main->Call(gObj,1,args);
			if(!err.Exception().IsEmpty()){
				ReportError(err);
			}else
				rt = r->Int32Value();
		}
	}
	releaseContext();
	return rt;
}
Пример #4
0
Local<Object> Module::LoadData(Isolate *isolate, const string& path)
{
	Local<Object> json;

	auto jsonData = File::ReadText(path);

	TryCatch tc;

	auto jsonStr = ConvertToV8String(jsonData);

	auto maybeValue = JSON::Parse(isolate, jsonStr);

	if (maybeValue.IsEmpty() || tc.HasCaught())
	{
		string errMsg = "Cannot parse JSON file " + path;
		throw NativeScriptException(tc, errMsg);
	}

	auto value = maybeValue.ToLocalChecked();

	if (!value->IsObject())
	{
		string errMsg = "JSON is not valid, file=" + path;
		throw NativeScriptException(errMsg);
	}

	json = value.As<Object>();

	return json;
}
Пример #5
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;
}
Пример #6
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();
}
Пример #7
0
bool v8test_eval()
{
    BEGINTEST();

    HandleScope handle_scope;
    Persistent<Context> context = Context::New();
    Context::Scope context_scope(context);

    Local<Object> qmlglobal = Object::New();
    qmlglobal->Set(String::New("a"), Integer::New(1922));

    Local<Script> script = Script::Compile(String::New("eval(\"a\")"), NULL, NULL, 
                                           Handle<String>(), Script::QmlMode);
    
    TryCatch tc;
    Local<Value> result = script->Run(qmlglobal);

    VERIFY(!tc.HasCaught());
    VERIFY(result->Int32Value() == 1922);

cleanup:
    context.Dispose();

    ENDTEST();
}
std::string V8Engine::compileScript(std::string script)
{
    HandleScope handleScope;
    TryCatch tc;

    Local<String> source = String::New(script.c_str());

    // Compile the source code.

    Local<Script> code = Script::Compile(source);
    if (!code.IsEmpty())
        return "";

    // There were errors, return them

    std::string ret = "";

    Handle<Object> exception = tc.Exception()->ToObject();
    String::AsciiValue exception_str(exception);

    ret += *exception_str; ret += "\n";

    Local<Message> message = tc.Message();

    ret += *(v8::String::Utf8Value( message->Get() )); ret += "\n";
    ret += "Source line: "; ret += *(v8::String::Utf8Value( message->GetSourceLine() )); ret += "\n";
    ret += "Source line number: "; ret += Utility::toString(message->GetLineNumber()); ret += "\n";

    return ret;
}
Пример #9
0
        void JSAttributeTest::requestValueWithCallbackTestOnlyFirstTime(std::shared_ptr<JSZAttribute> &jsZAttribute, std::shared_ptr<ZCLAttribute> attributeMock,
                                                                        Callbacks &changeSignal) {
            ZDevice zDevice{createZDevice()};
            std::stringstream stream;
            stream << "var f = function (){\n";
            stream << "    var log = Log();\n";
            stream << "    log.info('callback called')";
            stream << "};\n";

            stream << zAttributeVariable << "\n";
            stream << "var b = a.requestValue(f);\n";
            V8_SETUP
            jsZAttribute->initJsObjectsTemplate(isolate, global);
            jsLog->initJsObjectsTemplate(isolate, global);

            setInitExpectation(zDevice, attributeMock);

            TryCatch tryCatch;
            v8::Local<v8::Value> result = runScript(stream.str());
            if (tryCatch.HasCaught()) {
                String::Utf8Value value(tryCatch.Message()->Get());
            }
            ASSERT_THAT(result.IsEmpty(), false);
            ASSERT_THAT(result->IsUndefined(), true);

            changeSignal();

            result = runScript("");
            result = runScript("");

            ASSERT_THAT(log.empty(), false);
            Log::LogData logData = log.get();
            ASSERT_THAT(logData.msg, StrEq("callback called"));
            ASSERT_THAT(log.empty(), true);
        }
Пример #10
0
void ScriptGame::_mouseMoved( const float x, const float y )
{
	HandleScope hs;
	PersistentContext ctx = MagnetiteCore::Singleton->getScriptManager()->getContext();
	Context::Scope scope( ctx );
	
	bool eval = false;
	if( !mScriptObject.IsEmpty() && mScriptObject->Has( String::New("mouseMoved") ) )
	{
		Local<Value> onLoadVal = mScriptObject->Get( String::New("mouseMoved") );
		if( onLoadVal->IsFunction() )
		{
			TryCatch ct;
			Local<Function> onLoad = Local<Function>::Cast( onLoadVal );
			Handle<Value> args[2];
			args[0] = Number::New(x);
			args[1] = Number::New(y);
			auto r = onLoad->Call( mScriptObject, 2, args );
			if( r.IsEmpty() ) {
				Util::log(strize(ct.StackTrace()));
			}
			else 
			{
				eval = r->BooleanValue();
			}
		}
	}
	if(!eval && getLocalPlayer() ) {
		mPlayer->getCamera()->pitch( y );
		mPlayer->getCamera()->yaw( x );
	}
}
Пример #11
0
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);
}
Пример #12
0
    static int EIO_AfterIndex(eio_req* req) {
        HandleScope scope;
        index_baton_t* baton = static_cast<index_baton_t*>(req->data);
        ev_unref(EV_DEFAULT_UC);
        baton->lucene->Unref();

        Handle<Value> argv[2];

        if (!baton->error.empty()) {
            argv[0] = v8::String::New(baton->error.c_str());
            argv[1] = Undefined();
        }
        else {
            argv[0] = Undefined();
            argv[1] = v8::Integer::NewFromUnsigned((uint32_t)baton->indexTime);
        }

        TryCatch tryCatch;

        baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);

        if (tryCatch.HasCaught()) {
            FatalException(tryCatch);
        }

        baton->callback.Dispose();
        delete baton->index;
        delete baton;
        return 0;
    }
Пример #13
0
    static int EIO_AfterSearch(eio_req* req)
    {
        HandleScope scope;
        search_baton_t* baton = static_cast<search_baton_t*>(req->data);
        ev_unref(EV_DEFAULT_UC);
        baton->lucene->Unref();

        Handle<Value> argv[2];

        if (baton->error.empty()) {
            argv[0] = Null(); // Error arg, defaulting to no error
            argv[1] = baton->results;
        } else {
            argv[0] = String::New(baton->error.c_str());
            argv[1] = Null();
        }

        TryCatch tryCatch;

        baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);

        if (tryCatch.HasCaught()) {
            FatalException(tryCatch);
        }
        
        baton->callback.Dispose();
        if (!baton->results.IsEmpty()) baton->results.Dispose();

        delete baton->index;
        delete baton->search;
        delete baton;

        return 0;
    }
Пример #14
0
void CoreClrFuncInvokeContext::InvokeCallback(void* data)
{
	DBG("CoreClrFuncInvokeContext::InvokeCallback");

	CoreClrFuncInvokeContext* context = (CoreClrFuncInvokeContext*)data;
	v8::Handle<v8::Value> callbackData = NanNull();
	v8::Handle<v8::Value> errors = NanNull();

	if (context->taskState == TaskStatus::Faulted)
	{
		errors = CoreClrFunc::MarshalCLRToV8(context->resultData, context->resultType);
	}

	else
	{
		callbackData = CoreClrFunc::MarshalCLRToV8(context->resultData, context->resultType);
	}

	Handle<Value> argv[] = { errors, callbackData };
	int argc = 2;

	TryCatch tryCatch;
	NanNew<v8::Function>(*(context->callback))->Call(NanGetCurrentContext()->Global(), argc, argv);
	delete context;

	if (tryCatch.HasCaught())
	{
		node::FatalException(tryCatch);
	}
}
Пример #15
0
v8::Handle<v8::String> V8::toJson(v8::Handle<v8::Value> value) {
	HandleScope scope;

	Handle<Context> context = Context::GetCurrent();
	Handle<Object> global = context->Global();

	Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject();
	Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify")));

	TryCatch exception;

	Handle<Value> argv[] = {
		value,
		v8::Null(),
		v8::String::New("\t")
	};

	if (exception.HasCaught()) {
		throw chi::Exception(chi::V8::ReportException(exception));
	}

	Handle<Value> stringified = JSON_stringify->Call(JSON_stringify, 3, argv);

	if (exception.HasCaught()) {
		throw chi::Exception(chi::V8::ReportException(exception));
	}

	return scope.Close(stringified.As<String>());
}
Пример #16
0
    void Event(Pollpri * p, int revents) {
        HandleScope scope;
        PRINTF("fd = %d, epfd = %d, revents = 0x%0x\n", fd, epfd, revents);
        if(revents != EV_READ) {
            printf("fd = %d, epfd = %d, revents = 0x%0x\n", fd, epfd, revents);
            return;
        }
        
        int m = 0;
        char buf[64];
        m = lseek(fd, 0, SEEK_SET);
        PRINTF("seek(%d) %d bytes: %s\n", fd, m, strerror(errno));
        m = read(fd, &buf, 63);
        buf[m] = 0;
        PRINTF("read(%d) %d bytes (%s): %s\n", fd, m, buf, strerror(errno));

        Local<Value> emit_v = handle_->Get(String::NewSymbol("emit"));
        assert(emit_v->IsFunction());
        Local<Function> emit_f = emit_v.As<Function>();
        
        Handle<Value> argv[2];
        argv[0] = String::New("edge");
        argv[1] = String::New(buf);
        
        TryCatch tc;
        
        emit_f->Call(handle_, 2, argv);

        if(tc.HasCaught()) {
            FatalException(tc);
        }
    }
Пример #17
0
stdext::ustring JavaScriptContext::ExecuteReturnString(const stdext::ustring & source, const stdext::ustring & name, stdext::ustring & error)
{
	stdext::ustring resultString;
	error = wstringToUstring(L"");
	Locker locker(m_isolate); 
	Isolate::Scope isolate_scope(m_isolate);
	{
		Context::Scope contextScope(*m_ctx);
		HandleScope scope;
		Local<String> scriptSource = String::New(reinterpret_cast<const uint16_t *>(source.c_str()));
		Local<String> scriptName = String::New(reinterpret_cast<const uint16_t *>(name.c_str()));
		Local<Script> script = Script::New(scriptSource, scriptName);
		Local<Value> result;
		{
			TryCatch tryCatch;
			result = script->Run();
			if (!result.IsEmpty())
			{
				String::Value value(result);
				resultString.append(reinterpret_cast<const char16_t *>(*value));
			}

			if (tryCatch.HasCaught())
			{
				error.append(wstringToUstring(L"Error running script: "));
				error.append(name);
				error.append(wstringToUstring(L" - "));
				String::Value stackTrace(tryCatch.StackTrace());
				error.append(reinterpret_cast<const char16_t*>(*stackTrace));
			}
		}
	}

	return resultString;
}
Пример #18
0
int Interface::UserInvoke(JNIEnv *jniEnv, Handle<Object> target, int opIdx, jobjectArray jArgs, jobject *jResult) {
  HandleScope scope;
  TryCatch tryCatch;
  Operation *op = operations->addr(opIdx);
  int result = OK;
  for(int i = 0; result == OK && i < op->argCount; i++) {
      result = conv->ToV8Value(jniEnv, jniEnv->GetObjectArrayElement(jArgs, i), op->argTypes[i], &op->vArgs[i]);
  }
  if(result == OK) {
    Handle<Value> vRes;
    if(target->IsFunction() && parent == 0 && operations->getLength() == 1) {
      /* invoke as function if target is a function, and interface delcares only one operation */
      vRes = (Handle<Function>::Cast(target))->Call(target, op->argCount, op->vArgs);
    } else {
      /* locate the method and invoke that */
      Handle<Value> vMethod = target->Get(op->name);
      if(!vMethod.IsEmpty() && vMethod->IsFunction()) {
        vRes = Handle<Function>::Cast(vMethod)->Call(target, op->argCount, op->vArgs);
      }
    }
    if(!vRes.IsEmpty() && op->type != TYPE_UNDEFINED) {
      jobject ob;
      result = conv->ToJavaObject(jniEnv, vRes, op->type, &ob);
      if(result == OK) {
        *jResult = ob;
      }
    }
  }
  if(tryCatch.HasCaught()) {
    result = ErrorJS;
    tryCatch.Reset();
  }
  return result;
}
Пример #19
0
Script *v8ScriptService::scriptFromCode(const std::string &code, const boost::filesystem::path &filename) {
	HandleScope scope;

	// Instantiate the v8 script.
	TryCatch exception;
	Handle<v8::Script> script = v8::Script::New(
		String::New(code.c_str()),
		String::New(filename.string().c_str())
	);
	if (exception.HasCaught()) {

		throw script_compilation_error(
			V8::stringifyException(exception),
			code
		);
	}

	// Cast and ensure the factory is correct.
	AbstractFactory<v8Script> *v8ScriptFactory;
	v8ScriptFactory = dynamic_cast<AbstractFactory<v8Script> *>(
		Script::factoryManager.instance()
	);
	if (NULL == v8ScriptFactory) {
		throw script_compilation_error("Concrete v8 factory mismatch!");
	}

	// Instantiate our script and return it.
	return v8ScriptFactory->create(script);
}
Пример #20
0
JNIEXPORT void JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeSetWindow
	(JNIEnv *env, jobject javaKrollWindow, jlong ptr, jobject javaWindow)
{
	ENTER_V8(V8Runtime::globalContext);
	titanium::JNIScope jniScope(env);

	Handle<Object> jsKrollWindow;
	if (ptr != 0) {
		jsKrollWindow = Persistent<Object>((Object *) ptr);
	} else {
		jsKrollWindow = TypeConverter::javaObjectToJsValue(env, javaKrollWindow)->ToObject();
	}

	Handle<Value> setWindowValue = jsKrollWindow->Get(String::New("setWindow"));
	if (!setWindowValue->IsFunction()) {
		return;
	}

	Handle<Function> setWindow = Handle<Function>::Cast(setWindowValue->ToObject());

	Handle<Value> jsWindow = TypeConverter::javaObjectToJsValue(env, javaWindow);

	TryCatch tryCatch;
	if (!jsWindow->IsNull()) {
		Handle<Value> args[] = { jsWindow };
		setWindow->Call(jsKrollWindow, 1, args);
	}

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(tryCatch);
		V8Util::reportException(tryCatch);
	}
}
Пример #21
0
void Susi::JS::Engine::RegisterProcessor(const v8::FunctionCallbackInfo<v8::Value>& args) {
	if (args.Length() < 2) return;
	Handle<Value> callbackValue = args[1];
	if(callbackValue->IsFunction()){
		Handle<Value> topicValue = args[0];
		std::string topic{Susi::JS::Engine::convertFromJS(topicValue).toString()};
		std::shared_ptr<Persistent<Function>> jsCallback{new Persistent<Function>(Isolate::GetCurrent(),Handle<Function>::Cast(callbackValue))};
		Susi::Events::Processor callback = [jsCallback](Susi::Events::EventPtr event){
			Local<Function> func = Local<Function>::New(Isolate::GetCurrent(),*jsCallback);
			Handle<Value> callbackArguments[1];
			callbackArguments[0] = Susi::JS::Engine::convertFromCPP(event->toAny());
			TryCatch trycatch;
			auto res = func->Call(func,1,callbackArguments);
			if (res.IsEmpty()) {
				Handle<Value> exception = trycatch.Exception();
				String::Utf8Value exception_str(exception);
				std::cout<<*exception_str<<std::endl;
			}
		};
		long id = Susi::JS::engine->susi_client.subscribe(topic,callback);
		args.GetReturnValue().Set((double)id);
	}else{
		args.GetReturnValue().Set(false);
	}
}
Пример #22
0
/*
 * Class:     org_appcelerator_kroll_runtime_v8_V8Runtime
 * Method:    nativeRunModule
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeRunModule
	(JNIEnv *env, jobject self, jstring source, jstring filename, jobject activityProxy)
{
	ENTER_V8(V8Runtime::globalContext);
	titanium::JNIScope jniScope(env);

	if (moduleObject.IsEmpty()) {
		moduleObject = Persistent<Object>::New(
			V8Runtime::krollGlobalObject->Get(String::New("Module"))->ToObject());

		runModuleFunction = Persistent<Function>::New(
			Handle<Function>::Cast(moduleObject->Get(String::New("runModule"))));
	}

	Handle<Value> jsSource = TypeConverter::javaStringToJsString(source);
	Handle<Value> jsFilename = TypeConverter::javaStringToJsString(filename);
	Handle<Value> jsActivity = TypeConverter::javaObjectToJsValue(activityProxy);

	Handle<Value> args[] = { jsSource, jsFilename, jsActivity };
	TryCatch tryCatch;

	runModuleFunction->Call(moduleObject, 3, args);

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(tryCatch);
		V8Util::reportException(tryCatch, true);
	}
}
Пример #23
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();
}
Пример #24
0
v8::Handle<v8::Value> toJson(v8::Handle<v8::Value> value) {
	HandleScope scope;

	Handle<Context> context = Context::GetCurrent();
	Handle<Object> global = context->Global();
	Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject();
	Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify")));

	// JSON.stringify(values, null, '\t');
	Handle<Value> argv[] = {
		value,
		Null(),
		String::New("\t")
	};

	TryCatch exception;

	Handle<Value> stringified = JSON_stringify->Call(JSON_stringify, 3, argv);

	if (exception.HasCaught()) {
		return exception.ReThrow();
	}

	return scope.Close(stringified);
}
Пример #25
0
	Handle<Object> SorrowContext::SetupInternals(int argc, const char *argv[]) {
		HandleScope scope;
		Local<FunctionTemplate> internals_template = FunctionTemplate::New();
		internals = Persistent<Object>::New(internals_template->GetFunction()->NewInstance());
		
		Local<Object> global = Context::GetCurrent()->Global();
		SET_METHOD(global, "quit",    Quit)
		SET_METHOD(global, "version", Version)
		SET_METHOD(internals, "compile", CompileScript)
        
		if (argc) {
			Local<Array> lineArgs = Array::New(argc-1);
			for (int i = 0; i +1 < argc; i++) {
				lineArgs->Set(Integer::New(i), V8_STR(argv[i+1]));
			}
			internals->Set(V8_STR("args"), lineArgs);
		} else {
			internals->Set(V8_STR("args"), Array::New());
		}

		Handle<Object> libsObject = Object::New();
		LoadNativeLibraries(libsObject);
		internals->Set(V8_STR("stdlib"), libsObject);
        
		Handle<ObjectTemplate> env = ObjectTemplate::New();
		env->SetNamedPropertyHandler(EnvGetter);
		internals->Set(V8_STR("env"), env->NewInstance());
        
		internals->Set(V8_STR("global"), global);
		
		binarytypes = new BinaryTypes(internals);
		iostreams = new IOStreams(internals);

		Filesystem::Initialize(internals);
		Extensions::Initialize(internals);
		

		TryCatch tryCatch;
		Local<Value> func = ExecuteString(V8_STR(sorrow_native), V8_STR("sorrow.js"));
		
		if (tryCatch.HasCaught()) {
			ReportException(&tryCatch);
			exit(10);
		}

		ASSERT_PIN(func->IsFunction(), "sorrow.js main function not found");
		Local<Function> f = Local<Function>::Cast(func);
		
		Local<Value> args[1] = { Local<Value>::New(internals) };
		
		f->Call(global, 1, args);
		
		if (tryCatch.HasCaught())  {
			ReportException(&tryCatch);
			exit(11);
		}

		return internals;
	} // SetupInternals
Пример #26
0
int ArrayConv::UserGetElement(JNIEnv *jniEnv, Handle<Object> val, unsigned int elementType, int idx, jobject *jVal) {
  HandleScope scope;
  TryCatch tryCatch;
  Handle<Value> vElement = val->Get(idx);
  if(vElement.IsEmpty()) return ErrorNotfound;
  if(tryCatch.HasCaught()) return ErrorJS;
  return conv->ToJavaObject(jniEnv, vElement, elementType, jVal);
}
Пример #27
0
int ArrayConv::UserGetLength(JNIEnv *jniEnv, Handle<Object> val, int *length) {
  HandleScope scope;
  TryCatch tryCatch;
  Handle<Value> vLength = val->Get(sLength);
  if(vLength.IsEmpty()) return ErrorNotfound;
  if(tryCatch.HasCaught()) return ErrorJS;
  *length = (int)vLength->IntegerValue();
  return OK;
}
Пример #28
0
	Handle<Value> CallFunc(Handle<Object>& self,Handle<Function>& func,int argc,Handle<Value>* argv){
		TryCatch err;
		Handle<Value> ret = func->Call(self,argc,argv);
		if(err.HasCaught()){
			ReportError(err);
			return Undefined();
		}
		return ret;
	}
Пример #29
0
std::string GetException(TryCatch &try_catch, result_t hr)
{
    if (try_catch.HasCaught())
    {
        v8::String::Utf8Value exception(try_catch.Exception());

        v8::Local<v8::Message> message = try_catch.Message();
        if (message.IsEmpty())
            return ToCString(exception);
        else
        {
            v8::Local<v8::Value> trace_value = try_catch.StackTrace();

            if (!IsEmpty(trace_value))
            {
                v8::String::Utf8Value stack_trace(trace_value);
                return ToCString(stack_trace);
            }

            std::string strError;

            v8::String::Utf8Value filename(message->GetScriptResourceName());

            if (qstrcmp(ToCString(exception), "SyntaxError: ", 13))
            {
                strError.append(ToCString(exception));
                strError.append("\n    at ");
            }
            else
            {
                strError.append((ToCString(exception) + 13));
                strError.append("\n    at ");
            }

            strError.append(ToCString(filename));
            int lineNumber = message->GetLineNumber();
            if (lineNumber > 0)
            {
                char numStr[32];

                strError.append(1, ':');
                sprintf(numStr, "%d", lineNumber);
                strError.append(numStr);
                strError.append(1, ':');
                sprintf(numStr, "%d", message->GetStartColumn() + 1);
                strError.append(numStr);
            }

            return strError;
        }
    }
    else if (hr < 0)
        return getResultMessage(hr);

    return "";
}
Пример #30
0
int ArrayConv::UserSetElement(JNIEnv *jniEnv, Handle<Object> val, unsigned int elementType, int idx, jobject jVal) {
  HandleScope scope;
  TryCatch tryCatch;
  Handle<Value> vElement;
  int result = conv->ToV8Value(jniEnv, jVal, elementType, &vElement);
  if(result == OK) {
    val->Set(idx, vElement);
    if(tryCatch.HasCaught()) result =  ErrorJS;
  }
  return result;
}