| 1 | #include <v8.h> |
|---|
| 2 | #include <cstring> |
|---|
| 3 | |
|---|
| 4 | using namespace v8; |
|---|
| 5 | |
|---|
| 6 | // Executes a string within the current v8 context. |
|---|
| 7 | bool Exec(Handle<String> source, |
|---|
| 8 | Handle<Value> name, |
|---|
| 9 | bool print_result) { |
|---|
| 10 | HandleScope handle_scope; |
|---|
| 11 | TryCatch try_catch; |
|---|
| 12 | try_catch.SetVerbose(true); |
|---|
| 13 | Handle<Script> script = Script::Compile(source, name); |
|---|
| 14 | if (script.IsEmpty()) { |
|---|
| 15 | // Print errors that happened during compilation. |
|---|
| 16 | String::Utf8Value error(try_catch.Exception()); |
|---|
| 17 | printf("%s\n", *error); |
|---|
| 18 | return false; |
|---|
| 19 | } else { |
|---|
| 20 | Handle<Value> result = script->Run(); |
|---|
| 21 | if (result.IsEmpty()) { |
|---|
| 22 | // Print errors that happened during execution. |
|---|
| 23 | String::Utf8Value error(try_catch.Exception()); |
|---|
| 24 | printf("%s\n", *error); |
|---|
| 25 | return false; |
|---|
| 26 | } else { |
|---|
| 27 | if (print_result && !result->IsUndefined()) { |
|---|
| 28 | // If all went well and the result wasn't undefined then print |
|---|
| 29 | // the returned value. |
|---|
| 30 | String::AsciiValue str(result); |
|---|
| 31 | printf("%s\n", *str); |
|---|
| 32 | } |
|---|
| 33 | return true; |
|---|
| 34 | } |
|---|
| 35 | } |
|---|
| 36 | } |
|---|
| 37 | |
|---|
| 38 | Handle<String> ReadFile(const char* name) { |
|---|
| 39 | FILE* file = fopen(name, "rb"); |
|---|
| 40 | if (file == NULL) return Handle<String>(); |
|---|
| 41 | |
|---|
| 42 | fseek(file, 0, SEEK_END); |
|---|
| 43 | int size = ftell(file); |
|---|
| 44 | rewind(file); |
|---|
| 45 | |
|---|
| 46 | char* chars = new char[size + 1]; |
|---|
| 47 | char *buffer; |
|---|
| 48 | chars[size] = '\0'; |
|---|
| 49 | for (int i = 0; i < size;) { |
|---|
| 50 | int read = fread(&chars[i], 1, size - i, file); |
|---|
| 51 | i += read; |
|---|
| 52 | } |
|---|
| 53 | fclose(file); |
|---|
| 54 | if (size>2 && chars[0] == '#' && chars[1] == '!') { |
|---|
| 55 | // shebang hack |
|---|
| 56 | char *end = strchr(chars, '\n'); |
|---|
| 57 | if (end && end-chars > 0) { |
|---|
| 58 | size -= (end-chars) + 1; |
|---|
| 59 | buffer = end+1; |
|---|
| 60 | } |
|---|
| 61 | } else { |
|---|
| 62 | buffer = chars; |
|---|
| 63 | } |
|---|
| 64 | Handle<String> result = String::New(buffer, size); |
|---|
| 65 | delete[] chars; |
|---|
| 66 | return result; |
|---|
| 67 | } |
|---|
| 68 | |
|---|