Esempio n. 1
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();
}
Esempio n. 2
0
void
test_BasicCall()
{
  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);
  Context::Scope context_scope(context);
  Local<Value> addone = context->Global()->Get(String::New("AddOne"));
  do_check_true(!addone.IsEmpty());
  do_check_true(!addone->IsUndefined());
  do_check_true(addone->IsObject());
  do_check_true(addone->IsFunction());
  Local<Function> fn = addone.As<Function>();
  do_check_eq(fn, fnT->GetFunction());
  Local<Number> n = Number::New(0.5);
  Handle<Value> args[] = { n };
  Local<Value> v = fn->Call(context->Global(), 1, args);
  do_check_true(!v.IsEmpty());
  do_check_true(v->IsNumber());
  Local<Number> n2 = v->ToNumber();
  do_check_eq(n2->Value(), 1.5);
  context.Dispose();
}
Esempio n. 3
0
void cm_script_GetGeometrySize(cm_script* Script, int* x, int* y, int* z)
{
    // Thread protection
    v8::Locker Locker;
    
    // 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);
    
    // Get the latest geometry
    v8::Local<v8::Function> FunctionName = v8::Local<v8::Function>::Cast(context->Global()->Get(v8::String::New("cm_GetGeometry")));
    
    v8::Handle<v8::Value> args[] = { };
    v8::Local<v8::Value> Result = FunctionName->Call(FunctionName, 0, args);
    
    // If we got back an array
    if(Result->IsArray())
    {
        // Turn into array
        v8::Handle<v8::Array> Array0 = v8::Handle<v8::Array>::Cast(Result);
        *z = Array0->Length();
        
        v8::Handle<v8::Array> Array1 = v8::Handle<v8::Array>::Cast(Array0->Get(0));
        *y = Array1->Length();
        
        v8::Handle<v8::Array> Array2 = v8::Handle<v8::Array>::Cast(Array1->Get(0));
        *x = Array2->Length();
    }
    else
        *x = *y = *z = 0;
}
Esempio n. 4
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;
}
Esempio n. 5
0
jstring JNICALL Java_me_sarim_myfirstapp_MainActivity_avroparse( JNIEnv* env,jobject thiz,jstring sk1) {
	
  std::string banglatxt;
  GetJStringContent(env,sk1,banglatxt);
  Context::Scope context_scope(context);
  /*
  std::string code1 = "OmicronLab.Avro.Phonetic.parse('";
  std::string code2 = "');";
  std::string finalcode = code1 + banglatxt + code2;
  Handle<String> source2 = String::New(finalcode.c_str());
  
  Handle<Script> script2 = Script::Compile(source2);
   
  Handle<Value> result = script2->Run();
  */
  
  Handle<Object> global = context->Global();
  Handle<Value> avro_parse =   global->Get(String::New("testfunc"));
  Handle<Function> avro_parse_func = Handle<Function>::Cast(avro_parse);
  Handle<Value> args[1];
  Handle<Value> result;

  args[0] = v8::String::New(banglatxt.c_str());
  
  result = avro_parse_func->Call(global, 1, args);
  

  // Convert the result to an ASCII string and print it.
  String::Utf8Value ascii(result);
  //printf("%s\n", *ascii);
  //char * bntext = *ascii;
  std::string bntext = std::string(*ascii);
  
  return env->NewStringUTF(bntext.c_str());
}
Esempio n. 6
0
Handle<Value> WrappedScript::CreateContext(const Arguments& args)
{
	HandleScope scope;

	Persistent<Context> context = Context::New(NULL, WrappedContext::global_template);
	WrappedContext *wrappedContext = new WrappedContext(context);
	Local<Object> global = context->Global();

	// Allow current context access to newly created context's objects.
	context->SetSecurityToken(Context::GetCurrent()->GetSecurityToken());

	// If a sandbox is provided initial the new context's global with it.
	if (args.Length() > 0) {
		Local<Object> sandbox = args[0]->ToObject();
		Local<Array> keys = sandbox->GetPropertyNames();

		for (uint32_t i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = sandbox->Get(key);
			if (value == sandbox) {
				value = global;
			}
			global->Set(key, value);
		}
	}

	return scope.Close(global);
}
Esempio n. 7
0
/*
 * Class:     org_appcelerator_kroll_runtime_v8_V8Runtime
 * Method:    nativeInit
 * Signature: (Lorg/appcelerator/kroll/runtime/v8/V8Runtime;)J
 */
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeInit(JNIEnv *env, jobject self, jboolean useGlobalRefs, jint debuggerPort, jboolean DBG)
{
	HandleScope scope;
	titanium::JNIScope jniScope(env);

	// Log all uncaught V8 exceptions.
	V8::AddMessageListener(logV8Exception);
	V8::SetCaptureStackTraceForUncaughtExceptions(true);

	JavaObject::useGlobalRefs = useGlobalRefs;
	V8Runtime::debuggerEnabled = debuggerPort >= 0;
	V8Runtime::DBG = DBG;

	V8Runtime::javaInstance = env->NewGlobalRef(self);
	JNIUtil::initCache();

	Persistent<Context> context = Persistent<Context>::New(Context::New());
	context->Enter();

	V8Runtime::globalContext = context;
	V8Runtime::bootstrap(context->Global());

	if (V8Runtime::debuggerEnabled) {
		jclass v8RuntimeClass = env->FindClass("org/appcelerator/kroll/runtime/v8/V8Runtime");
		dispatchDebugMessage = env->GetMethodID(v8RuntimeClass, "dispatchDebugMessages", "()V");

		Debug::SetDebugMessageDispatchHandler(dispatchHandler);
		Debug::EnableAgent("titanium", debuggerPort, true);
	}

	LOG_HEAP_STATS(TAG);
}
Esempio n. 8
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();
}
Esempio n. 9
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();
}
Esempio n. 10
0
jstring JNICALL Java_com_omicronlab_avrokeyboard_PhoneticIM_avroparse( JNIEnv* env,jobject thiz,jstring sk1) {
	
  std::string banglatxt;

  //convert java String to Cpp String  
  GetJStringContent(env,sk1,banglatxt);
    
  Context::Scope context_scope(context);
  
  Handle<Object> global = context->Global();
  Handle<Value> avro_parse = global->Get(String::New("avroparsefunc"));
  Handle<Function> avro_parse_func = Handle<Function>::Cast(avro_parse);
  Handle<Value> args[1];
  Handle<Value> result;

  args[0] = v8::String::New(banglatxt.c_str());
  
  result = avro_parse_func->Call(global, 1, args);
  

  // Convert the result to an ASCII string 
  String::Utf8Value ascii(result);

  std::string bntext = std::string(*ascii);
  
  return env->NewStringUTF(bntext.c_str());
}
Esempio n. 11
0
bool cm_script_GetGeometry(cm_script* Script, int x, int y, int z, int* Char, int* Color)
{
    // Get geometry size and return on error
    int Sizex, Sizey, Sizez;
    cm_script_GetGeometrySize(Script, &Sizex, &Sizey, &Sizez);
    if(x < 0 || x >= Sizex || y < 0 || y >= Sizey)
        return false;
    
    // Thread protection
    v8::Locker Locker;
    
    // 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);
    
    // Get the latest geometry
    v8::Local<v8::Function> FunctionName = v8::Local<v8::Function>::Cast(context->Global()->Get(v8::String::New("cm_GetGeometry")));
    
    v8::Handle<v8::Value> args[] = { };
    v8::Local<v8::Value> Result = FunctionName->Call(FunctionName, 0, args);
    
    // If we got back an array
    if(Result->IsArray())
    {
        // Turn into array
        v8::Handle<v8::Array> Array = v8::Handle<v8::Array>::Cast(Result);
        String::AsciiValue Ascii(Array->ToString());
        if(Array->IsUndefined())
            return false;
        
        v8::Handle<v8::Array> Array0 = v8::Handle<v8::Array>::Cast(Array->Get(z));
        String::AsciiValue Ascii0(Array0->ToString());
        if(Array0->IsUndefined())
            return false;
        
        v8::Handle<v8::Array> Array1 = v8::Handle<v8::Array>::Cast(Array0->Get(y));
        String::AsciiValue Ascii1(Array1->ToString());
        if(Array1->IsUndefined())
            return false;
        
        v8::Handle<v8::Value> Array2 = Array1->Get(x);
        String::AsciiValue Ascii2(Array2->ToString());
        if(Array2->IsUndefined())
            return false;
        
        *Color = CM_BG_RED | CM_FG_WHITE;
        *Char = (*Ascii2)[0];
        
        // If empty (space) just return false
        if(*Char != ' ')
            return true;
    }
    
    // Failed
    return false;
}
Esempio n. 12
0
extern "C" void registerValue(Persistent<Context> context, const char* name, Handle<Value> val) {
    HandleScope handle_scope;
    Context::Scope context_scope(context);

    Handle<Object> global = context->Global();
    
    global->Set(String::New(name), val);
}
Esempio n. 13
0
extern "C" void register_function(Persistent<Context> context, InvocationCallback cb) {
    HandleScope handle_scope;
    Context::Scope context_scope(context);

    Handle<Object> global = context->Global();
    
    global->Set(String::New("apply_fsharp"), FunctionTemplate::New(cb)->GetFunction());
}
// 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();
}
Esempio n. 15
0
WrappedContext::WrappedContext(Persistent<Context> context)
	: context_(context)
{
	HandleScope scope;

	Local<Object> globalProxy = context->Global();
	Local<Object> global = globalProxy->GetPrototype().As<Object>();
	Wrap(global);
}
Esempio n. 16
0
int main(int argc, char** argv) {
	signal(SIGSEGV, AnsiSignalHandler);
//    printf("SILK V0.1\n");
    if (argc < 2) {
		printf("usage: %s file.js\n", argv[0]);
		exit(1);
    }
	
	char *startup = readFile(argv[1]);
	if (!startup) {
		printf("%s not found\n", argv[1]);
		exit(1);
	}
	if (startup[0] == '#' && startup[1] == '!') {
		startup[0] = startup[1] = '/';
	}
	init_global_object();
	{
		HandleScope scope;
		context = Persistent<Context>::New(Context::New(NULL, globalObject));
		Context::Scope context_scope(context);

//		Debug::EnableAgent("silkjs", 9222);
//		Debug::SetDebugMessageDispatchHandler(debugger, true);

		Handle<Script>init = Script::New(String::New("global=this;"), String::New("builtin"));
		init->Run();
		
		mainScript = Persistent<Script>::New(Script::Compile(String::New(startup), String::New(argv[1])));
		mainScript->Run();
		Handle<String> process_name = String::New("main");
		Handle<Value> process_val = context->Global()->Get(process_name);
		Handle<Function> process_fun = Handle<Function>::Cast(process_val);
		mainFunc = Persistent<Function>::New(process_fun);
		const int ac = argc-2;
		Handle<Value>av[ac];
		for (int i=2; i<argc; i++) {
			av[i-2] = String::New(argv[i]);
		}
//		printf("SILKJS running %s\n", argv[1]);
		mainFunc->Call(context->Global(), ac, av);
	}
}
Esempio n. 17
0
extern "C" Handle<Value> apply_function(Persistent<Context> context,
                                        Handle<Function> func,
                                        Handle<Value> arg1) {
    HandleScope handle_scope;

    Context::Scope context_scope(context);

    Handle<Value> result = func->Call(context->Global(), 1, &arg1);

    Persistent<Value> js_result = Persistent<Value>::New(result);

    return js_result;
}
Esempio n. 18
0
/*
void cm_script_Interact(cm_script* Script)
 {
 // Thread protection
 v8::Locker Locker;
 
    // Create a stack-allocated handle scope.
    HandleScope handle_scope;
    
    // Cast as needed
    Persistent<Context> context = *((Persistent<Context>*)Script->__PersistentContext);
    
    // Get the latest geometry
    v8::Local<v8::Function> FunctionName = v8::Local<v8::Function>::Cast(context->Global()->Get(v8::String::New("cm_Interact")));
    
    v8::Handle<v8::Value> args[] = { };
    FunctionName->Call(FunctionName, 0, args);
}

void cm_script_LookAt(cm_script* Script)
 {
 // Thread protection
 v8::Locker Locker;
 
    // Create a stack-allocated handle scope.
    HandleScope handle_scope;
    
    // Cast as needed
    Persistent<Context> context = *((Persistent<Context>*)Script->__PersistentContext);
    
    // Get the latest geometry
    v8::Local<v8::Function> FunctionName = v8::Local<v8::Function>::Cast(context->Global()->Get(v8::String::New("cm_LookAt")));
    
    v8::Handle<v8::Value> args[] = { };
    FunctionName->Call(FunctionName, 0, args);
}
*/
void cm_script_Update(cm_script* Script, float dT)
{
    // Thread protection
    v8::Locker Locker;
    
    // 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);
    
    // Get the latest geometry
    v8::Local<v8::Function> FunctionName = v8::Local<v8::Function>::Cast(context->Global()->Get(v8::String::New("cm_Update")));
    
    v8::Handle<v8::Value> args[] = { v8::Number::New(dT) };
    FunctionName->Call(FunctionName, 1, args);
}
Esempio n. 19
0
File: main.cpp Progetto: simonask/js
int main (int argc, char const *argv[])
{
	HandleScope handle_scope;
	
	Handle<ObjectTemplate> global = ObjectTemplate::New();
	
	global->Set(String::New("load"), FunctionTemplate::New(js_load));
	Persistent<Context> context = Context::New(NULL, global);
	Context::Scope context_scope(context);
	Handle<Object> global_obj(context->Global());
	IO::initialize(global_obj);
	Process::initialize(global_obj);
	
	Handle<Value> result = LoadScript(argv[1]);
	
	context.Dispose();
	
	return 0;
}
Esempio n. 20
0
Handle<Value> EditorGetCurrentLineRange(const Arguments& args)
{
    CComPtr<VirtualPoint> point;
    long charOffset;
    long lineLen;
    long absCharOffset;
    g_pSelection->get_ActivePoint(&point);
    point->get_AbsoluteCharOffset(&absCharOffset);
    point->get_LineCharOffset(&charOffset);
    point->get_LineLength(&lineLen);
    
    long lineOffset = absCharOffset - charOffset;

    Local<Function> fCreateRange =
        Local<Function>::Cast(g_Context->Global()->Get(String::New("createRange")));

    Handle<Value> argv[] = { Int32::New(lineOffset), Int32::New(lineOffset + lineLen) };

    return fCreateRange->Call(fCreateRange, 2, argv);
}
Esempio n. 21
0
// Performs a dust.js render inside of V8
int DustJs::render(const string filename, const map<string, string> &model, onRenderFn callback) {
	const string tmpl = filename.substr(0, filename.find_last_of("."));

	// Create a new scope
	HandleScope handle_scope;
	Persistent<Context> context = Context::New(NULL);
	Context::Scope context_scope(context);

	// Load the dust libraries
	// Note: The libraries are generated at build time to bundle dust.js
	// rather than load it at runtime from an arbitrary location
	const char* lib_dust = reinterpret_cast<const char*>(lib_dust_js);
	const char* lib_compiler = reinterpret_cast<const char*>(lib_compiler_js);
	const char* lib_parser = reinterpret_cast<const char*>(lib_parser_js);
	const char* lib_helpers = reinterpret_cast<const char*>(lib_dust_helpers_js);

	eval(lib_dust);
	eval(lib_compiler);
	eval(lib_parser);
	eval(lib_helpers);

	// Get dust out of the global scope so we can bind it with C++ methods
	Handle<Object> global = context->Global();
	Handle<Object> dust = global->Get(String::New("dust"))->ToObject();

	dust->Set(String::New("onLoad"), FunctionTemplate::New(onLoad)->GetFunction());

	// Call dust.render with our arguments
	Handle<Value> cbargs[3];

	cbargs[0] = String::New(tmpl.c_str());
	cbargs[1] = mapToJson(model);
	cbargs[2] = FunctionTemplate::New(callback)->GetFunction();

	Handle<Function> render = Handle<Function>::Cast(dust->Get(String::New("render")));
	render->Call(dust, 3, cbargs);

	// Done!
	return 0;
}
Esempio n. 22
0
		Handle<Value> evalInContext(const Arguments& args) {
			if (args.Length() < 3) {
				return ThrowException(Exception::TypeError(String::New("evalInContext takes 3 arguments.")));
			}
			
			if (!args[1]->IsObject()) {
				return ThrowException(Exception::TypeError(String::New("evalInContext expects an object as second argument.")));
			}
			
			HandleScope scope;
			
			Persistent<Context> context = Context::New();
			Context::Scope context_scope(context);

			Local<Object> global = context->Global();

			Local<Object> jscontext = args[1]->ToObject()->Clone();
			Local<Array> names = jscontext->GetOwnPropertyNames();
			for (int i = 0; i < names->Length(); i++) {
				global->Set(names->Get(i), jscontext->Get(names->Get(i)));
			}

			TryCatch tc;
			
			Local<Script> compiled = Script::Compile(args[0]->ToString(), args[2]->ToString());
			
			if (compiled.IsEmpty()) {
				return tc.ReThrow();
			}
			
			Handle<Value> value = compiled->Run();
			
			if (value.IsEmpty()) {
				return tc.ReThrow();
			}

			
			return scope.Close(value);
		}
Esempio n. 23
0
Persistent<Function> GetFunctionHandle(const char * filename, const char * functionName)
{
	HandleScope handle_scope;
	Persistent<Function> function;


	Handle<ObjectTemplate> objectTemplate = ObjectTemplate::New();


	Handle<Script> script = ReadAndCompileScript(filename);

	Handle<String> processName = String::New(functionName);
	Handle<Value> process_val = g_context->Global()->Get(processName);

	// bail if we couldn't find the function
	if( !process_val->IsFunction()) 
		return function;

	Handle<Function> process_fun = Handle<Function>::Cast(process_val);
	function = Persistent<Function>::New(process_fun);

	return function;

}
Esempio n. 24
0
int main(int argc, char* argv[])
{
	HandleScope handleScope;

	Local<FunctionTemplate> logFunction = FunctionTemplate::New(LogCallback);
	Local<ObjectTemplate> globals = ObjectTemplate::New();
	globals->Set(String::New("Log"),logFunction);

	Handle<Context> context = Context::New(NULL,globals);
	g_context = Persistent<Context>::New(context); // make the context global
	Context::Scope scope(g_context);
	
	Persistent<Function> updateFunction = GetFunctionHandle("test.js","Update");
	printf("\n\n... Running Code ...\n\n");
	const int numArgs=0;
	Handle<Value> * args = NULL;
	Handle<Value> result = updateFunction->Call( g_context->Global(), numArgs, args);
	
	// Convert the result to an ASCII string and print it.
	String::AsciiValue ascii(result);
	printf("The Result is %s\n", *ascii);

	return 0;
}
Esempio n. 25
0
void
test_obj_tmplexn() {
  HandleScope scope;

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

  Handle<ObjectTemplate> tmpl = ObjectTemplate::New();
  tmpl->SetNamedPropertyHandler(NamedGetterThrows, NamedSetterThrows, 0, NamedDeleterThrows);
  tmpl->SetIndexedPropertyHandler(IndexedGetterThrows, IndexedSetterThrows, 0, IndexedDeleterThrows);
  Handle<Object> obj = tmpl->NewInstance();
  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; }"
                                      "try { delete testobj.myprop; } catch (e) { n += e; };"
                                      "try { testobj[4]; } catch (e) { n += e; };"
                                      "try { testobj[5] = (n+9); } catch (e) { n += e; }"
                                      "try { delete testobj[6]; } 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(i, 21);
  context.Dispose();
}
Esempio n. 26
0
Handle<Value> WrappedScript::EvalMachine(const Arguments& args)
{
	HandleScope scope;

	if (input_flag == compileCode && args.Length() < 1) {
		return ThrowException(Exception::TypeError(String::New("needs at least 'code' argument.")));
	}

	const int sandbox_index = input_flag == compileCode ? 1 : 0;
	if (context_flag == userContext && args.Length() < (sandbox_index + 1)) {
		return ThrowException(Exception::TypeError(String::New("needs a 'context' argument.")));
	}

	Local<String> code;
	if (input_flag == compileCode) code = args[0]->ToString();

	Local<Object> sandbox;
	if (context_flag == newContext) {
		sandbox = args[sandbox_index]->IsObject() ? args[sandbox_index]->ToObject() : Object::New();
	} else if (context_flag == userContext) {
		sandbox = args[sandbox_index]->ToObject();
	}

	const int filename_index = sandbox_index + (context_flag == newContext ? 1 : 0);
	Local<String> filename =
			args.Length() > filename_index ? args[filename_index]->ToString() : String::New("evalmachine.<anonymous>");

	const int display_error_index = args.Length() - 1;
	bool display_error = false;
	if (args.Length() > display_error_index && args[display_error_index]->IsBoolean()
		&& args[display_error_index]->BooleanValue() == true) {
		display_error = true;
	}

	Persistent<Context> context;

	Local<Array> keys;
	unsigned int i;
	WrappedContext *nContext = NULL;
	Local<Object> contextArg;

	if (context_flag == newContext) {
		// Create the new context
		context = Context::New();

	} else if (context_flag == userContext) {
		// Use the passed in context
		contextArg = args[sandbox_index]->ToObject();
		nContext = NativeObject::Unwrap<WrappedContext>(contextArg);
		context = nContext->GetV8Context();
	}

	// New and user context share code. DRY it up.
	if (context_flag == userContext || context_flag == newContext) {
		// Enter the context
		context->Enter();

		// Call the initCallback, if it exists
		if (nContext) {
			Persistent<Function> initCallback = nContext->GetInitCallback();

			if (!initCallback.IsEmpty()) {
				Handle<Value> callbackArgs[] = { contextArg, context->Global() };
				initCallback->Call(contextArg, 2, callbackArgs);
			}
		}

		// Copy everything from the passed in sandbox (either the persistent
		// context for runInContext(), or the sandbox arg to runInNewContext()).
		keys = sandbox->GetPropertyNames();

		for (i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = sandbox->Get(key);
			if (value == sandbox) {
				value = context->Global();
			}
			context->Global()->Set(key, value);
		}
	}

	Handle<Value> result;
	Handle<Script> script;

	if (input_flag == compileCode) {
		// well, here WrappedScript::New would suffice in all cases, but maybe
		// Compile has a little better performance where possible
		script = output_flag == returnResult ? Script::Compile(code, filename) : Script::New(code, filename);
		if (script.IsEmpty()) {
			// Hack because I can't get a proper stacktrace on SyntaxError
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		} else if (n_script->script_.IsEmpty()) {
			return ThrowException(Exception::Error(String::New("'this' must be a result of previous "
				"new Script(code) call.")));
		}

		script = n_script->script_;
	}

	if (output_flag == returnResult) {
		result = script->Run();
		if (result.IsEmpty()) {
			if (context_flag == newContext) {
				context->DetachGlobal();
				context->Exit();
				context.Dispose();
			}
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		}
		n_script->script_ = Persistent<Script>::New(script);
		result = args.This();
	}

	if (context_flag == userContext || context_flag == newContext) {
		// success! copy changes back onto the sandbox object.
		keys = context->Global()->GetPropertyNames();
		for (i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = context->Global()->Get(key);
			if (value == context->Global()) {
				value = sandbox;
			}
			sandbox->Set(key, value);
		}
	}

	if (context_flag == newContext) {
		// Clean up, clean up, everybody everywhere!
		context->DetachGlobal();
		context->Exit();
		context.Dispose();
	} else if (context_flag == userContext) {
		// Exit the passed in context.
		context->Exit();
	}

	if (result->IsObject()) {
		Local<Context> creation = result->ToObject()->CreationContext();
	}

	return result == args.This() ? result : scope.Close(result);
}
void CanvasContextV8Bindings::loadScript(const std::string& _filename, OgreCanvas::CanvasContext* _canvasContext, OgreCanvas::CanvasLogger* _console)
{
	CanvasContextV8Bindings::context2D = _canvasContext;
	
	HandleScope handle_scope;
	
	//Console :
		
		//template
		Handle<FunctionTemplate> consoleTemplate = FunctionTemplate::New();
		consoleTemplate->SetClassName(v8::String::New("Console"));
		CanvasContextV8Bindings::consoleTemplate = Persistent<FunctionTemplate>::New(consoleTemplate);

		//prototype
		Handle<ObjectTemplate> consolePrototype = consoleTemplate->PrototypeTemplate();

		//attaching method
		consolePrototype->Set("log", FunctionTemplate::New(log));

		//creating instance
		Handle<ObjectTemplate> consoleInstance = consoleTemplate->InstanceTemplate();
		consoleInstance->SetInternalFieldCount(1);

	//Image :
		
		//template
		Handle<FunctionTemplate> imageTemplate = FunctionTemplate::New();
		imageTemplate->SetClassName(v8::String::New("Image"));
		CanvasContextV8Bindings::imageTemplate = Persistent<FunctionTemplate>::New(imageTemplate);

		//prototype
		Handle<ObjectTemplate> imagePrototype = imageTemplate->PrototypeTemplate();

		//creating instance
		Handle<ObjectTemplate> imageInstance = imageTemplate->InstanceTemplate();
		imageInstance->SetInternalFieldCount(1);

	//Canvas gradient :
		
		//template
		Handle<FunctionTemplate> canvasGradientTemplate = FunctionTemplate::New();
		canvasGradientTemplate->SetClassName(v8::String::New("CanvasGradient"));
		CanvasContextV8Bindings::canvasGradientTemplate = Persistent<FunctionTemplate>::New(canvasGradientTemplate);

		//prototype
		Handle<ObjectTemplate> canvasGradientPrototype = canvasGradientTemplate->PrototypeTemplate();

		//creating instance
		Handle<ObjectTemplate> canvasGradientInstance = canvasGradientTemplate->InstanceTemplate();
		canvasGradientInstance->SetInternalFieldCount(1);

		//attaching method
		canvasGradientPrototype->Set("addColorStop", FunctionTemplate::New(addColorStop));

	//Canvas Pattern :

		//template
		Handle<FunctionTemplate> canvasPatternTemplate = FunctionTemplate::New();
		canvasPatternTemplate->SetClassName(v8::String::New("CanvasPattern"));
		CanvasContextV8Bindings::canvasPatternTemplate = Persistent<FunctionTemplate>::New(canvasPatternTemplate);

		//prototype
		Handle<ObjectTemplate> canvasPatternPrototype = canvasPatternTemplate->PrototypeTemplate();
		
		//creating instance
		Handle<ObjectTemplate> canvasPatternInstance = canvasPatternTemplate->InstanceTemplate();
		canvasPatternInstance->SetInternalFieldCount(1);

	//Canvas context :

		//template
		Handle<FunctionTemplate> canvasContextTemplate = FunctionTemplate::New();
		canvasContextTemplate->SetClassName(v8::String::New("CanvasContext"));
	
		//prototype
		Handle<ObjectTemplate> canvasContextPrototype = canvasContextTemplate->PrototypeTemplate();

		//attaching method

			//2D Context
			canvasContextPrototype->Set("save",        FunctionTemplate::New(save));
			canvasContextPrototype->Set("restore",     FunctionTemplate::New(restore));

			//Transformation
			canvasContextPrototype->Set("scale",        FunctionTemplate::New(scale));
			canvasContextPrototype->Set("rotate",       FunctionTemplate::New(rotate));
			canvasContextPrototype->Set("translate",    FunctionTemplate::New(translate));
			canvasContextPrototype->Set("transform",    FunctionTemplate::New(transform));
			canvasContextPrototype->Set("setTransform", FunctionTemplate::New(setTransform));
			
			//Image drawing
			canvasContextPrototype->Set("drawImage",    FunctionTemplate::New(drawImage));		

			//Colors, styles and shadows
			canvasContextPrototype->Set("createLinearGradient", FunctionTemplate::New(createLinearGradient));
			canvasContextPrototype->Set("createRadialGradient", FunctionTemplate::New(createRadialGradient));
			canvasContextPrototype->Set("createPattern",        FunctionTemplate::New(createPattern));

			//Paths
			canvasContextPrototype->Set("beginPath",        FunctionTemplate::New(beginPath));
			canvasContextPrototype->Set("closePath",        FunctionTemplate::New(closePath));		
			canvasContextPrototype->Set("fill",             FunctionTemplate::New(fill));
			canvasContextPrototype->Set("stroke",           FunctionTemplate::New(stroke));
			canvasContextPrototype->Set("clip",             FunctionTemplate::New(clip));

			canvasContextPrototype->Set("moveTo",           FunctionTemplate::New(moveTo));
			canvasContextPrototype->Set("lineTo",           FunctionTemplate::New(lineTo));
			canvasContextPrototype->Set("quadraticCurveTo", FunctionTemplate::New(quadraticCurveTo));
			canvasContextPrototype->Set("bezierCurveTo",    FunctionTemplate::New(bezierCurveTo));
			canvasContextPrototype->Set("arcTo",            FunctionTemplate::New(arcTo));
			canvasContextPrototype->Set("arc",              FunctionTemplate::New(arc));
			canvasContextPrototype->Set("rect",             FunctionTemplate::New(rect));
			canvasContextPrototype->Set("isPointInPath",    FunctionTemplate::New(isPointInPath));

			//Text
			canvasContextPrototype->Set("fillText",    FunctionTemplate::New(fillText));
			canvasContextPrototype->Set("strokeText",  FunctionTemplate::New(strokeText));
			canvasContextPrototype->Set("measureText", FunctionTemplate::New(measureText));

			//Rectangles
			canvasContextPrototype->Set("clearRect",   FunctionTemplate::New(clearRect));
			canvasContextPrototype->Set("fillRect",    FunctionTemplate::New(fillRect));
			canvasContextPrototype->Set("strokeRect",  FunctionTemplate::New(strokeRect));

			//New
			canvasContextPrototype->Set("saveToPNG",   FunctionTemplate::New(saveToPNG));		
			canvasContextPrototype->Set("clear",       FunctionTemplate::New(clear));

		//creating instance
		Handle<ObjectTemplate> canvasContextInstance = canvasContextTemplate->InstanceTemplate();
		canvasContextInstance->SetInternalFieldCount(1);

		//attaching properties

			//Compositing
			canvasContextInstance->SetAccessor(v8::String::New("globalAlpha"), getterGlobalAlpha, setterGlobalAlpha);
			canvasContextInstance->SetAccessor(v8::String::New("globalCompositeOperation"), getterGlobalCompositeOperation, setterGlobalCompositeOperation);
			
			//Line styles
			canvasContextInstance->SetAccessor(v8::String::New("lineWidth"),   getterLineWidth,  setterLineWidth);
			canvasContextInstance->SetAccessor(v8::String::New("lineCap"),     getterLineCap,    setterLineCap);
			canvasContextInstance->SetAccessor(v8::String::New("lineJoin"),    getterLineJoin,   setterLineJoin);
			canvasContextInstance->SetAccessor(v8::String::New("miterLimit"),  getterMiterLimit, setterMiterLimit);
			canvasContextInstance->SetAccessor(v8::String::New("lineDash"),    getterLineDash,   setterLineDash);
			
			//Colors, styles and shadows
			canvasContextInstance->SetAccessor(v8::String::New("fillStyle"),     getterFillStyle,     setterFillStyle);
			canvasContextInstance->SetAccessor(v8::String::New("strokeStyle"),   getterStrokeStyle,   setterStrokeStyle);
			canvasContextInstance->SetAccessor(v8::String::New("shadowOffsetX"), getterShadowOffsetX, setterShadowOffsetX);
			canvasContextInstance->SetAccessor(v8::String::New("shadowOffsetY"), getterShadowOffsetY, setterShadowOffsetY);
			canvasContextInstance->SetAccessor(v8::String::New("shadowBlur"),    getterShadowBlur,    setterShadowBlur);
			canvasContextInstance->SetAccessor(v8::String::New("shadowColor"),   getterShadowColor,   setterShadowColor);

			//Text
			canvasContextInstance->SetAccessor(v8::String::New("font"),         getterFont,         setterFont);
			canvasContextInstance->SetAccessor(v8::String::New("textAlign"),    getterTextAlign,    setterTextAlign);
			canvasContextInstance->SetAccessor(v8::String::New("textBaseline"), getterTextBaseline, setterTextBaseline);
			
			//New
			canvasContextInstance->SetAccessor(v8::String::New("antialiasing"), getterAntiAliasing, setterAntiAliasing);

	//Image
	Handle<ObjectTemplate> global = ObjectTemplate::New();
	global->Set(String::New("loadImage"), FunctionTemplate::New(loadImage));

	Persistent<Context> context = Context::New(NULL, global);
	CanvasContextV8Bindings::contextV8 = context;

	Context::Scope context_scope(context);

		//building link between js 'ctx' variable and c++ _canvasContext variable
		Handle<Function> canvasContextConstructor = canvasContextTemplate->GetFunction();
		Local<Object> obj = canvasContextConstructor->NewInstance();
		obj->SetInternalField(0, External::New(_canvasContext));
		context->Global()->Set(v8::String::New("ctx"), obj);

		//building link between js 'console' variable and c++ _console variable
		Handle<Function> consoleConstructor = consoleTemplate->GetFunction();
		Local<Object> obj2 = consoleConstructor->NewInstance();
		obj2->SetInternalField(0, External::New(_console));
		context->Global()->Set(v8::String::New("console"), obj2);

	Handle<v8::String> source = v8::String::New(readScript(_filename).c_str());
	Handle<Script> script = Script::Compile(source);
	Handle<Value> result = script->Run();
	/*
	CanvasContextV8Bindings::canvasGradientTemplate.Dispose();
	CanvasContextV8Bindings::canvasPatternTemplate.Dispose();
	CanvasContextV8Bindings::imageTemplate.Dispose();
	*/
}
Esempio n. 28
0
bool v8test_userobjectcompare()
{
    BEGINTEST();

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

    V8::SetUserObjectComparisonCallbackFunction(UserObjectComparison);

    Local<ObjectTemplate> ot = ObjectTemplate::New();
    ot->MarkAsUseUserObjectComparison();

    Local<Object> uoc1 = ot->NewInstance();
    Local<Object> uoc2 = ot->NewInstance();
    context->Global()->Set(String::New("uoc1a"), uoc1);
    context->Global()->Set(String::New("uoc1b"), uoc1);
    context->Global()->Set(String::New("uoc2"), uoc2);
    Local<Object> obj1 = Object::New();
    context->Global()->Set(String::New("obj1a"), obj1);
    context->Global()->Set(String::New("obj1b"), obj1);
    context->Global()->Set(String::New("obj2"), Object::New());
    Local<String> string1 = String::New("Hello World");
    context->Global()->Set(String::New("string1a"), string1);
    context->Global()->Set(String::New("string1b"), string1);
    context->Global()->Set(String::New("string2"), v8::String::New("Goodbye World"));

    // XXX Opportunity for optimization - don't invoke user callback if objects are
    // equal.  
#if 0
    userObjectComparisonCalled = 0; userObjectComparisonReturn = false;
    VERIFY(true == runscript("uoc1a == uoc1b"));
    VERIFY(userObjectComparisonCalled == 0);
#endif

    // Comparing two uoc objects invokes uoc
    userObjectComparisonCalled = 0; 
    userObjectComparisonReturn = false;
    VERIFY(false == runscript("uoc1a == uoc2"));
    VERIFY(userObjectComparisonCalled == 1);

    VERIFY(false == runscript("uoc2 == uoc1a"));
    VERIFY(userObjectComparisonCalled == 2);
    userObjectComparisonReturn = true;
    VERIFY(true == runscript("uoc1a == uoc2"));
    VERIFY(userObjectComparisonCalled == 3);
    VERIFY(true == runscript("uoc2 == uoc1a"));
    VERIFY(userObjectComparisonCalled == 4);

    // != on two uoc object invokes uoc
    userObjectComparisonCalled = 0; 
    userObjectComparisonReturn = false;
    VERIFY(true == runscript("uoc1a != uoc2"));
    VERIFY(userObjectComparisonCalled == 1);
    VERIFY(true == runscript("uoc2 != uoc1a"));
    VERIFY(userObjectComparisonCalled == 2);
    userObjectComparisonReturn = true;
    VERIFY(false == runscript("uoc1a != uoc2"));
    VERIFY(userObjectComparisonCalled == 3);
    VERIFY(false == runscript("uoc2 != uoc1a"));
    VERIFY(userObjectComparisonCalled == 4);

    // Comparison against a non-object doesn't invoke uoc
    userObjectComparisonCalled = 0; 
    userObjectComparisonReturn = false;
    VERIFY(false == runscript("uoc1a == string1a"));
    VERIFY(userObjectComparisonCalled == 0);
    VERIFY(false == runscript("string1a == uoc1a"));
    VERIFY(userObjectComparisonCalled == 0);
    VERIFY(false == runscript("2 == uoc1a"));
    VERIFY(userObjectComparisonCalled == 0);
    VERIFY(true == runscript("uoc1a != string1a"));
    VERIFY(userObjectComparisonCalled == 0);
    VERIFY(true == runscript("string1a != uoc1a"));
    VERIFY(userObjectComparisonCalled == 0);
    VERIFY(true == runscript("2 != uoc1a"));
    VERIFY(userObjectComparisonCalled == 0);
    
    // Comparison against a non-uoc-object still invokes uoc
    userObjectComparisonCalled = 0; 
    userObjectComparisonReturn = false;
    VERIFY(false == runscript("uoc1a == obj1a"));
    VERIFY(userObjectComparisonCalled == 1);
    VERIFY(false == runscript("obj1a == uoc1a"));
    VERIFY(userObjectComparisonCalled == 2);
    userObjectComparisonReturn = true;
    VERIFY(true == runscript("uoc1a == obj1a"));
    VERIFY(userObjectComparisonCalled == 3);
    VERIFY(true == runscript("obj1a == uoc1a"));
    VERIFY(userObjectComparisonCalled == 4);

    // != comparison against a non-uoc-object still invokes uoc
    userObjectComparisonCalled = 0; 
    userObjectComparisonReturn = false;
    VERIFY(true == runscript("uoc1a != obj1a"));
    VERIFY(userObjectComparisonCalled == 1);
    VERIFY(true == runscript("obj1a != uoc1a"));
    VERIFY(userObjectComparisonCalled == 2);
    userObjectComparisonReturn = true;
    VERIFY(false == runscript("uoc1a != obj1a"));
    VERIFY(userObjectComparisonCalled == 3);
    VERIFY(false == runscript("obj1a != uoc1a"));
    VERIFY(userObjectComparisonCalled == 4);

    // Comparing two non-uoc objects does not invoke uoc
    userObjectComparisonCalled = 0; 
    userObjectComparisonReturn = false;
    VERIFY(true == runscript("obj1a == obj1a"));
    VERIFY(true == runscript("obj1a == obj1b"));
    VERIFY(false == runscript("obj1a == obj2"));
    VERIFY(false == runscript("obj1a == string1a"));
    VERIFY(true == runscript("string1a == string1a"));
    VERIFY(true == runscript("string1a == string1b"));
    VERIFY(false == runscript("string1a == string2"));
    VERIFY(userObjectComparisonCalled == 0);

    // Correct lhs and rhs passed to uoc
    userObjectComparisonCalled = 0; 
    userObjectComparisonReturn = false;
    SET_EXPECTED(uoc1, uoc2);
    VERIFY(false == runscript("uoc1a == uoc2"));
    VERIFY(true == expectedObjectsCompared);
    SET_EXPECTED(uoc2, uoc1);
    VERIFY(false == runscript("uoc2 == uoc1a"));
    VERIFY(true == expectedObjectsCompared);
    SET_EXPECTED(uoc1, uoc2);
    VERIFY(true == runscript("uoc1a != uoc2"));
    VERIFY(true == expectedObjectsCompared);
    SET_EXPECTED(uoc2, uoc1);
    VERIFY(true == runscript("uoc2 != uoc1a"));
    VERIFY(true == expectedObjectsCompared);
    SET_EXPECTED(uoc1, obj1);
    VERIFY(false == runscript("uoc1a == obj1a"));
    VERIFY(true == expectedObjectsCompared);
    SET_EXPECTED(obj1, uoc1);
    VERIFY(false == runscript("obj1a == uoc1a"));
    VERIFY(true == expectedObjectsCompared);

cleanup:
    V8::SetUserObjectComparisonCallbackFunction(0);
    context.Dispose();

    ENDTEST();
}
Esempio n. 29
0
int main(int argc, char* argv[]) {
	SDL_Init(SDL_INIT_EVERYTHING);

	V8::Initialize();
	isolate = Isolate::GetCurrent();
	HandleScope handle_scope(isolate);
	
	Persistent<Context> context = Context::New();
    Context::Scope context_scope(context);

	Local<Object> global = context->Global();
	
	Local<Object> sphere = Object::New();
	
	global->Set(String::New("sphere"), sphere);
	
	API::fs::Init(sphere);
	API::engine::Init(sphere);
	API::graphics::Init(sphere);
	API::events::Init(sphere);
	
	Local<Object> engine = sphere->Get(String::New("engine"))->ToObject();
	
	engine->Set(String::New("argc"), Integer::New(argc));
	Local<Array> js_argv = Array::New(argc);
	
	for (int i = 0; i < argc; i++) {
		js_argv->Set(Number::New(i), String::New(argv[i]));
	}

	engine->Set(String::New("argv"), js_argv);
	
	const char* gameScript = Files::readTextFile("system/sphere.js");
	
	if (gameScript == NULL) {
		debug("Error loading bootstrap script.\n");
		exit(1);
	}
	
	TryCatch trycatch;
	Local<Script> compiled = Script::Compile(String::New(gameScript), String::New("system/sphere.js"));
	
	if (compiled.IsEmpty()) {
		Handle<Value> exception = trycatch.Exception();
		String::Utf8Value exception_str(exception);
		printf("Exception: %s\n", *exception_str);
		exit(1);
	}
	
	Handle<Value> value = compiled->Run();
	
	if (value.IsEmpty()) {
		Handle<Object> exception = trycatch.Exception()->ToObject();
		Handle<String> str;
		if (exception->Has(String::New("stack"))) {
			str = exception->Get(String::New("stack"))->ToString();
		}
		else {
			str = exception->ToString();
		}
		String::Utf8Value exception_str(str);
		printf("Exception: %s\n", *exception_str);
		exit(1);
	}
	
	return 0;
}
Esempio n. 30
0
int main (int argc, char** argv) {
    signal(SIGSEGV, AnsiSignalHandler);
    //    printf("SILK V0.1\n");
    char *startup;
    const char *progName;
    signal(SIGSEGV, AnsiSignalHandler);
    signal(SIGINT, AnsiSignalHandler);

    if (argc < 2) {
        startup = readFile("/usr/local/silkjs/builtin/interpreter.js");
        if (!startup) {
            startup = readFile("/usr/share/silkjs/builtin/interpreter.js");
        }
        progName = "interpreter";
    }
    else {
        startup = readFile(argv[1]);
        progName = argv[1];
    }
    if (!startup) {
        printf("%s not found\n", argv[1]);
        exit(1);
    }
    if (startup[0] == '#' && startup[1] == '!') {
        startup[0] = startup[1] = '/';
    }
    
    // v8 command line switches
    const char *switches = "--harmony";
    V8::SetFlagsFromString(switches, strlen(switches));
    
    {
        //		Isolate *isolate = Isolate::New();
        //		isolate->Enter();
        //		Locker lock(isolate);
        Locker locker;
        HandleScope scope;

        init_global_object();
        V8::SetCaptureStackTraceForUncaughtExceptions(true, 50); // , StackTrace::kDetailed);
        context = Context::New(NULL, globalObject);
        Context::Scope context_scope(context);
        {
            Locker locker;
            //			Debug::SetDebugMessageDispatchHandler(debugger, true);
            //			Debug::EnableAgent("silkjs", 5858);

            Handle<Script>init = Script::New(String::New("global=this; module = {}; include('builtin/all.js');"), String::New("builtin"));
            init->Run();
            V8::SetCaptureStackTraceForUncaughtExceptions(true, 50, StackTrace::kDetailed);
            TryCatch tryCatch;
            mainScript = Persistent<Script>::New(Script::Compile(String::New(startup), String::New(progName)));
            if (mainScript.IsEmpty()) {
                ReportException(&tryCatch);
                exit(1);
            }
            Handle<Value>v = mainScript->Run();
            if (v.IsEmpty()) {
                ReportException(&tryCatch);
                exit(1);
            }
            Handle<String> process_name = String::New("main");
            Handle<Value> process_val = context->Global()->Get(process_name);
            if (!process_val.IsEmpty() && process_val->IsFunction()) {
                Handle<Function> process_fun = Handle<Function>::Cast(process_val);
                mainFunc = Persistent<Function>::New(process_fun);
                int ac = argc - 2;
                if (ac < 0) {
                    ac = 0;
                }
                Handle<Value>av[ac];
                for (int i = 2; i < argc; i++) {
                    av[i - 2] = String::New(argv[i]);
                }
                v = mainFunc->Call(context->Global(), ac, av);
                if (v.IsEmpty()) {
                    ReportException(&tryCatch);
                    exit(1);
                }
            }
        }
        context.Dispose();
    }
}