int main (int argc, char **argv) { JSGlobalContextRef ctx; JSStringRef script; bool isOk; JSValueRef result; char *js; if (argc <= 1) { printf("Usage: JavaScript\n"); return 0; } js = argv[1]; ctx = JSGlobalContextCreate(NULL); printf("Checking: %s\n", js); script = JSStringCreateWithUTF8CString(js); isOk = JSCheckScriptSyntax(ctx, script, NULL, 1, NULL); printf("is ok? %s\n", isOk ? "TRUE" : "FALSE"); result = JSEvaluateScript(ctx, script, NULL, NULL, 1, NULL); JSStringRelease(script); printf("Value %.2f\n", JSValueToNumber(ctx, result, NULL)); JSGarbageCollect(ctx); JSGlobalContextRelease(ctx); printf("Ok\n"); return 0; }
pdf_jsimp *pdf_new_jsimp(fz_context *ctx, void *jsctx) { pdf_jsimp *imp = fz_malloc_struct(ctx, pdf_jsimp); fz_try(ctx) { JSClassDefinition classDef = kJSClassDefinitionEmpty; classDef.getProperty = getProperty; classDef.setProperty = setProperty; imp->nat_ctx = jsctx; imp->class_ref = JSClassCreate(&classDef); imp->jscore_ctx = JSGlobalContextCreate(imp->class_ref); if (imp->jscore_ctx == NULL) fz_throw(ctx, FZ_ERROR_GENERIC, "JSGlobalContextCreate failed"); } fz_catch(ctx) { pdf_drop_jsimp(imp); fz_rethrow(ctx); } imp->ctx = ctx; return imp; }
int main() { JSContextRef ctx = JSGlobalContextCreate(NULL); JSValueRef jsvalue; JSObjectRef jsobject2; JSObjectRef jsobject3; JSValueRef jsvalue4; jsvalue = JSValueMakeNumber(ctx, 0.123456711111111111); print_js(ctx, jsvalue); jsvalue = JSValueMakeBoolean(ctx, 1); print_js(ctx, jsvalue); jsvalue = JSValueMakeBoolean(ctx, 0); print_js(ctx, jsvalue); jsvalue = JSValueMakeNull(ctx); print_js(ctx, jsvalue); jsvalue = JSValueMakeUndefined(ctx); /* JSObjectIsFunction(ctx, jsvalue); //segmentation fault */ print_js(ctx, jsvalue); jsvalue = JSObjectMakeError(ctx, 0, NULL, NULL); printf("%lx\n", (unsigned long)jsvalue); printf("%lx\n", (unsigned long)(jsvalue = JSValueToObject(ctx, jsvalue, NULL))); printf("%lx\n", (unsigned long)(jsvalue = JSValueToObject(ctx, jsvalue, NULL))); print_js(ctx, jsvalue); jsvalue = JSObjectMake(ctx, NULL, NULL); print_js(ctx, jsvalue); jsobject2 = (JSObjectRef)get_property(ctx, jsvalue, "toString"); print_js(ctx, jsobject2); jsobject3 = JSObjectMakeError(ctx, 0, NULL, NULL); /* jsobject3 = JSValueMakeBoolean(ctx, 0); */ /* jsobject3 = JSValueMakeNull(ctx); */ /* jsobject3 = JSValueMakeNumber(ctx, 0.123134123); */ /* jsobject3 = JSValueMakeUndefined(ctx); */ jsvalue4 = JSObjectCallAsFunction(ctx, jsobject2, jsobject3, 0, NULL, NULL); print_js(ctx, jsvalue4); printf("test_function\n"); //test_function(ctx, jsobject3); JSStringRef jsstr; jsstr = JSStringCreateWithUTF8CString("abcdef"); jsvalue = JSValueMakeString(ctx, jsstr); JSStringRelease(jsstr); printf("%lx\n", (unsigned long)jsvalue); print_js(ctx, jsvalue); printf("%lx\n", (unsigned long)JSValueToObject(ctx, jsvalue, NULL)); print_js(ctx, JSValueToObject(ctx, jsvalue, NULL)); JSObjectCopyPropertyNames(ctx, (JSObjectRef)jsvalue); return 0; }
int main() { g_type_init(); ctx = JSGlobalContextCreate(NULL); DBusGConnection *con = dbus_g_bus_get(DBUS_BUS_SESSION, NULL); JSObjectRef obj = get_dbus_object(ctx, con, "org.gnome.Shell", "/org/gnome/Shell", "org.gnome.Shell"); dbus_g_connection_unref(con); JSGlobalContextRelease(ctx); /*dbus_object_info_free(info);*/ }
static void didRunJavaScript(WKSerializedScriptValueRef resultSerializedScriptValue, WKErrorRef error, void* context) { EXPECT_EQ(reinterpret_cast<void*>(0x1234578), context); EXPECT_NOT_NULL(resultSerializedScriptValue); JSGlobalContextRef scriptContext = JSGlobalContextCreate(0); JSValueRef scriptValue = WKSerializedScriptValueDeserialize(resultSerializedScriptValue, scriptContext, 0); EXPECT_TRUE(JSValueIsString(scriptContext, scriptValue)); // Make sure that the result of navigator.userAgent isn't empty, even if we set the custom // user agent to the empty string. JSStringRef scriptString = JSValueToStringCopy(scriptContext, scriptValue, 0); EXPECT_GT(JSStringGetLength(scriptString), 0u); JSStringRelease(scriptString); JSGlobalContextRelease(scriptContext); testDone = true; }
JavascriptModuleInstance::JavascriptModuleInstance(Host* host, std::string path, std::string dir, std::string name) : Module(host, dir.c_str(), name.c_str(), "0.1"), path(path) { this->context = JSGlobalContextCreate(NULL); this->global = JSContextGetGlobalObject(context); KJSUtil::RegisterGlobalContext(global, context); KJSUtil::ProtectGlobalContext(context); try { this->Run(); } catch (ValueException& e) { SharedString ss = e.GetValue()->DisplayString(); Logger *logger = Logger::Get("Javascript"); logger->Error("Could not execute %s because %s", path.c_str(), (*ss).c_str()); } }
static void javaScriptCallback(WKSerializedScriptValueRef resultSerializedScriptValue, WKErrorRef error, void* ctx) { ASSERT_NOT_NULL(resultSerializedScriptValue); JavaScriptCallbackContext* context = static_cast<JavaScriptCallbackContext*>(ctx); JSGlobalContextRef scriptContext = JSGlobalContextCreate(0); ASSERT_NOT_NULL(scriptContext); JSValueRef scriptValue = WKSerializedScriptValueDeserialize(resultSerializedScriptValue, scriptContext, 0); ASSERT_NOT_NULL(scriptValue); context->actualString.adopt(JSValueToStringCopy(scriptContext, scriptValue, 0)); ASSERT_NOT_NULL(context->actualString.get()); context->didFinish = true; JSGlobalContextRelease(scriptContext); EXPECT_NULL(error); }
EJApp::EJApp() : currentRenderingContext(0), screenRenderingContext(0) { landscapeMode = true; // Show the loading screen - commented out for now. // This causes some visual quirks on different devices, as the launch screen may be a // different one than we loade here - let's rather show a black screen for 200ms... //NSString * loadingScreenName = [EJApp landscapeMode] ? @"Default-Landscape.png" : @"Default-Portrait.png"; //loadingScreen = [[UIImageView alloc] initWithImage:[UIImage imageNamed:loadingScreenName]]; //loadingScreen.frame = self.view.bounds; //[self.view addSubview:loadingScreen]; paused = false; internalScaling = 1.0f; mainBundle = 0; timers = new EJTimerCollection(); // Create the global JS context and attach the 'Ejecta' object jsClasses = NSDictionary::create(); JSClassDefinition constructorClassDef = kJSClassDefinitionEmpty; constructorClassDef.callAsConstructor = ej_callAsConstructor; ej_constructorClass = JSClassCreate(&constructorClassDef); JSClassDefinition globalClassDef = kJSClassDefinitionEmpty; globalClassDef.getProperty = ej_getNativeClass; JSClassRef globalClass = JSClassCreate(&globalClassDef); jsGlobalContext = JSGlobalContextCreate(NULL); ej_global_undefined = JSValueMakeUndefined(jsGlobalContext); JSValueProtect(jsGlobalContext, ej_global_undefined); JSObjectRef globalObject = JSContextGetGlobalObject(jsGlobalContext); JSObjectRef iosObject = JSObjectMake( jsGlobalContext, globalClass, NULL ); JSObjectSetProperty( jsGlobalContext, globalObject, JSStringCreateWithUTF8CString("Ejecta"), iosObject, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly, NULL ); // Create the OpenGL ES1 Context // Android init GLView on java framework NSObjectFactory::map_type* base = NSObjectFactory::getMap(); for(NSObjectFactory::map_type::iterator it = base->begin(); it != base->end(); it++) { string name = it->first; NSLOG("NSObjectFactory : %s", name.c_str()); } NSObjectFactory::fuc_map_type* fuc_base = NSObjectFactory::getFunctionMap(); for(NSObjectFactory::fuc_map_type::iterator it = fuc_base->begin(); it != fuc_base->end(); it++) { string name = it->first; NSLOG("NSObjectFactory : %s", name.c_str()); } }
/** * return a new global context initialized with Hyperloop global objects */ EXPORTAPI JSGlobalContextRef HyperloopNewGlobalContext() { auto ctx = JSGlobalContextCreate(nullptr); InitializeContext(ctx); return ctx; }
gint main (gint argc, gchar ** argv) { JSGlobalContextRef ctx; JSStringRef str; JSObjectRef func; JSValueRef result; JSValueRef exception = NULL; JsonObject *obj; JsonNode *node; g_type_init(); gchar *buffer; if (argc != 2) { printf ("Usage: %s <script>\n", argv[0]); return 1; } ctx = JSGlobalContextCreate (NULL); str = JSStringCreateWithUTF8CString ("emitIntermediate"); func = JSObjectMakeFunctionWithCallback (ctx, str, js_emitIntermediate); JSObjectSetProperty (ctx, JSContextGetGlobalObject (ctx), str, func, kJSPropertyAttributeNone, NULL); JSStringRelease (str); str = JSStringCreateWithUTF8CString ("emit"); func = JSObjectMakeFunctionWithCallback (ctx, str, js_emit); JSObjectSetProperty (ctx, JSContextGetGlobalObject (ctx), str, func, kJSPropertyAttributeNone, NULL); JSStringRelease (str); str = JSStringCreateWithUTF8CString (argv[1]); result = JSEvaluateScript (ctx, str, NULL, NULL, 0, &exception); JSStringRelease (str); obj = json_object_new (); if (!result || exception) { js_value (ctx, exception, &node); json_object_set_member (obj, "error", node); json_object_set_boolean_member (obj, "status", FALSE); JSGlobalContextRelease (ctx); } else { json_object_set_boolean_member (obj, "status", TRUE); } JsonNode *node1 = json_node_new (JSON_NODE_OBJECT); if (node1 == NULL) { json_object_unref (obj); JSGlobalContextRelease (ctx); return 1; } json_node_set_object (node1, obj); JsonGenerator *gen = json_generator_new(); if (gen == NULL) { json_node_free (node1); JSGlobalContextRelease (ctx); return 1; } json_generator_set_root (gen, node1 ); buffer = json_generator_to_data (gen,NULL); if (buffer == NULL) { json_node_free (node1); JSGlobalContextRelease (ctx); return 1; } json_node_free (node1); puts (buffer); g_free (buffer); JSGlobalContextRelease (ctx); return 0; }
int main(int argc, char **argv) { struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"legal", no_argument, NULL, 'l'}, {"verbose", no_argument, NULL, 'v'}, {"quiet", no_argument, NULL, 'q'}, {"repl", no_argument, NULL, 'r'}, {"static-fns", no_argument, NULL, 's'}, {"elide-asserts", no_argument, NULL, 'a'}, {"cache", required_argument, NULL, 'k'}, {"eval", required_argument, NULL, 'e'}, {"theme", required_argument, NULL, 't'}, {"classpath", required_argument, NULL, 'c'}, {"auto-cache", no_argument, NULL, 'K'}, {"init", required_argument, NULL, 'i'}, {"main", required_argument, NULL, 'm'}, // development options {"javascript", no_argument, NULL, 'j'}, {"out", required_argument, NULL, 'o'}, {0, 0, 0, 0} }; int opt, option_index; while ((opt = getopt_long(argc, argv, "h?lvrsak:je:t:c:o:Ki:qm:", long_options, &option_index)) != -1) { switch (opt) { case 'h': usage(argv[0]); exit(0); case 'l': legal(); return 0; case 'v': verbose = true; break; case 'q': quiet = true; break; case 'r': repl = true; break; case 's': static_fns = true; break; case 'a': elide_asserts = true; break; case 'k': cache_path = argv[optind - 1]; break; case 'K': cache_path = ".planck_cache"; { char *path_copy = strdup(cache_path); char *dir = dirname(path_copy); if (mkdir_p(dir) < 0) { fprintf(stderr, "Could not create %s: %s\n", cache_path, strerror(errno)); } free(path_copy); } break; case 'j': javascript = true; break; case 'e': num_scripts += 1; scripts = realloc(scripts, num_scripts * sizeof(struct script)); scripts[num_scripts - 1].type = "text"; scripts[num_scripts - 1].expression = true; scripts[num_scripts - 1].source = argv[optind - 1]; break; case 'i': num_scripts += 1; scripts = realloc(scripts, num_scripts * sizeof(struct script)); scripts[num_scripts - 1].type = "path"; scripts[num_scripts - 1].expression = false; scripts[num_scripts - 1].source = argv[optind - 1]; break; case 'm': main_ns_name = argv[optind - 1]; case 't': theme = argv[optind - 1]; break; case 'c': { char *classpath = argv[optind - 1]; char *source = strtok(classpath, ":"); while (source != NULL) { char *type = "src"; if (str_has_suffix(source, ".jar") == 0) { type = "jar"; } num_src_paths += 1; src_paths = realloc(src_paths, num_src_paths * sizeof(struct src_path)); src_paths[num_src_paths - 1].type = type; src_paths[num_src_paths - 1].path = strdup(source); source = strtok(NULL, ":"); } break; } case 'o': out_path = argv[optind - 1]; break; case '?': usage(argv[0]); exit(1); default: printf("unhandled argument: %c\n", opt); } } int num_rest_args = 0; char **rest_args = NULL; if (optind < argc) { num_rest_args = argc - optind; rest_args = malloc((argc - optind) * sizeof(char*)); int i = 0; while (optind < argc) { rest_args[i++] = argv[optind++]; } } if (num_scripts == 0 && main_ns_name == NULL && num_rest_args == 0) { repl = true; } if (main_ns_name != NULL && repl) { printf("Only one main-opt can be specified."); } JSGlobalContextRef ctx = JSGlobalContextCreate(NULL); JSStringRef nameRef = JSStringCreateWithUTF8CString("planck"); JSGlobalContextSetName(ctx, nameRef); evaluate_script(ctx, "var global = this;", "<init>"); register_global_function(ctx, "AMBLY_IMPORT_SCRIPT", function_import_script); bootstrap(ctx, out_path); register_global_function(ctx, "PLANCK_CONSOLE_LOG", function_console_log); register_global_function(ctx, "PLANCK_CONSOLE_ERROR", function_console_error); evaluate_script(ctx, "var console = {};"\ "console.log = PLANCK_CONSOLE_LOG;"\ "console.error = PLANCK_CONSOLE_ERROR;", "<init>"); evaluate_script(ctx, "var PLANCK_VERSION = \"" PLANCK_VERSION "\";", "<init>"); // require app namespaces evaluate_script(ctx, "goog.require('planck.repl');", "<init>"); // without this things won't work evaluate_script(ctx, "var window = global;", "<init>"); register_global_function(ctx, "PLANCK_READ_FILE", function_read_file); register_global_function(ctx, "PLANCK_LOAD", function_load); register_global_function(ctx, "PLANCK_LOAD_DEPS_CLJS_FILES", function_load_deps_cljs_files); register_global_function(ctx, "PLANCK_CACHE", function_cache); register_global_function(ctx, "PLANCK_EVAL", function_eval); register_global_function(ctx, "PLANCK_GET_TERM_SIZE", function_get_term_size); register_global_function(ctx, "PLANCK_PRINT_FN", function_print_fn); register_global_function(ctx, "PLANCK_PRINT_ERR_FN", function_print_err_fn); register_global_function(ctx, "PLANCK_SET_EXIT_VALUE", function_set_exit_value); is_tty = isatty(STDIN_FILENO) == 1; register_global_function(ctx, "PLANCK_RAW_READ_STDIN", function_raw_read_stdin); register_global_function(ctx, "PLANCK_RAW_WRITE_STDOUT", function_raw_write_stdout); register_global_function(ctx, "PLANCK_RAW_FLUSH_STDOUT", function_raw_flush_stdout); register_global_function(ctx, "PLANCK_RAW_WRITE_STDERR", function_raw_write_stderr); register_global_function(ctx, "PLANCK_RAW_FLUSH_STDERR", function_raw_flush_stderr); { JSValueRef arguments[num_rest_args]; for (int i = 0; i < num_rest_args; i++) { arguments[i] = c_string_to_value(ctx, rest_args[i]); } JSValueRef args_ref = JSObjectMakeArray(ctx, num_rest_args, arguments, NULL); JSValueRef global_obj = JSContextGetGlobalObject(ctx); JSStringRef prop = JSStringCreateWithUTF8CString("PLANCK_INITIAL_COMMAND_LINE_ARGS"); JSObjectSetProperty(ctx, JSValueToObject(ctx, global_obj, NULL), prop, args_ref, kJSPropertyAttributeNone, NULL); JSStringRelease(prop); } evaluate_script(ctx, "cljs.core.set_print_fn_BANG_.call(null,PLANCK_PRINT_FN);", "<init>"); evaluate_script(ctx, "cljs.core.set_print_err_fn_BANG_.call(null,PLANCK_PRINT_ERR_FN);", "<init>"); char *elide_script = str_concat("cljs.core._STAR_assert_STAR_ = ", elide_asserts ? "false" : "true"); evaluate_script(ctx, elide_script, "<init>"); free(elide_script); { JSValueRef arguments[4]; arguments[0] = JSValueMakeBoolean(ctx, repl); arguments[1] = JSValueMakeBoolean(ctx, verbose); JSValueRef cache_path_ref = NULL; if (cache_path != NULL) { JSStringRef cache_path_str = JSStringCreateWithUTF8CString(cache_path); cache_path_ref = JSValueMakeString(ctx, cache_path_str); } arguments[2] = cache_path_ref; arguments[3] = JSValueMakeBoolean(ctx, static_fns); JSValueRef ex = NULL; JSObjectCallAsFunction(ctx, get_function(ctx, "planck.repl", "init"), JSContextGetGlobalObject(ctx), 4, arguments, &ex); debug_print_value("planck.repl/init", ctx, ex); } if (repl) { evaluate_source(ctx, "text", "(require '[planck.repl :refer-macros [apropos dir find-doc doc source pst]])", true, false, "cljs.user", "dumb"); } evaluate_script(ctx, "goog.provide('cljs.user');", "<init>"); evaluate_script(ctx, "goog.require('cljs.core');", "<init>"); evaluate_script(ctx, "cljs.core._STAR_assert_STAR_ = true;", "<init>"); // Process init arguments for (int i = 0; i < num_scripts; i++) { // TODO: exit if not successfull evaluate_source(ctx, scripts[i].type, scripts[i].source, scripts[i].expression, false, NULL, theme); } // Process main arguments if (main_ns_name != NULL) { run_main_in_ns(ctx, main_ns_name, num_rest_args, rest_args); } else if (!repl && num_rest_args > 0) { char *path = rest_args[0]; struct script script; if (strcmp(path, "-") == 0) { char *source = read_all(stdin); script.type = "text"; script.source = source; script.expression = false; } else { script.type = "path"; script.source = path; script.expression = false; } evaluate_source(ctx, script.type, script.source, script.expression, false, NULL, theme); } else if (repl) { if (!quiet) { banner(); } char *home = getenv("HOME"); char *history_path = NULL; if (home != NULL) { char history_name[] = ".planck_history"; int len = strlen(home) + strlen(history_name) + 2; history_path = malloc(len * sizeof(char)); snprintf(history_path, len, "%s/%s", home, history_name); linenoiseHistoryLoad(history_path); } char *prompt = javascript ? " > " : " => "; char *line; while ((line = linenoise(prompt)) != NULL) { if (javascript) { JSValueRef res = evaluate_script(ctx, line, "<stdin>"); print_value("", ctx, res); } else { evaluate_source(ctx, "text", line, true, true, "cljs.user", theme); } linenoiseHistoryAdd(line); if (history_path != NULL) { linenoiseHistorySave(history_path); } free(line); } } return exit_value; }
int main(int argc, char *argv[], char *envp[]) { #ifdef WEBKIT NSAutoreleasePool *pool = [NSAutoreleasePool new]; WebView *webView = [[WebView alloc] init]; JSGlobalContextRef _context = [[webView mainFrame] globalContext]; #elif WEBKIT_DEBUG NSAutoreleasePool *pool = [NSAutoreleasePool new]; WebView *webView = NW_init(argc, argv, envp); JSGlobalContextRef _context = [[webView mainFrame] globalContext]; #elif defined(JSCOCOA) NSAutoreleasePool *pool = [NSAutoreleasePool new]; JSCocoaController *jsc = [JSCocoa new]; JSGlobalContextRef _context = [jsc ctx]; #else JSGlobalContextRef _context = JSGlobalContextCreate(NULL); #endif #ifdef WEBKIT_DEBUG return NSApplicationMain(argc, (const char **)argv); #else JSValueRef exception = NULL; JSValueRef *_exception = &exception; CALL(narwhal, argc, argv, envp, 1); int code = !!(*_exception); #ifdef WEBKIT [pool drain]; #elif defined(JSCOCOA)
int main(int argc, char* argv[]) { UNUSED_PARAM(argc); UNUSED_PARAM(argv); // Test garbage collection with a fresh context context = JSGlobalContextCreate(NULL); TestInitializeFinalize = true; testInitializeFinalize(); JSGlobalContextRelease(context); JSGarbageCollect(context); TestInitializeFinalize = false; assert(Base_didFinalize); JSClassDefinition globalObjectClassDefinition = kJSClassDefinitionEmpty; globalObjectClassDefinition.initialize = testInitializeOfGlobalObjectClassHasNonNullContext; JSClassRef globalObjectClass = JSClassCreate(&globalObjectClassDefinition); context = JSGlobalContextCreate(globalObjectClass); JSObjectRef globalObject = JSContextGetGlobalObject(context); assert(JSValueIsObject(context, globalObject)); JSValueRef jsUndefined = JSValueMakeUndefined(context); JSValueRef jsNull = JSValueMakeNull(context); JSValueRef jsTrue = JSValueMakeBoolean(context, true); JSValueRef jsFalse = JSValueMakeBoolean(context, false); JSValueRef jsZero = JSValueMakeNumber(context, 0); JSValueRef jsOne = JSValueMakeNumber(context, 1); JSValueRef jsOneThird = JSValueMakeNumber(context, 1.0 / 3.0); JSObjectRef jsObjectNoProto = JSObjectMake(context, NULL, NULL); JSObjectSetPrototype(context, jsObjectNoProto, JSValueMakeNull(context)); // FIXME: test funny utf8 characters JSStringRef jsEmptyIString = JSStringCreateWithUTF8CString(""); JSValueRef jsEmptyString = JSValueMakeString(context, jsEmptyIString); JSStringRef jsOneIString = JSStringCreateWithUTF8CString("1"); JSValueRef jsOneString = JSValueMakeString(context, jsOneIString); UniChar singleUniChar = 65; // Capital A CFMutableStringRef cfString = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorDefault, &singleUniChar, 1, 1, kCFAllocatorNull); JSStringRef jsCFIString = JSStringCreateWithCFString(cfString); JSValueRef jsCFString = JSValueMakeString(context, jsCFIString); CFStringRef cfEmptyString = CFStringCreateWithCString(kCFAllocatorDefault, "", kCFStringEncodingUTF8); JSStringRef jsCFEmptyIString = JSStringCreateWithCFString(cfEmptyString); JSValueRef jsCFEmptyString = JSValueMakeString(context, jsCFEmptyIString); CFIndex cfStringLength = CFStringGetLength(cfString); UniChar buffer[cfStringLength]; CFStringGetCharacters(cfString, CFRangeMake(0, cfStringLength), buffer); JSStringRef jsCFIStringWithCharacters = JSStringCreateWithCharacters(buffer, cfStringLength); JSValueRef jsCFStringWithCharacters = JSValueMakeString(context, jsCFIStringWithCharacters); JSStringRef jsCFEmptyIStringWithCharacters = JSStringCreateWithCharacters(buffer, CFStringGetLength(cfEmptyString)); JSValueRef jsCFEmptyStringWithCharacters = JSValueMakeString(context, jsCFEmptyIStringWithCharacters); assert(JSValueGetType(context, jsUndefined) == kJSTypeUndefined); assert(JSValueGetType(context, jsNull) == kJSTypeNull); assert(JSValueGetType(context, jsTrue) == kJSTypeBoolean); assert(JSValueGetType(context, jsFalse) == kJSTypeBoolean); assert(JSValueGetType(context, jsZero) == kJSTypeNumber); assert(JSValueGetType(context, jsOne) == kJSTypeNumber); assert(JSValueGetType(context, jsOneThird) == kJSTypeNumber); assert(JSValueGetType(context, jsEmptyString) == kJSTypeString); assert(JSValueGetType(context, jsOneString) == kJSTypeString); assert(JSValueGetType(context, jsCFString) == kJSTypeString); assert(JSValueGetType(context, jsCFStringWithCharacters) == kJSTypeString); assert(JSValueGetType(context, jsCFEmptyString) == kJSTypeString); assert(JSValueGetType(context, jsCFEmptyStringWithCharacters) == kJSTypeString); JSObjectRef myObject = JSObjectMake(context, MyObject_class(context), NULL); JSStringRef myObjectIString = JSStringCreateWithUTF8CString("MyObject"); JSObjectSetProperty(context, globalObject, myObjectIString, myObject, kJSPropertyAttributeNone, NULL); JSStringRelease(myObjectIString); JSValueRef exception; // Conversions that throw exceptions exception = NULL; assert(NULL == JSValueToObject(context, jsNull, &exception)); assert(exception); exception = NULL; // FIXME <rdar://4668451> - On i386 the isnan(double) macro tries to map to the isnan(float) function, // causing a build break with -Wshorten-64-to-32 enabled. The issue is known by the appropriate team. // After that's resolved, we can remove these casts assert(isnan((float)JSValueToNumber(context, jsObjectNoProto, &exception))); assert(exception); exception = NULL; assert(!JSValueToStringCopy(context, jsObjectNoProto, &exception)); assert(exception); assert(JSValueToBoolean(context, myObject)); exception = NULL; assert(!JSValueIsEqual(context, jsObjectNoProto, JSValueMakeNumber(context, 1), &exception)); assert(exception); exception = NULL; JSObjectGetPropertyAtIndex(context, myObject, 0, &exception); assert(1 == JSValueToNumber(context, exception, NULL)); assertEqualsAsBoolean(jsUndefined, false); assertEqualsAsBoolean(jsNull, false); assertEqualsAsBoolean(jsTrue, true); assertEqualsAsBoolean(jsFalse, false); assertEqualsAsBoolean(jsZero, false); assertEqualsAsBoolean(jsOne, true); assertEqualsAsBoolean(jsOneThird, true); assertEqualsAsBoolean(jsEmptyString, false); assertEqualsAsBoolean(jsOneString, true); assertEqualsAsBoolean(jsCFString, true); assertEqualsAsBoolean(jsCFStringWithCharacters, true); assertEqualsAsBoolean(jsCFEmptyString, false); assertEqualsAsBoolean(jsCFEmptyStringWithCharacters, false); assertEqualsAsNumber(jsUndefined, nan("")); assertEqualsAsNumber(jsNull, 0); assertEqualsAsNumber(jsTrue, 1); assertEqualsAsNumber(jsFalse, 0); assertEqualsAsNumber(jsZero, 0); assertEqualsAsNumber(jsOne, 1); assertEqualsAsNumber(jsOneThird, 1.0 / 3.0); assertEqualsAsNumber(jsEmptyString, 0); assertEqualsAsNumber(jsOneString, 1); assertEqualsAsNumber(jsCFString, nan("")); assertEqualsAsNumber(jsCFStringWithCharacters, nan("")); assertEqualsAsNumber(jsCFEmptyString, 0); assertEqualsAsNumber(jsCFEmptyStringWithCharacters, 0); assert(sizeof(JSChar) == sizeof(UniChar)); assertEqualsAsCharactersPtr(jsUndefined, "undefined"); assertEqualsAsCharactersPtr(jsNull, "null"); assertEqualsAsCharactersPtr(jsTrue, "true"); assertEqualsAsCharactersPtr(jsFalse, "false"); assertEqualsAsCharactersPtr(jsZero, "0"); assertEqualsAsCharactersPtr(jsOne, "1"); assertEqualsAsCharactersPtr(jsOneThird, "0.3333333333333333"); assertEqualsAsCharactersPtr(jsEmptyString, ""); assertEqualsAsCharactersPtr(jsOneString, "1"); assertEqualsAsCharactersPtr(jsCFString, "A"); assertEqualsAsCharactersPtr(jsCFStringWithCharacters, "A"); assertEqualsAsCharactersPtr(jsCFEmptyString, ""); assertEqualsAsCharactersPtr(jsCFEmptyStringWithCharacters, ""); assertEqualsAsUTF8String(jsUndefined, "undefined"); assertEqualsAsUTF8String(jsNull, "null"); assertEqualsAsUTF8String(jsTrue, "true"); assertEqualsAsUTF8String(jsFalse, "false"); assertEqualsAsUTF8String(jsZero, "0"); assertEqualsAsUTF8String(jsOne, "1"); assertEqualsAsUTF8String(jsOneThird, "0.3333333333333333"); assertEqualsAsUTF8String(jsEmptyString, ""); assertEqualsAsUTF8String(jsOneString, "1"); assertEqualsAsUTF8String(jsCFString, "A"); assertEqualsAsUTF8String(jsCFStringWithCharacters, "A"); assertEqualsAsUTF8String(jsCFEmptyString, ""); assertEqualsAsUTF8String(jsCFEmptyStringWithCharacters, ""); assert(JSValueIsStrictEqual(context, jsTrue, jsTrue)); assert(!JSValueIsStrictEqual(context, jsOne, jsOneString)); assert(JSValueIsEqual(context, jsOne, jsOneString, NULL)); assert(!JSValueIsEqual(context, jsTrue, jsFalse, NULL)); CFStringRef cfJSString = JSStringCopyCFString(kCFAllocatorDefault, jsCFIString); CFStringRef cfJSEmptyString = JSStringCopyCFString(kCFAllocatorDefault, jsCFEmptyIString); assert(CFEqual(cfJSString, cfString)); assert(CFEqual(cfJSEmptyString, cfEmptyString)); CFRelease(cfJSString); CFRelease(cfJSEmptyString); CFRelease(cfString); CFRelease(cfEmptyString); jsGlobalValue = JSObjectMake(context, NULL, NULL); JSValueProtect(context, jsGlobalValue); JSGarbageCollect(context); assert(JSValueIsObject(context, jsGlobalValue)); JSValueUnprotect(context, jsGlobalValue); JSStringRef goodSyntax = JSStringCreateWithUTF8CString("x = 1;"); JSStringRef badSyntax = JSStringCreateWithUTF8CString("x := 1;"); assert(JSCheckScriptSyntax(context, goodSyntax, NULL, 0, NULL)); assert(!JSCheckScriptSyntax(context, badSyntax, NULL, 0, NULL)); JSValueRef result; JSValueRef v; JSObjectRef o; JSStringRef string; result = JSEvaluateScript(context, goodSyntax, NULL, NULL, 1, NULL); assert(result); assert(JSValueIsEqual(context, result, jsOne, NULL)); exception = NULL; result = JSEvaluateScript(context, badSyntax, NULL, NULL, 1, &exception); assert(!result); assert(JSValueIsObject(context, exception)); JSStringRef array = JSStringCreateWithUTF8CString("Array"); JSObjectRef arrayConstructor = JSValueToObject(context, JSObjectGetProperty(context, globalObject, array, NULL), NULL); JSStringRelease(array); result = JSObjectCallAsConstructor(context, arrayConstructor, 0, NULL, NULL); assert(result); assert(JSValueIsObject(context, result)); assert(JSValueIsInstanceOfConstructor(context, result, arrayConstructor, NULL)); assert(!JSValueIsInstanceOfConstructor(context, JSValueMakeNull(context), arrayConstructor, NULL)); o = JSValueToObject(context, result, NULL); exception = NULL; assert(JSValueIsUndefined(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception))); assert(!exception); JSObjectSetPropertyAtIndex(context, o, 0, JSValueMakeNumber(context, 1), &exception); assert(!exception); exception = NULL; assert(1 == JSValueToNumber(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception), &exception)); assert(!exception); JSStringRef functionBody; JSObjectRef function; exception = NULL; functionBody = JSStringCreateWithUTF8CString("rreturn Array;"); JSStringRef line = JSStringCreateWithUTF8CString("line"); assert(!JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception)); assert(JSValueIsObject(context, exception)); v = JSObjectGetProperty(context, JSValueToObject(context, exception, NULL), line, NULL); assertEqualsAsNumber(v, 2); // FIXME: Lexer::setCode bumps startingLineNumber by 1 -- we need to change internal callers so that it doesn't have to (saying '0' to mean '1' in the API would be really confusing -- it's really confusing internally, in fact) JSStringRelease(functionBody); JSStringRelease(line); exception = NULL; functionBody = JSStringCreateWithUTF8CString("return Array;"); function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception); JSStringRelease(functionBody); assert(!exception); assert(JSObjectIsFunction(context, function)); v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL); assert(v); assert(JSValueIsEqual(context, v, arrayConstructor, NULL)); exception = NULL; function = JSObjectMakeFunction(context, NULL, 0, NULL, jsEmptyIString, NULL, 0, &exception); assert(!exception); v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, &exception); assert(v && !exception); assert(JSValueIsUndefined(context, v)); exception = NULL; v = NULL; JSStringRef foo = JSStringCreateWithUTF8CString("foo"); JSStringRef argumentNames[] = { foo }; functionBody = JSStringCreateWithUTF8CString("return foo;"); function = JSObjectMakeFunction(context, foo, 1, argumentNames, functionBody, NULL, 1, &exception); assert(function && !exception); JSValueRef arguments[] = { JSValueMakeNumber(context, 2) }; v = JSObjectCallAsFunction(context, function, NULL, 1, arguments, &exception); JSStringRelease(foo); JSStringRelease(functionBody); string = JSValueToStringCopy(context, function, NULL); assertEqualsAsUTF8String(JSValueMakeString(context, string), "function foo(foo) \n{\n return foo;\n}"); JSStringRelease(string); JSStringRef print = JSStringCreateWithUTF8CString("print"); JSObjectRef printFunction = JSObjectMakeFunctionWithCallback(context, print, print_callAsFunction); JSObjectSetProperty(context, globalObject, print, printFunction, kJSPropertyAttributeNone, NULL); JSStringRelease(print); assert(!JSObjectSetPrivate(printFunction, (void*)1)); assert(!JSObjectGetPrivate(printFunction)); JSStringRef myConstructorIString = JSStringCreateWithUTF8CString("MyConstructor"); JSObjectRef myConstructor = JSObjectMakeConstructor(context, NULL, myConstructor_callAsConstructor); JSObjectSetProperty(context, globalObject, myConstructorIString, myConstructor, kJSPropertyAttributeNone, NULL); JSStringRelease(myConstructorIString); assert(!JSObjectSetPrivate(myConstructor, (void*)1)); assert(!JSObjectGetPrivate(myConstructor)); string = JSStringCreateWithUTF8CString("Derived"); JSObjectRef derivedConstructor = JSObjectMakeConstructor(context, Derived_class(context), NULL); JSObjectSetProperty(context, globalObject, string, derivedConstructor, kJSPropertyAttributeNone, NULL); JSStringRelease(string); o = JSObjectMake(context, NULL, NULL); JSObjectSetProperty(context, o, jsOneIString, JSValueMakeNumber(context, 1), kJSPropertyAttributeNone, NULL); JSObjectSetProperty(context, o, jsCFIString, JSValueMakeNumber(context, 1), kJSPropertyAttributeDontEnum, NULL); JSPropertyNameArrayRef nameArray = JSObjectCopyPropertyNames(context, o); size_t expectedCount = JSPropertyNameArrayGetCount(nameArray); size_t count; for (count = 0; count < expectedCount; ++count) JSPropertyNameArrayGetNameAtIndex(nameArray, count); JSPropertyNameArrayRelease(nameArray); assert(count == 1); // jsCFString should not be enumerated JSClassDefinition nullDefinition = kJSClassDefinitionEmpty; nullDefinition.attributes = kJSClassAttributeNoAutomaticPrototype; JSClassRef nullClass = JSClassCreate(&nullDefinition); JSClassRelease(nullClass); nullDefinition = kJSClassDefinitionEmpty; nullClass = JSClassCreate(&nullDefinition); JSClassRelease(nullClass); functionBody = JSStringCreateWithUTF8CString("return this;"); function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, NULL); JSStringRelease(functionBody); v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL); assert(JSValueIsEqual(context, v, globalObject, NULL)); v = JSObjectCallAsFunction(context, function, o, 0, NULL, NULL); assert(JSValueIsEqual(context, v, o, NULL)); char* scriptUTF8 = createStringWithContentsOfFile("testapi.js"); JSStringRef script = JSStringCreateWithUTF8CString(scriptUTF8); result = JSEvaluateScript(context, script, NULL, NULL, 1, &exception); if (JSValueIsUndefined(context, result)) printf("PASS: Test script executed successfully.\n"); else { printf("FAIL: Test script returned unexcpected value:\n"); JSStringRef exceptionIString = JSValueToStringCopy(context, exception, NULL); CFStringRef exceptionCF = JSStringCopyCFString(kCFAllocatorDefault, exceptionIString); CFShow(exceptionCF); CFRelease(exceptionCF); JSStringRelease(exceptionIString); } JSStringRelease(script); free(scriptUTF8); JSStringRelease(jsEmptyIString); JSStringRelease(jsOneIString); JSStringRelease(jsCFIString); JSStringRelease(jsCFEmptyIString); JSStringRelease(jsCFIStringWithCharacters); JSStringRelease(jsCFEmptyIStringWithCharacters); JSStringRelease(goodSyntax); JSStringRelease(badSyntax); JSGlobalContextRelease(context); JSGarbageCollect(context); JSClassRelease(globalObjectClass); printf("PASS: Program exited normally.\n"); return 0; }
JSContext::JSContext() { _context = JSGlobalContextCreate(NULL); _contextCreated = true; }
int main(int argc, char **argv) { config.verbose = false; config.quiet = false; config.repl = false; config.javascript = false; config.static_fns = false; config.elide_asserts = false; config.cache_path = NULL; config.theme = "light"; config.dumb_terminal = false; config.out_path = NULL; config.num_src_paths = 0; config.src_paths = NULL; config.num_scripts = 0; config.scripts = NULL; config.main_ns_name = NULL; struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"legal", no_argument, NULL, 'l'}, {"verbose", no_argument, NULL, 'v'}, {"quiet", no_argument, NULL, 'q'}, {"repl", no_argument, NULL, 'r'}, {"static-fns", no_argument, NULL, 's'}, {"elide-asserts", no_argument, NULL, 'a'}, {"cache", required_argument, NULL, 'k'}, {"eval", required_argument, NULL, 'e'}, {"theme", required_argument, NULL, 't'}, {"dumb-terminal", no_argument, NULL, 'd'}, {"classpath", required_argument, NULL, 'c'}, {"auto-cache", no_argument, NULL, 'K'}, {"init", required_argument, NULL, 'i'}, {"main", required_argument, NULL, 'm'}, // development options {"javascript", no_argument, NULL, 'j'}, {"out", required_argument, NULL, 'o'}, {0, 0, 0, 0} }; int opt, option_index; while ((opt = getopt_long(argc, argv, "h?lvrsak:je:t:dc:o:Ki:qm:", long_options, &option_index)) != -1) { switch (opt) { case 'h': usage(argv[0]); exit(0); case 'l': legal(); return 0; case 'v': config.verbose = true; break; case 'q': config.quiet = true; break; case 'r': config.repl = true; break; case 's': config.static_fns = true; break; case 'a': config.elide_asserts = true; break; case 'k': config.cache_path = argv[optind - 1]; break; case 'K': config.cache_path = ".planck_cache"; { char *path_copy = strdup(config.cache_path); char *dir = dirname(path_copy); if (mkdir_p(dir) < 0) { fprintf(stderr, "Could not create %s: %s\n", config.cache_path, strerror(errno)); } free(path_copy); } break; case 'j': config.javascript = true; break; case 'e': config.num_scripts += 1; config.scripts = realloc(config.scripts, config.num_scripts * sizeof(struct script)); config.scripts[config.num_scripts - 1].type = "text"; config.scripts[config.num_scripts - 1].expression = true; config.scripts[config.num_scripts - 1].source = argv[optind - 1]; break; case 'i': config.num_scripts += 1; config.scripts = realloc(config.scripts, config.num_scripts * sizeof(struct script)); config.scripts[config.num_scripts - 1].type = "path"; config.scripts[config.num_scripts - 1].expression = false; config.scripts[config.num_scripts - 1].source = argv[optind - 1]; break; case 'm': config.main_ns_name = argv[optind - 1]; break; case 't': config.theme = argv[optind - 1]; break; case 'd': config.dumb_terminal = true; break; case 'c': { char *classpath = argv[optind - 1]; char *source = strtok(classpath, ":"); while (source != NULL) { char *type = "src"; if (str_has_suffix(source, ".jar") == 0) { type = "jar"; } config.num_src_paths += 1; config.src_paths = realloc(config.src_paths, config.num_src_paths * sizeof(struct src_path)); config.src_paths[config.num_src_paths - 1].type = type; config.src_paths[config.num_src_paths - 1].path = strcmp(type, "jar") == 0 ? strdup(source) : ensure_trailing_slash(source); source = strtok(NULL, ":"); } break; } case 'o': config.out_path = ensure_trailing_slash(argv[optind - 1]); break; case '?': usage(argv[0]); exit(1); default: printf("unhandled argument: %c\n", opt); } } if (config.dumb_terminal) { config.theme = "dumb"; } config.num_rest_args = 0; config.rest_args = NULL; if (optind < argc) { config.num_rest_args = argc - optind; config.rest_args = malloc((argc - optind) * sizeof(char*)); int i = 0; while (optind < argc) { config.rest_args[i++] = argv[optind++]; } } if (config.num_scripts == 0 && config.main_ns_name == NULL && config.num_rest_args == 0) { config.repl = true; } if (config.main_ns_name != NULL && config.repl) { printf("Only one main-opt can be specified.\n"); exit(1); } config.is_tty = isatty(STDIN_FILENO) == 1; JSGlobalContextRef ctx = JSGlobalContextCreate(NULL); global_ctx = ctx; cljs_engine_init(ctx); // Process init arguments for (int i = 0; i < config.num_scripts; i++) { // TODO: exit if not successfull struct script script = config.scripts[i]; evaluate_source(ctx, script.type, script.source, script.expression, false, NULL, config.theme, true); } // Process main arguments if (config.main_ns_name != NULL) { run_main_in_ns(ctx, config.main_ns_name, config.num_rest_args, config.rest_args); } else if (!config.repl && config.num_rest_args > 0) { char *path = config.rest_args[0]; struct script script; if (strcmp(path, "-") == 0) { char *source = read_all(stdin); script.type = "text"; script.source = source; script.expression = false; } else { script.type = "path"; script.source = path; script.expression = false; } evaluate_source(ctx, script.type, script.source, script.expression, false, NULL, config.theme, true); } else if (config.repl) { if (!config.quiet) { banner(); } run_repl(ctx); } return exit_value; }
int main(int argc, char *argv[], char *envp[]) { void * ctx = JSGlobalContextCreate(NULL); JSGlobalContextRelease(ctx); return 0; }