OLD | NEW |
(Empty) | |
| 1 #include "include/v8c.h" |
| 2 #include <stdio.h> |
| 3 |
| 4 const bool true = 1; |
| 5 const bool false = 0; |
| 6 |
| 7 static void print_value(V8Handle v) { |
| 8 V8StringUtf8Value* utf8 = v8_string_utf8_value_new(v); |
| 9 printf("%s", v8_string_utf8_value_chars(utf8)); |
| 10 v8_string_utf8_value_free(utf8); |
| 11 } |
| 12 |
| 13 // A callback from JavaScript to print verbosely. |
| 14 static V8Handle debug_print_cb(const V8Arguments* args) { |
| 15 int i, length = v8_arguments_length(args); |
| 16 printf("debug_print called with %d args\n", length); |
| 17 for (i = 0; i < length; ++i) { |
| 18 printf("%d: ", i); |
| 19 print_value(v8_arguments_get(args, i)); |
| 20 printf("\n"); |
| 21 } |
| 22 return v8_undefined(); |
| 23 } |
| 24 |
| 25 // A callback from JavaScript to print concisely. |
| 26 static V8Handle print_cb(const V8Arguments* args) { |
| 27 int i, length = v8_arguments_length(args); |
| 28 for (i = 0; i < length; ++i) { |
| 29 if (i > 0) |
| 30 printf(" "); |
| 31 print_value(v8_arguments_get(args, i)); |
| 32 } |
| 33 printf("\n"); |
| 34 return v8_undefined(); |
| 35 } |
| 36 |
| 37 void report_exception(V8TryCatch* try_catch) { |
| 38 V8HandleScope* handle_scope = v8_handle_scope_new(); |
| 39 V8StringUtf8Value* exception = |
| 40 v8_string_utf8_value_new(v8_try_catch_exception(try_catch)); |
| 41 printf("%s\n", v8_string_utf8_value_chars(exception)); |
| 42 v8_string_utf8_value_free(exception); |
| 43 v8_handle_scope_free(handle_scope); |
| 44 } |
| 45 |
| 46 int main(int argc, char** argv) { |
| 47 V8HandleScope* handle_scope; |
| 48 V8Handle print, debug_print, global, context, script; |
| 49 V8TryCatch* try_catch; |
| 50 |
| 51 v8_set_flags_from_command_line(&argc, argv, true); |
| 52 |
| 53 if (argc < 2) { |
| 54 printf("usage: %s <javascript>\n", argv[0]); |
| 55 return 1; |
| 56 } |
| 57 const char* code = argv[1]; |
| 58 |
| 59 handle_scope = v8_handle_scope_new(); |
| 60 print = v8_function_template_new(print_cb); |
| 61 debug_print = v8_function_template_new(debug_print_cb); |
| 62 global = v8_object_template_new(); |
| 63 v8_template_set(global, v8_string_new_utf8("debug_print", -1), debug_print); |
| 64 v8_template_set(global, v8_string_new_utf8("print", -1), print); |
| 65 |
| 66 context = v8_context_new(NULL, global); |
| 67 v8_context_enter(context); |
| 68 |
| 69 try_catch = v8_try_catch_new(); |
| 70 script = v8_script_compile(v8_string_new_utf8(code, -1)); |
| 71 if (v8_handle_is_empty(script)) { |
| 72 report_exception(try_catch); |
| 73 } else { |
| 74 V8Handle result = v8_script_run(script); |
| 75 if (v8_handle_is_empty(result)) { |
| 76 report_exception(try_catch); |
| 77 } else { |
| 78 printf("result is: "); |
| 79 print_value(result); |
| 80 printf("\n"); |
| 81 } |
| 82 } |
| 83 v8_try_catch_free(try_catch); |
| 84 |
| 85 v8_context_exit(context); |
| 86 v8_handle_scope_free(handle_scope); |
| 87 |
| 88 return 0; |
| 89 } |
OLD | NEW |