Selaa lähdekoodia

Support importing scripts from disk

This is rather brittle right now, but quite interesting anyway.
Lucas Stadler 9 vuotta sitten
vanhempi
commit
6763eedf44
1 muutettua tiedostoa jossa 44 lisäystä ja 0 poistoa
  1. 44 0
      c/jsc-test.c

+ 44 - 0
c/jsc-test.c

@ -1,6 +1,7 @@
1 1
#include <stdio.h>
2 2
#include <stdlib.h>
3 3
#include <string.h>
4
#include <sys/stat.h>
4 5
5 6
#include <JavaScriptCore/JavaScript.h>
6 7
@ -39,6 +40,47 @@ JSValueRef function_console_error(JSContextRef ctx, JSObjectRef function, JSObje
39 40
	return JSValueMakeUndefined(ctx);
40 41
}
41 42
43
JSValueRef function_import_script(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) {
44
	if (argumentCount == 1 && JSValueGetType(ctx, arguments[0]) == kJSTypeString) {
45
		JSStringRef path_str_ref = JSValueToStringCopy(ctx, arguments[0], NULL);
46
		char path[100];
47
		path[0] = '\0';
48
		JSStringGetUTF8CString(path_str_ref, path, 100);
49
50
		FILE *f = fopen(path, "r");
51
		if (f == NULL) {
52
			perror("fopen");
53
			goto err;
54
		}
55
56
		struct stat f_stat;
57
		if (fstat(fileno(f), &f_stat) < 0) {
58
			perror("fstat");
59
			goto err;
60
		}
61
62
		char *buf = malloc(f_stat.st_size * sizeof(char));
63
		fread(buf, sizeof(char), f_stat.st_size, f);
64
		if (ferror(f)) {
65
			perror("fread");
66
			free(buf);
67
			goto err;
68
		}
69
70
		JSStringRef script_ref = JSStringCreateWithUTF8CString(buf);
71
		free(buf);
72
73
		JSEvaluateScript(ctx, script_ref, NULL, path_str_ref, 0, NULL);
74
		JSStringRelease(script_ref);
75
	}
76
77
	return JSValueMakeUndefined(ctx);
78
79
err:
80
	// TODO: Fill exception with error from errno
81
	return JSValueMakeUndefined(ctx);
82
}
83
42 84
void register_global_function(JSContextRef ctx, char *name, JSObjectCallAsFunctionCallback handler) {
43 85
	JSObjectRef global_obj = JSContextGetGlobalObject(ctx);
44 86
@ -56,6 +98,8 @@ int main(int argc, char **argv) {
56 98
57 99
	JSObjectRef global_obj = JSContextGetGlobalObject(ctx);
58 100
101
	register_global_function(ctx, "IMPORT_SCRIPT", function_import_script);
102
59 103
	register_global_function(ctx, "CONSOLE_LOG", function_console_log);
60 104
	register_global_function(ctx, "CONSOLE_ERROR", function_console_error);
61 105