v8js_methods.cc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2012 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 3.01 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available through the world-wide-web at the following url: |
  10. | http://www.php.net/license/3_01.txt |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | [email protected] so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Author: Jani Taskinen <[email protected]> |
  16. | Author: Patrick Reilly <[email protected]> |
  17. +----------------------------------------------------------------------+
  18. */
  19. /* $Id$ */
  20. #ifdef HAVE_CONFIG_H
  21. #include "config.h"
  22. #endif
  23. extern "C" {
  24. #include "php.h"
  25. }
  26. #include "php_v8js_macros.h"
  27. #include <v8.h>
  28. #include <map>
  29. #include <vector>
  30. /* global.exit - terminate execution */
  31. V8JS_METHOD(exit) /* {{{ */
  32. {
  33. v8::V8::TerminateExecution();
  34. return v8::Undefined();
  35. }
  36. /* }}} */
  37. /* global.sleep - sleep for passed seconds */
  38. V8JS_METHOD(sleep) /* {{{ */
  39. {
  40. php_sleep(args[0]->Int32Value());
  41. return v8::Undefined();
  42. }
  43. /* }}} */
  44. /* global.print - php print() */
  45. V8JS_METHOD(print) /* {{{ */
  46. {
  47. int ret = 0;
  48. TSRMLS_FETCH();
  49. for (int i = 0; i < args.Length(); i++) {
  50. v8::String::Utf8Value str(args[i]);
  51. const char *cstr = ToCString(str);
  52. ret = PHPWRITE(cstr, strlen(cstr));
  53. }
  54. return V8JS_INT(ret);
  55. }
  56. /* }}} */
  57. static void _php_v8js_dumper(v8::Local<v8::Value> var, int level TSRMLS_DC) /* {{{ */
  58. {
  59. v8::String::Utf8Value str(var->ToDetailString());
  60. const char *valstr = ToCString(str);
  61. size_t valstr_len = (valstr) ? strlen(valstr) : 0;
  62. if (level > 1) {
  63. php_printf("%*c", (level - 1) * 2, ' ');
  64. }
  65. if (var->IsString())
  66. {
  67. php_printf("string(%d) \"%s\"\n", valstr_len, valstr);
  68. }
  69. else if (var->IsBoolean())
  70. {
  71. php_printf("bool(%s)\n", valstr);
  72. }
  73. else if (var->IsInt32() || var->IsUint32())
  74. {
  75. php_printf("int(%s)\n", valstr);
  76. }
  77. else if (var->IsNumber())
  78. {
  79. php_printf("float(%s)\n", valstr);
  80. }
  81. else if (var->IsDate())
  82. {
  83. php_printf("Date(%s)\n", valstr);
  84. }
  85. #if PHP_V8_API_VERSION >= 2003007
  86. else if (var->IsRegExp())
  87. {
  88. php_printf("RegExp(%s)\n", valstr);
  89. }
  90. #endif
  91. else if (var->IsArray())
  92. {
  93. v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(var);
  94. uint32_t length = array->Length();
  95. php_printf("array(%d) {\n", length);
  96. for (unsigned i = 0; i < length; i++) {
  97. php_printf("%*c[%d] =>\n", level * 2, ' ', i);
  98. _php_v8js_dumper(array->Get(i), level + 1 TSRMLS_CC);
  99. }
  100. if (level > 1) {
  101. php_printf("%*c", (level - 1) * 2, ' ');
  102. }
  103. ZEND_PUTS("}\n");
  104. }
  105. else if (var->IsObject())
  106. {
  107. v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(var);
  108. V8JS_GET_CLASS_NAME(cname, object);
  109. if (var->IsFunction())
  110. {
  111. v8::String::Utf8Value csource(object->ToString());
  112. php_printf("object(%s)#%d {\n%*c%s\n", ToCString(cname), object->GetIdentityHash(), level * 2 + 2, ' ', ToCString(csource));
  113. }
  114. else
  115. {
  116. v8::Local<v8::Array> keys = object->GetPropertyNames();
  117. uint32_t length = keys->Length();
  118. php_printf("object(%s)#%d (%d) {\n", ToCString(cname), object->GetIdentityHash(), length);
  119. for (unsigned i = 0; i < length; i++) {
  120. v8::Local<v8::String> key = keys->Get(i)->ToString();
  121. v8::String::Utf8Value kname(key);
  122. php_printf("%*c[\"%s\"] =>\n", level * 2, ' ', ToCString(kname));
  123. _php_v8js_dumper(object->Get(key), level + 1 TSRMLS_CC);
  124. }
  125. }
  126. if (level > 1) {
  127. php_printf("%*c", (level - 1) * 2, ' ');
  128. }
  129. ZEND_PUTS("}\n");
  130. }
  131. else /* null, undefined, etc. */
  132. {
  133. php_printf("<%s>\n", valstr);
  134. }
  135. }
  136. /* }}} */
  137. /* global.var_dump - Dump JS values */
  138. V8JS_METHOD(var_dump) /* {{{ */
  139. {
  140. int i;
  141. TSRMLS_FETCH();
  142. for (int i = 0; i < args.Length(); i++) {
  143. _php_v8js_dumper(args[i], 1 TSRMLS_CC);
  144. }
  145. return V8JS_NULL;
  146. }
  147. /* }}} */
  148. // TODO: Put this in php_v8js_context
  149. std::map<char *, v8::Handle<v8::Object> > modules_loaded;
  150. std::vector<char *> modules_stack;
  151. V8JS_METHOD(require)
  152. {
  153. //v8::Persistent<v8::Value> module_name_value_v8 = v8::Persistent<v8::Value>::New(args[0]->ToObject());
  154. v8::String::Utf8Value module_name_v8(args[0]);
  155. // Make sure to duplicate the module name string so it doesn't get freed by the V8 garbage collector
  156. char *module_name = strdup(ToCString(module_name_v8));
  157. // Check for module cyclic dependencies
  158. for (std::vector<char *>::iterator it = modules_stack.begin(); it != modules_stack.end(); ++it)
  159. {
  160. if (!strcmp(*it, module_name)) {
  161. return v8::ThrowException(v8::String::New("Module cyclic dependency"));
  162. }
  163. }
  164. // If we have already loaded and cached this module then use it
  165. if (modules_loaded.count(module_name) > 0) {
  166. return modules_loaded[module_name];
  167. }
  168. // Get the extension context
  169. v8::Handle<v8::External> data = v8::Handle<v8::External>::Cast(args.Data());
  170. php_v8js_ctx *c = static_cast<php_v8js_ctx*>(data->Value());
  171. // Check that we have a module loader
  172. if (c->module_loader == NULL) {
  173. return v8::ThrowException(v8::String::New("No module loader"));
  174. }
  175. // Callback to PHP to load the module code
  176. zval module_code;
  177. zval *module_name_zend;
  178. MAKE_STD_ZVAL(module_name_zend);
  179. ZVAL_STRING(module_name_zend, module_name, 1);
  180. zval* params[] = { module_name_zend };
  181. if (FAILURE == call_user_function(EG(function_table), NULL, c->module_loader, &module_code, 1, params TSRMLS_CC)) {
  182. return v8::ThrowException(v8::String::New("Module loader callback failed"));
  183. }
  184. // Create a template for the global object and set the built-in global functions
  185. v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
  186. global->Set(v8::String::New("print"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);
  187. global->Set(v8::String::New("require"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);
  188. // Add the exports object in which the module returns its API
  189. v8::Handle<v8::ObjectTemplate> exports_template = v8::ObjectTemplate::New();
  190. v8::Handle<v8::Object> exports = exports_template->NewInstance();
  191. global->Set(v8::String::New("exports"), exports);
  192. // Each module gets its own context so different modules do not affect each other
  193. v8::Persistent<v8::Context> context = v8::Context::New(NULL, global);
  194. // Catch JS exceptions
  195. v8::TryCatch try_catch;
  196. // Enter the module context
  197. v8::Context::Scope scope(context);
  198. v8::HandleScope handle_scope;
  199. // Set script identifier
  200. v8::Local<v8::String> sname = V8JS_SYM("require");
  201. // TODO: Load module code here
  202. v8::Local<v8::String> source = v8::String::New(Z_STRVAL(module_code));
  203. // Create and compile script
  204. v8::Local<v8::Script> script = v8::Script::New(source, sname);
  205. // The script will be empty if there are compile errors
  206. if (script.IsEmpty()) {
  207. return v8::ThrowException(v8::String::New("Module script compile failed"));
  208. }
  209. // Add this module to the stack
  210. modules_stack.push_back(module_name);
  211. // Run script
  212. v8::Local<v8::Value> result = script->Run();
  213. // Remove this module from the stack
  214. modules_stack.pop_back();
  215. // Script possibly terminated, return immediately
  216. if (!try_catch.CanContinue()) {
  217. return v8::ThrowException(v8::String::New("Module script compile failed"));
  218. }
  219. // Handle runtime JS exceptions
  220. if (try_catch.HasCaught()) {
  221. // Rethrow the exception back to JS
  222. return try_catch.ReThrow();
  223. }
  224. // Cache the module so it doesn't need to be compiled and run again
  225. modules_loaded[module_name] = handle_scope.Close(exports);
  226. return modules_loaded[module_name];
  227. }
  228. void php_v8js_register_methods(v8::Handle<v8::ObjectTemplate> global, php_v8js_ctx *c) /* {{{ */
  229. {
  230. global->Set(V8JS_SYM("exit"), v8::FunctionTemplate::New(V8JS_MN(exit)), v8::ReadOnly);
  231. global->Set(V8JS_SYM("sleep"), v8::FunctionTemplate::New(V8JS_MN(sleep)), v8::ReadOnly);
  232. global->Set(V8JS_SYM("print"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);
  233. global->Set(V8JS_SYM("var_dump"), v8::FunctionTemplate::New(V8JS_MN(var_dump)), v8::ReadOnly);
  234. global->Set(V8JS_SYM("require"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);
  235. }
  236. /* }}} */
  237. /*
  238. * Local variables:
  239. * tab-width: 4
  240. * c-basic-offset: 4
  241. * End:
  242. * vim600: noet sw=4 ts=4 fdm=marker
  243. * vim<600: noet sw=4 ts=4
  244. */