Initial commit

This commit is contained in:
Bassem Girgis
2018-12-20 17:34:07 -06:00
parent 7a2d899662
commit 81b4b9e273
34743 changed files with 5940233 additions and 0 deletions

View File

@@ -0,0 +1,72 @@
# ----------------------------------------------------------------
# Compile a custom javascript interpreter
# ----------------------------------------------------------------
#
# Note:
# There is no common CLI Javascript interpreter.
# V8 comes with one 'd8' which however does not provide a means
# to load extensions. Therefore, by default we use nodejs as
# environment.
# For testing native v8 and jsc extensions we provide our own
# interpreter (see 'Tools/javascript').
#
# ----------------------------------------------------------------
all: javascript
CC = @CC@
# HACK: under Mac OS X a g++ compiled interpreter is seg-faulting when loading module libraries
# with 'c++' it works... probably some missing flags?
JSCXX = @JSINTERPRETERCXX@
CPPFLAGS = @BOOST_CPPFLAGS@
CFLAGS = @PLATCFLAGS@
CXXFLAGS = @PLATCXXFLAGS@
LDFLAGS =
LINKFLAGS = @JSINTERPRETERLINKFLAGS@
ROOT_DIR = @ROOT_DIR@
JSINCLUDES = @JSCOREINC@ @JSV8INC@
JSDYNAMICLINKING = @JSCOREDYNAMICLINKING@ @JSV8DYNAMICLINKING@
JSV8ENABLED = @JSV8ENABLED@
JSCENABLED = @JSCENABLED@
srcdir = @srcdir@
ifneq (, $(V8_VERSION))
JSV8_VERSION=$(V8_VERSION)
else
JSV8_VERSION=0x031110
endif
# Regenerate Makefile if Makefile.in or config.status have changed.
Makefile: $(srcdir)/Makefile.in ../../config.status
cd ../.. && $(SHELL) ./config.status Tools/javascript/Makefile
# These settings are provided by 'configure' (see '/configure.in')
ifeq (1, $(JSV8ENABLED))
JS_INTERPRETER_SRC_V8 = v8_shell.cxx
JS_INTERPRETER_ENABLE_V8 = -DENABLE_V8 -DSWIG_V8_VERSION=$(JSV8_VERSION) -DV8_DEPRECATION_WARNINGS
endif
ifeq (1, $(JSCENABLED))
JS_INTERPRETER_SRC_JSC = jsc_shell.cxx
JS_INTERPRETER_ENABLE_JSC = -DENABLE_JSC
endif
JS_INTERPRETER_DEFINES = $(JS_INTERPRETER_ENABLE_JSC) $(JS_INTERPRETER_ENABLE_V8)
JS_INTERPRETER_SRC = javascript.cxx js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_INTERPRETER_SRC_V8)
JS_INTERPRETER_OBJS = $(JS_INTERPRETER_SRC:.cxx=.o)
%.o: $(srcdir)/%.cxx
$(JSCXX) $(JS_INTERPRETER_DEFINES) $(CPPFLAGS) $(CXXFLAGS) $(JSINCLUDES) -o $@ -c $<
javascript: $(JS_INTERPRETER_OBJS)
$(JSCXX) $^ $(CXXFLAGS) $(LDFLAGS) -o javascript $(JSDYNAMICLINKING) $(LINKFLAGS)
clean:
rm -f *.o
rm -f javascript
distclean: clean
rm -f Makefile

View File

@@ -0,0 +1,66 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <string>
#include <vector>
#include "js_shell.h"
void print_usage() {
std::cout << "javascript [-i] [-jsc|-v8] [-l module] <js-file>" << std::endl;
}
int main(int argc, char* argv[]) {
#if defined(JAVASCRIPT_INTERPRETER_STOP)
std::cout << "Attach your Debugger and press any key to continue" << std::endl;
std::cin.get();
#endif
std::string scriptPath = "";
bool interactive = false;
JSShell* shell = 0;
std::vector<std::string> modulePath;
modulePath.push_back(".");
for (int idx = 1; idx < argc; ++idx) {
if(strcmp(argv[idx], "-v8") == 0) {
shell = JSShell::Create(JSShell::V8);
} else if(strcmp(argv[idx], "-jsc") == 0) {
shell = JSShell::Create(JSShell::JSC);
} else if(strcmp(argv[idx], "-i") == 0) {
interactive = true;
} else if(strcmp(argv[idx], "-L") == 0) {
modulePath.push_back(argv[++idx]);
} else {
scriptPath = argv[idx];
}
}
if (shell == 0) {
shell = JSShell::Create();
}
shell->setModulePath(modulePath);
bool failed = false;
if(interactive) {
failed = !(shell->RunShell());
} else {
failed = !(shell->RunScript(scriptPath));
}
if (failed) {
delete shell;
printf("FAIL: Error during execution of script.\n");
return 1;
}
delete shell;
return 0;
}

View File

@@ -0,0 +1,156 @@
#include "js_shell.h"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef __GNUC__
#ifdef __APPLE__
#define LIBRARY_EXT ".bundle"
#else
#define LIBRARY_EXT ".so"
#endif
#include <dlfcn.h>
#define LOAD_LIBRARY(name) dlopen(name, RTLD_LAZY)
#define CLOSE_LIBRARY(handle) dlclose(handle)
#define LIBRARY_ERROR dlerror
#define LIBRARYFILE(name) std::string("lib").append(name).append(LIBRARY_EXT)
#else
#error "implement dll loading"
#endif
JSShell::~JSShell() {
for(std::vector<HANDLE>::iterator it = loaded_modules.begin();
it != loaded_modules.end(); ++it) {
HANDLE handle = *it;
CLOSE_LIBRARY(handle);
}
}
// TODO: this could be done more intelligent...
// - can we achieve source file relative loading?
// - better path resolution
std::string JSShell::LoadModule(const std::string& name, HANDLE* library) {
// works only for posix like OSs
size_t pathIdx = name.find_last_of("/");
std::string lib_name;
std::string module_name;
if (pathIdx == std::string::npos) {
module_name = name;
lib_name = std::string(name).append(LIBRARY_EXT);
} else {
std::string path = name.substr(0, pathIdx+1);
module_name = name.substr(pathIdx+1);
lib_name = path.append(module_name).append(LIBRARY_EXT);
}
std::string lib_path;
HANDLE handle = 0;
for (int i = 0; i < module_path.size(); ++i) {
lib_path = module_path[i] + "/" + lib_name;
if (access( lib_path.c_str(), F_OK ) != -1) {
handle = LOAD_LIBRARY(lib_path.c_str());
}
}
if(handle == 0) {
std::cerr << "Could not find module " << lib_path << ":"
<< std::endl << LIBRARY_ERROR() << std::endl;
return 0;
}
loaded_modules.push_back(handle);
*library = handle;
return module_name;
}
bool JSShell::RunScript(const std::string& scriptPath) {
std::string source = ReadFile(scriptPath);
if(!InitializeEngine()) return false;
// Node.js compatibility: make `print` available as `console.log()`
ExecuteScript("var console = {}; console.log = print;", "<console>");
if(!ExecuteScript(source, scriptPath)) {
return false;
}
return DisposeEngine();
}
bool JSShell::RunShell() {
if(!InitializeEngine()) return false;
static const int kBufferSize = 1024;
while (true) {
char buffer[kBufferSize];
printf("> ");
char* str = fgets(buffer, kBufferSize, stdin);
if (str == NULL) break;
std::string source(str);
ExecuteScript(source, "(shell)");
}
printf("\n");
return true;
}
std::string JSShell::ReadFile(const std::string& fileName)
{
std::string script;
std::ifstream file(fileName.c_str());
if (file.is_open()) {
while ( file.good() ) {
std::string line;
getline(file, line);
script.append(line);
script.append("\n");
}
file.close();
} else {
std::cout << "Unable to open file " << fileName << "." << std::endl;
}
return script;
}
#ifdef ENABLE_JSC
extern JSShell* JSCShell_Create();
#endif
#ifdef ENABLE_V8
extern JSShell* V8Shell_Create();
#endif
typedef JSShell*(*ShellFactory)();
static ShellFactory js_shell_factories[2] = {
#ifdef ENABLE_JSC
JSCShell_Create,
#else
0,
#endif
#ifdef ENABLE_V8
V8Shell_Create,
#else
0,
#endif
};
JSShell *JSShell::Create(Engine engine) {
if(js_shell_factories[engine] == 0) {
throw "Engine not available.";
}
return js_shell_factories[engine]();
}

View File

@@ -0,0 +1,53 @@
#ifndef JS_SHELL_H
#define JS_SHELL_H
#include <vector>
#include <string>
typedef void* HANDLE;
typedef void* MODULE;
class JSShell {
public:
enum Engine {
JSC = 0,
V8
};
public:
JSShell() {}
virtual ~JSShell() = 0;
static JSShell* Create(Engine engine = JSC);
std::string LoadModule(const std::string& name, HANDLE* library);
virtual bool RunScript(const std::string& scriptPath);
virtual bool RunShell();
void setModulePath(const std::vector<std::string>& modulePath) {
module_path = modulePath;
}
protected:
virtual bool InitializeEngine() = 0;
virtual bool ExecuteScript(const std::string& source, const std::string& scriptPath) = 0;
virtual bool DisposeEngine() = 0;
static std::string ReadFile(const std::string& fileName);
protected:
std::vector<HANDLE> loaded_modules;
std::vector<std::string> module_path;
};
#endif // JS_SHELL_H

View File

@@ -0,0 +1,233 @@
#include <JavaScriptCore/JavaScript.h>
#include "js_shell.h"
#include <iostream>
#include <stdio.h>
#ifdef __GNUC__
#include <dlfcn.h>
#define LOAD_SYMBOL(handle, name) dlsym(handle, name)
#else
#error "implement dll loading"
#endif
class JSCShell: public JSShell {
typedef int (*JSCIntializer)(JSGlobalContextRef context, JSObjectRef *module);
public:
JSCShell() {};
virtual ~JSCShell();
protected:
virtual bool InitializeEngine();
virtual bool ExecuteScript(const std::string& source, const std::string& scriptPath);
virtual bool DisposeEngine();
private:
JSObjectRef Import(const std::string &moduleName);
static JSValueRef Print(JSContextRef context, JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex);
static JSValueRef Require(JSContextRef context, JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex);
static bool RegisterFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback cbFunction);
static void PrintError(JSContextRef, JSValueRef);
private:
JSGlobalContextRef context;
};
JSCShell::~JSCShell() {
if(context != 0) {
JSGlobalContextRelease(context);
context = 0;
}
}
bool JSCShell::InitializeEngine() {
if(context != 0) {
JSGlobalContextRelease(context);
context = 0;
}
// TODO: check for initialization errors
context = JSGlobalContextCreate(NULL);
if(context == 0) return false;
JSObjectRef globalObject = JSContextGetGlobalObject(context);
// store this for later use
JSClassDefinition __shell_classdef__ = JSClassDefinition();
JSClassRef __shell_class__ = JSClassCreate(&__shell_classdef__);
JSObjectRef __shell__ = JSObjectMake(context, __shell_class__, 0);
bool success = JSObjectSetPrivate(__shell__, (void*) (long) this);
if (!success) {
std::cerr << "Could not register the shell in the Javascript context" << std::endl;
return false;
}
JSStringRef shellKey = JSStringCreateWithUTF8CString("__shell__");
JSObjectSetProperty(context, globalObject, shellKey, __shell__, kJSPropertyAttributeReadOnly, NULL);
JSStringRelease(shellKey);
JSCShell::RegisterFunction(context, globalObject, "print", JSCShell::Print);
JSCShell::RegisterFunction(context, globalObject, "require", JSCShell::Require);
return true;
}
bool JSCShell::ExecuteScript(const std::string& source, const std::string& scriptPath) {
JSStringRef jsScript;
JSStringRef sourceURL;
JSValueRef ex;
jsScript = JSStringCreateWithUTF8CString(source.c_str());
sourceURL = JSStringCreateWithUTF8CString(scriptPath.c_str());
JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, sourceURL, 0, &ex);
JSStringRelease(jsScript);
if (jsResult == NULL && ex != NULL) {
JSCShell::PrintError(context, ex);
return false;
}
return true;
}
bool JSCShell::DisposeEngine() {
JSGlobalContextRelease(context);
context = 0;
return true;
}
JSValueRef JSCShell::Print(JSContextRef context, JSObjectRef object,
JSObjectRef globalobj, size_t argc,
const JSValueRef args[], JSValueRef* ex) {
if (argc > 0)
{
JSStringRef string = JSValueToStringCopy(context, args[0], NULL);
size_t numChars = JSStringGetMaximumUTF8CStringSize(string);
char *stringUTF8 = new char[numChars];
JSStringGetUTF8CString(string, stringUTF8, numChars);
printf("%s\n", stringUTF8);
delete[] stringUTF8;
}
return JSValueMakeUndefined(context);
}
// Attention: this feature should not create too high expectations.
// It is only capable of loading things relative to the execution directory
// and not relative to the parent script.
JSValueRef JSCShell::Require(JSContextRef context, JSObjectRef object,
JSObjectRef globalObj, size_t argc,
const JSValueRef args[], JSValueRef* ex) {
JSObjectRef module;
JSStringRef shellKey = JSStringCreateWithUTF8CString("__shell__");
JSValueRef shellAsVal = JSObjectGetProperty(context, globalObj, shellKey, NULL);
JSStringRelease(shellKey);
JSObjectRef shell = JSValueToObject(context, shellAsVal, 0);
JSCShell *_this = (JSCShell*) (long) JSObjectGetPrivate(shell);
if (argc > 0)
{
JSStringRef string = JSValueToStringCopy(context, args[0], NULL);
size_t numChars = JSStringGetMaximumUTF8CStringSize(string);
char *stringUTF8 = new char[numChars];
JSStringGetUTF8CString(string, stringUTF8, numChars);
std::string modulePath(stringUTF8);
module = _this->Import(modulePath);
delete[] stringUTF8;
}
if (module) {
return module;
} else {
printf("Ooops.\n");
return JSValueMakeUndefined(context);
}
}
JSObjectRef JSCShell::Import(const std::string& module_path) {
HANDLE library;
std::string module_name = LoadModule(module_path, &library);
if (library == 0) {
printf("Could not load module.");
return 0;
}
std::string symname = std::string(module_name).append("_initialize");
JSCIntializer init_function = reinterpret_cast<JSCIntializer>((long) LOAD_SYMBOL(library, symname.c_str()));
if(init_function == 0) {
printf("Could not find module's initializer function.");
return 0;
}
JSObjectRef module;
init_function(context, &module);
return module;
}
bool JSCShell::RegisterFunction(JSGlobalContextRef context, JSObjectRef object,
const char* functionName, JSObjectCallAsFunctionCallback callback) {
JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName);
JSObjectSetProperty(context, object, js_functionName,
JSObjectMakeFunctionWithCallback(context, js_functionName, callback),
kJSPropertyAttributeNone, NULL);
JSStringRelease(js_functionName);
return true;
}
void JSCShell::PrintError(JSContextRef ctx, JSValueRef err) {
char *buffer;
size_t length;
JSStringRef string = JSValueToStringCopy(ctx, err, 0);
length = JSStringGetLength(string);
buffer = new char[length+1];
JSStringGetUTF8CString(string, buffer, length+1);
std::string errMsg(buffer);
JSStringRelease(string);
delete[] buffer;
JSObjectRef errObj = JSValueToObject(ctx, err, 0);
if(errObj == 0) {
std::cerr << errMsg << std::endl;
return;
}
JSStringRef sourceURLKey = JSStringCreateWithUTF8CString("sourceURL");
JSStringRef sourceURLStr = JSValueToStringCopy(ctx, JSObjectGetProperty(ctx, errObj, sourceURLKey, 0), 0);
length = JSStringGetLength(sourceURLStr);
buffer = new char[length+1];
JSStringGetUTF8CString(sourceURLStr, buffer, length+1);
std::string sourceURL(buffer);
delete[] buffer;
JSStringRelease(sourceURLStr);
JSStringRelease(sourceURLKey);
JSStringRef lineKey = JSStringCreateWithUTF8CString("line");
JSValueRef jsLine = JSObjectGetProperty(ctx, errObj, lineKey, 0);
int line = (int) JSValueToNumber(ctx, jsLine, 0);
JSStringRelease(lineKey);
std::cerr << sourceURL << ":" << line << ":" << errMsg << std::endl;
}
JSShell* JSCShell_Create() {
return new JSCShell();
}

View File

@@ -0,0 +1,388 @@
#include <assert.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <v8.h>
#include <vector>
#include "js_shell.h"
typedef int (*V8ExtensionInitializer) (v8::Handle<v8::Object> module);
// Note: these typedefs and defines are used to deal with v8 API changes since version 3.19.00
#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903)
typedef v8::Handle<v8::Value> SwigV8ReturnValue;
typedef v8::Arguments SwigV8Arguments;
typedef v8::AccessorInfo SwigV8PropertyCallbackInfo;
#define SWIGV8_RETURN(val) return scope.Close(val)
#define SWIGV8_RETURN_INFO(val, info) return scope.Close(val)
#else
typedef void SwigV8ReturnValue;
typedef v8::FunctionCallbackInfo<v8::Value> SwigV8Arguments;
typedef v8::PropertyCallbackInfo<v8::Value> SwigV8PropertyCallbackInfo;
#define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return
#define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return
#endif
#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032117)
#define SWIGV8_HANDLESCOPE() v8::HandleScope scope
#define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope
#define SWIGV8_ESCAPE(val) return scope.Close(val)
#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032318)
#define SWIGV8_HANDLESCOPE() v8::HandleScope scope(v8::Isolate::GetCurrent());
#define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope(v8::Isolate::GetCurrent());
#define SWIGV8_ESCAPE(val) return scope.Close(val)
#else
#define SWIGV8_HANDLESCOPE() v8::HandleScope scope(v8::Isolate::GetCurrent());
#define SWIGV8_HANDLESCOPE_ESC() v8::EscapableHandleScope scope(v8::Isolate::GetCurrent());
#define SWIGV8_ESCAPE(val) return scope.Escape(val)
#endif
#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032318)
#define SWIGV8_CURRENT_CONTEXT() v8::Context::GetCurrent()
#define SWIGV8_STRING_NEW(str) v8::String::New(str)
#define SWIGV8_FUNCTEMPLATE_NEW(func) v8::FunctionTemplate::New(func)
#define SWIGV8_OBJECT_NEW() v8::Object::New()
#define SWIGV8_EXTERNAL_NEW(val) v8::External::New(val)
#define SWIGV8_UNDEFINED() v8::Undefined()
#else
#define SWIGV8_CURRENT_CONTEXT() v8::Isolate::GetCurrent()->GetCurrentContext()
#define SWIGV8_STRING_NEW(str) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), str)
#define SWIGV8_FUNCTEMPLATE_NEW(func) v8::FunctionTemplate::New(v8::Isolate::GetCurrent(), func)
#define SWIGV8_OBJECT_NEW() v8::Object::New(v8::Isolate::GetCurrent())
#define SWIGV8_EXTERNAL_NEW(val) v8::External::New(v8::Isolate::GetCurrent(), val)
#define SWIGV8_UNDEFINED() v8::Undefined(v8::Isolate::GetCurrent())
#endif
#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900)
typedef v8::Persistent<v8::Context> SwigV8Context;
#else
typedef v8::Local<v8::Context> SwigV8Context;
#endif
class V8Shell: public JSShell {
public:
V8Shell();
virtual ~V8Shell();
virtual bool RunScript(const std::string &scriptPath);
virtual bool RunShell();
protected:
virtual bool InitializeEngine();
virtual bool ExecuteScript(const std::string &source, const std::string &scriptPath);
virtual bool DisposeEngine();
private:
v8::Handle<v8::Value> Import(const std::string &moduleName);
SwigV8Context CreateShellContext();
void ReportException(v8::TryCatch *handler);
static SwigV8ReturnValue Print(const SwigV8Arguments &args);
static SwigV8ReturnValue Require(const SwigV8Arguments &args);
static SwigV8ReturnValue Quit(const SwigV8Arguments &args);
static SwigV8ReturnValue Version(const SwigV8Arguments &args);
static const char* ToCString(const v8::String::Utf8Value &value);
};
#ifdef __GNUC__
#include <dlfcn.h>
#define LOAD_SYMBOL(handle, name) dlsym(handle, name)
#else
#error "implement dll loading"
#endif
V8Shell::V8Shell() {}
V8Shell::~V8Shell() {}
bool V8Shell::RunScript(const std::string &scriptPath) {
std::string source = ReadFile(scriptPath);
v8::Isolate *isolate = v8::Isolate::New();
v8::Isolate::Scope isolate_scope(isolate);
SWIGV8_HANDLESCOPE();
SwigV8Context context = CreateShellContext();
if (context.IsEmpty()) {
printf("Could not create context.\n");
return false;
}
context->Enter();
// Store a pointer to this shell for later use
v8::Handle<v8::Object> global = context->Global();
v8::Local<v8::External> __shell__ = SWIGV8_EXTERNAL_NEW((void*) (long) this);
global->SetHiddenValue(SWIGV8_STRING_NEW("__shell__"), __shell__);
// Node.js compatibility: make `print` available as `console.log()`
ExecuteScript("var console = {}; console.log = print;", "<console>");
bool success = ExecuteScript(source, scriptPath);
// Cleanup
context->Exit();
#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710)
context.Dispose();
#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900)
context.Dispose(v8::Isolate::GetCurrent());
#else
// context.Dispose();
#endif
// v8::V8::Dispose();
return success;
}
bool V8Shell::RunShell() {
SWIGV8_HANDLESCOPE();
SwigV8Context context = CreateShellContext();
if (context.IsEmpty()) {
printf("Could not create context.\n");
return false;
}
context->Enter();
v8::Context::Scope context_scope(context);
ExecuteScript("var console = {}; console.log = print;", "<console>");
static const int kBufferSize = 1024;
while (true) {
char buffer[kBufferSize];
printf("> ");
char *str = fgets(buffer, kBufferSize, stdin);
if (str == NULL) break;
std::string source(str);
ExecuteScript(source, "(shell)");
}
printf("\n");
// Cleanup
context->Exit();
#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710)
context.Dispose();
#elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900)
context.Dispose(v8::Isolate::GetCurrent());
#else
// context.Dispose();
#endif
// v8::V8::Dispose();
return true;
}
bool V8Shell::InitializeEngine() {
return true;
}
bool V8Shell::ExecuteScript(const std::string &source, const std::string &name) {
SWIGV8_HANDLESCOPE();
v8::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(SWIGV8_STRING_NEW(source.c_str()), SWIGV8_STRING_NEW(name.c_str()));
// Stop if script is empty
if (script.IsEmpty()) {
// Print errors that happened during compilation.
ReportException(&try_catch);
return false;
}
v8::Handle<v8::Value> result = script->Run();
// Print errors that happened during execution.
if (try_catch.HasCaught()) {
ReportException(&try_catch);
return false;
} else {
return true;
}
}
bool V8Shell::DisposeEngine() {
return true;
}
SwigV8Context V8Shell::CreateShellContext() {
// Create a template for the global object.
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
// Bind global functions
global->Set(SWIGV8_STRING_NEW("print"), SWIGV8_FUNCTEMPLATE_NEW(V8Shell::Print));
global->Set(SWIGV8_STRING_NEW("quit"), SWIGV8_FUNCTEMPLATE_NEW(V8Shell::Quit));
global->Set(SWIGV8_STRING_NEW("require"), SWIGV8_FUNCTEMPLATE_NEW(V8Shell::Require));
global->Set(SWIGV8_STRING_NEW("version"), SWIGV8_FUNCTEMPLATE_NEW(V8Shell::Version));
#if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900)
SwigV8Context context = v8::Context::New(NULL, global);
return context;
#else
SwigV8Context context = v8::Context::New(v8::Isolate::GetCurrent(), NULL, global);
return context;
#endif
}
v8::Handle<v8::Value> V8Shell::Import(const std::string &module_path)
{
SWIGV8_HANDLESCOPE_ESC();
HANDLE library;
std::string module_name = LoadModule(module_path, &library);
std::string symname = std::string(module_name).append("_initialize");
V8ExtensionInitializer init_function = reinterpret_cast<V8ExtensionInitializer>((long) LOAD_SYMBOL(library, symname.c_str()));
if(init_function == 0) {
printf("Could not find initializer function.");
return SWIGV8_UNDEFINED();
}
v8::Local<v8::Object> module = SWIGV8_OBJECT_NEW();
init_function(module);
SWIGV8_ESCAPE(module);
}
SwigV8ReturnValue V8Shell::Print(const SwigV8Arguments &args) {
SWIGV8_HANDLESCOPE();
bool first = true;
for (int i = 0; i < args.Length(); i++) {
if (first) {
first = false;
} else {
printf(" ");
}
v8::String::Utf8Value str(args[i]);
const char *cstr = V8Shell::ToCString(str);
printf("%s", cstr);
}
printf("\n");
fflush(stdout);
SWIGV8_RETURN(SWIGV8_UNDEFINED());
}
SwigV8ReturnValue V8Shell::Require(const SwigV8Arguments &args) {
SWIGV8_HANDLESCOPE();
if (args.Length() != 1) {
printf("Illegal arguments for `require`");
};
v8::String::Utf8Value str(args[0]);
const char *cstr = V8Shell::ToCString(str);
std::string moduleName(cstr);
v8::Local<v8::Object> global = SWIGV8_CURRENT_CONTEXT()->Global();
v8::Local<v8::Value> hidden = global->GetHiddenValue(SWIGV8_STRING_NEW("__shell__"));
v8::Local<v8::External> __shell__ = v8::Local<v8::External>::Cast(hidden);
V8Shell *_this = (V8Shell *) (long) __shell__->Value();
v8::Handle<v8::Value> module = _this->Import(moduleName);
SWIGV8_RETURN(module);
}
SwigV8ReturnValue V8Shell::Quit(const SwigV8Arguments &args) {
SWIGV8_HANDLESCOPE();
int exit_code = args[0]->Int32Value();
fflush(stdout);
fflush(stderr);
exit(exit_code);
SWIGV8_RETURN(SWIGV8_UNDEFINED());
}
SwigV8ReturnValue V8Shell::Version(const SwigV8Arguments &args) {
SWIGV8_HANDLESCOPE();
SWIGV8_RETURN(SWIGV8_STRING_NEW(v8::V8::GetVersion()));
}
void V8Shell::ReportException(v8::TryCatch *try_catch) {
SWIGV8_HANDLESCOPE();
v8::String::Utf8Value exception(try_catch->Exception());
const char *exception_string = V8Shell::ToCString(exception);
v8::Handle<v8::Message> message = try_catch->Message();
if (message.IsEmpty()) {
// V8 didn't provide any extra information about this error; just
// print the exception.
printf("%s\n", exception_string);
} else {
// Print (filename):(line number): (message).
v8::String::Utf8Value filename(message->GetScriptResourceName());
const char *filename_string = V8Shell::ToCString(filename);
int linenum = message->GetLineNumber();
printf("%s:%i: %s\n", filename_string, linenum, exception_string);
// Print line of source code.
v8::String::Utf8Value sourceline(message->GetSourceLine());
const char *sourceline_string = V8Shell::ToCString(sourceline);
printf("%s\n", sourceline_string);
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
printf(" ");
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
printf("^");
}
printf("\n");
v8::String::Utf8Value stack_trace(try_catch->StackTrace());
if (stack_trace.length() > 0) {
const char *stack_trace_string = V8Shell::ToCString(stack_trace);
printf("%s\n", stack_trace_string);
}
}
}
// Extracts a C string from a V8 Utf8Value.
const char *V8Shell::ToCString(const v8::String::Utf8Value &value) {
return *value ? *value : "<string conversion failed>";
}
JSShell *V8Shell_Create() {
return new V8Shell();
}