浏览代码

Extract evaluation to a separate function

Lucas Stadler 9 年之前
父节点
当前提交
4ab9cbd6b3
共有 1 个文件被更改,包括 31 次插入16 次删除
  1. 31 16
      c/jsc-test.c

+ 31 - 16
c/jsc-test.c

@ -9,6 +9,7 @@
9 9
char console_log_buf[CONSOLE_LOG_BUF_SIZE];
10 10
11 11
JSStringRef to_string(JSContextRef ctx, JSValueRef val);
12
JSValueRef evaluate_script(JSContextRef ctx, char *script, char *source);
12 13
13 14
JSValueRef function_console_log(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) {
14 15
	for (int i = 0; i < argumentCount; i++) {
@ -46,6 +47,7 @@ JSValueRef function_import_script(JSContextRef ctx, JSObjectRef function, JSObje
46 47
		char path[100];
47 48
		path[0] = '\0';
48 49
		JSStringGetUTF8CString(path_str_ref, path, 100);
50
		JSStringRelease(path_str_ref);
49 51
50 52
		FILE *f = fopen(path, "r");
51 53
		if (f == NULL) {
@ -67,23 +69,8 @@ JSValueRef function_import_script(JSContextRef ctx, JSObjectRef function, JSObje
67 69
			goto err;
68 70
		}
69 71
70
		JSStringRef script_ref = JSStringCreateWithUTF8CString(buf);
72
		evaluate_script(ctx, buf, path);
71 73
		free(buf);
72
73
		JSValueRef ex = NULL;
74
		JSEvaluateScript(ctx, script_ref, NULL, path_str_ref, 0, &ex);
75
		JSStringRelease(script_ref);
76
77
#ifdef DEBUG
78
		if (ex != NULL) {
79
			JSStringRef ex_str = to_string(ctx, ex);
80
			char ex_buf[1000];
81
			ex_buf[0] = '\0';
82
			JSStringGetUTF8CString(ex_str, ex_buf, 1000);
83
			printf("import: %s\n", ex_buf);
84
			JSStringRelease(ex_str);
85
		}
86
#endif
87 74
	}
88 75
89 76
	return JSValueMakeUndefined(ctx);
@ -152,3 +139,31 @@ JSStringRef to_string(JSContextRef ctx, JSValueRef val) {
152 139
		return JSValueToStringCopy(ctx, obj_val, NULL);
153 140
	}
154 141
}
142
143
JSValueRef evaluate_script(JSContextRef ctx, char *script, char *source) {
144
	JSStringRef script_ref = JSStringCreateWithUTF8CString(script);
145
	JSStringRef source_ref = NULL;
146
	if (source != NULL) {
147
		source_ref = JSStringCreateWithUTF8CString(source);
148
	}
149
150
	JSValueRef ex = NULL;
151
	JSValueRef val = JSEvaluateScript(ctx, script_ref, NULL, source_ref, 0, &ex);
152
	JSStringRelease(script_ref);
153
	if (source != NULL) {
154
		JSStringRelease(source_ref);
155
	}
156
157
#ifdef DEBUG
158
	if (ex != NULL) {
159
		JSStringRef ex_str = to_string(ctx, ex);
160
		char ex_buf[1000];
161
		ex_buf[0] = '\0';
162
		JSStringGetUTF8CString(ex_str, ex_buf, 1000);
163
		printf("eval %s: %s\n", source, ex_buf);
164
		JSStringRelease(ex_str);
165
	}
166
#endif
167
168
	return val;
169
}