[gjs/wip/ptomato/mozjs52: 8/42] js: Use a special object for modules



commit 43f58e609cfb9fba2476266cfdb4f7a5dae955d5
Author: Philip Chimento <philip chimento gmail com>
Date:   Fri Jun 23 22:22:43 2017 -0700

    js: Use a special object for modules
    
    This introduces a new GjsModule class for imported module objects. The
    functionality is unchanged, but we will use this as a basis for making
    bindings from modules' lexical scopes (variables declared with 'let' and
    'const') available for compatibility. In SpiderMonkey 45, these will stop
    being exported as properties, as per ES6 standard.
    
    The function GjsModule::evaluate_import() contains duplicated code with
    gjs_eval_with_scope(), but that will change when we have to import the
    lexical scope separately.

 gjs-srcs.mk                                |    2 +
 gjs/importer.cpp                           |   38 ++-----
 gjs/module.cpp                             |  154 ++++++++++++++++++++++++++++
 gjs/module.h                               |   41 ++++++++
 installed-tests/js/jsunit.gresources.xml   |    1 +
 installed-tests/js/modules/lexicalScope.js |   12 ++
 installed-tests/js/testImporter.js         |    7 ++
 7 files changed, 226 insertions(+), 29 deletions(-)
---
diff --git a/gjs-srcs.mk b/gjs-srcs.mk
index aa11de5..503c5c9 100644
--- a/gjs-srcs.mk
+++ b/gjs-srcs.mk
@@ -71,6 +71,8 @@ gjs_srcs =                            \
        gjs/jsapi-wrapper.h             \
        gjs/mem.h                       \
        gjs/mem.cpp                     \
+       gjs/module.h                    \
+       gjs/module.cpp                  \
        gjs/native.cpp                  \
        gjs/native.h                    \
        gjs/runtime.cpp                 \
diff --git a/gjs/importer.cpp b/gjs/importer.cpp
index ff592c1..55a6fa7 100644
--- a/gjs/importer.cpp
+++ b/gjs/importer.cpp
@@ -30,6 +30,7 @@
 #include "jsapi-class.h"
 #include "jsapi-wrapper.h"
 #include "mem.h"
+#include "module.h"
 #include "native.h"
 
 #include <gio/gio.h>
@@ -185,24 +186,7 @@ import_directory(JSContext       *context,
     return importer != NULL;
 }
 
-static bool
-define_import(JSContext       *context,
-              JS::HandleObject obj,
-              JS::HandleObject module_obj,
-              const char      *name)
-{
-    if (!JS_DefineProperty(context, obj, name, module_obj,
-                           GJS_MODULE_PROP_FLAGS & ~JSPROP_PERMANENT)) {
-        gjs_debug(GJS_DEBUG_IMPORTER,
-                  "Failed to define '%s' in importer",
-                  name);
-        return false;
-    }
-
-    return true;
-}
-
-/* Make the property we set in define_import permament;
+/* Make the property we set in gjs_module_import() permament;
  * we do this after the import succesfully completes.
  */
 static bool
@@ -327,10 +311,9 @@ import_native_file(JSContext       *context,
 }
 
 static bool
-import_file(JSContext       *context,
-            const char      *name,
-            GFile           *file,
-            JS::HandleObject module_obj)
+import_module_init(JSContext       *context,
+                   GFile           *file,
+                   JS::HandleObject module_obj)
 {
     bool ret = false;
     char *script = NULL;
@@ -387,7 +370,7 @@ load_module_init(JSContext       *context,
 
     JS::RootedObject module_obj(context, JS_NewPlainObject(context));
     GjsAutoUnref<GFile> file = g_file_new_for_commandline_arg(full_path);
-    if (!import_file (context, "__init__", file, module_obj))
+    if (!import_module_init(context, file, module_obj))
         return module_obj;
 
     gjs_object_define_property(context, in_object,
@@ -462,12 +445,9 @@ import_file_on_module(JSContext       *context,
     bool retval = false;
     char *full_path = NULL;
 
-    JS::RootedObject module_obj(context, JS_NewPlainObject(context));
-
-    if (!define_import(context, obj, module_obj, name))
-        goto out;
-
-    if (!import_file(context, name, file, module_obj))
+    JS::RootedObject module_obj(context,
+        gjs_module_import(context, obj, name, file));
+    if (!module_obj)
         goto out;
 
     full_path = g_file_get_parse_name (file);
diff --git a/gjs/module.cpp b/gjs/module.cpp
new file mode 100644
index 0000000..a024083
--- /dev/null
+++ b/gjs/module.cpp
@@ -0,0 +1,154 @@
+/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
+/*
+ * Copyright (c) 2017  Philip Chimento <philip chimento gmail com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#include <gio/gio.h>
+
+#include "jsapi-private.h"
+#include "jsapi-util.h"
+#include "jsapi-wrapper.h"
+#include "module.h"
+#include "util/log.h"
+
+class GjsModule {
+    GjsModule(void) {}
+
+    /* Creates a JS module object and sets GjsModule as the private data */
+    static JSObject *
+    create(JSContext *cx)
+    {
+        return JS_NewObject(cx, &GjsModule::klass);
+    }
+
+    static bool
+    define_import(JSContext       *cx,
+                  JS::HandleObject module,
+                  JS::HandleObject importer,
+                  const char      *name)
+    {
+        if (!JS_DefineProperty(cx, importer, name, module,
+                               GJS_MODULE_PROP_FLAGS & ~JSPROP_PERMANENT)) {
+            gjs_debug(GJS_DEBUG_IMPORTER, "Failed to define '%s' in importer",
+                      name);
+            return false;
+        }
+
+        return true;
+    }
+
+    static bool
+    evaluate_import(JSContext       *cx,
+                    JS::HandleObject module,
+                    const char      *script,
+                    size_t           script_len,
+                    const char      *filename,
+                    int              line_number)
+    {
+        JS::CompileOptions options(cx);
+        options.setUTF8(true)
+               .setFileAndLine(filename, line_number)
+               .setSourceIsLazy(true);
+
+        JS::RootedScript compiled_script(cx);
+        if (!JS::Compile(cx, module, options, script, script_len,
+                         &compiled_script))
+            return false;
+
+        JS::AutoObjectVector scope_chain(cx);
+        scope_chain.append(module);
+        JS::RootedValue ignored_retval(cx);
+        if (!JS_ExecuteScript(cx, scope_chain, compiled_script,
+                              &ignored_retval))
+            return false;
+
+        gjs_schedule_gc_if_needed(cx);
+
+        gjs_debug(GJS_DEBUG_IMPORTER, "Module loading succeeded");
+
+        return true;
+    }
+
+    static bool
+    import_file(JSContext       *cx,
+                JS::HandleObject module,
+                const char      *name,
+                GFile           *file)
+    {
+        GError *error = nullptr;
+        char *unowned_script;
+        size_t script_len = 0;
+        int start_line_number = 1;
+
+        if (!(g_file_load_contents(file, nullptr, &unowned_script, &script_len,
+                                   nullptr, &error))) {
+            gjs_throw_g_error(cx, error);
+            return false;
+        }
+
+        GjsAutoChar script = unowned_script;  /* steals ownership */
+        g_assert(script != nullptr);
+
+        const char *stripped_script =
+            gjs_strip_unix_shebang(script, &script_len, &start_line_number);
+
+        GjsAutoChar full_path = g_file_get_parse_name(file);
+        return evaluate_import(cx, module, stripped_script, script_len,
+                               full_path, start_line_number);
+    }
+
+    /* JSClass operations */
+
+    static constexpr JSClass klass = {
+        "GjsModule",
+        JSCLASS_BACKGROUND_FINALIZE,
+    };
+
+public:
+
+    static JSObject *
+    import(JSContext       *cx,
+           JS::HandleObject importer,
+           const char      *name,
+           GFile           *file)
+    {
+        JS::RootedObject module(cx, GjsModule::create(cx));
+        if (!module)
+            return nullptr;
+
+        if (!define_import(cx, module, importer, name) ||
+            !import_file(cx, module, name, file))
+            return nullptr;
+
+        return module;
+    }
+};
+
+JSObject *
+gjs_module_import(JSContext       *cx,
+                  JS::HandleObject importer,
+                  const char      *name,
+                  GFile           *file)
+{
+    return GjsModule::import(cx, importer, name, file);
+}
+
+decltype(GjsModule::klass) constexpr GjsModule::klass;
diff --git a/gjs/module.h b/gjs/module.h
new file mode 100644
index 0000000..ebed6da
--- /dev/null
+++ b/gjs/module.h
@@ -0,0 +1,41 @@
+/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
+/*
+ * Copyright (c) 2017  Philip Chimento <philip chimento gmail com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef GJS_MODULE_H
+#define GJS_MODULE_H
+
+#include <gio/gio.h>
+
+#include "jsapi-wrapper.h"
+
+G_BEGIN_DECLS
+
+JSObject *
+gjs_module_import(JSContext       *cx,
+                  JS::HandleObject importer,
+                  const char      *name,
+                  GFile           *file);
+
+G_END_DECLS
+
+#endif  /* GJS_MODULE_H */
diff --git a/installed-tests/js/jsunit.gresources.xml b/installed-tests/js/jsunit.gresources.xml
index 3fe08f2..15bd330 100644
--- a/installed-tests/js/jsunit.gresources.xml
+++ b/installed-tests/js/jsunit.gresources.xml
@@ -6,6 +6,7 @@
     <file>minijasmine.js</file>
     <file>modules/alwaysThrows.js</file>
     <file>modules/foobar.js</file>
+    <file>modules/lexicalScope.js</file>
     <file>modules/modunicode.js</file>
     <file>modules/mutualImport/a.js</file>
     <file>modules/mutualImport/b.js</file>
diff --git a/installed-tests/js/modules/lexicalScope.js b/installed-tests/js/modules/lexicalScope.js
new file mode 100644
index 0000000..5e7fc45
--- /dev/null
+++ b/installed-tests/js/modules/lexicalScope.js
@@ -0,0 +1,12 @@
+/* exported a, b, c */
+
+// Tests bindings in the global scope (var) and lexical environment (let, const)
+
+// This should be exported as a property when importing this module
+var a = 1;
+
+// These should not be exported, but for compatibility we will pretend they are
+// for the time being;
+
+let b = 2;
+const c = 3;
diff --git a/installed-tests/js/testImporter.js b/installed-tests/js/testImporter.js
index 6b73643..93ea268 100644
--- a/installed-tests/js/testImporter.js
+++ b/installed-tests/js/testImporter.js
@@ -156,6 +156,13 @@ describe('Importer', function () {
         expect(ModUnicode.uval).toEqual('const \u2665 utf8');
     });
 
+    it("can access properties defined in the module's lexical scope", function () {
+        const LexicalScope = imports.lexicalScope;
+        expect(LexicalScope.a).toEqual(1);
+        expect(LexicalScope.b).toEqual(2);
+        expect(LexicalScope.c).toEqual(3);
+    });
+
     describe('enumerating modules', function () {
         let keys;
         beforeEach(function () {


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]