[gjs/wip/ptomato/mozjs52: 1/37] js: Use a special object for modules



commit 5cb6eff7acc6e386b00e8a9f361eba1add62327d
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                           |   57 +++------
 gjs/module.cpp                             |  194 ++++++++++++++++++++++++++++
 gjs/module.h                               |   41 ++++++
 installed-tests/js/jsunit.gresources.xml   |    1 +
 installed-tests/js/modules/lexicalScope.js |   15 ++
 installed-tests/js/testImporter.js         |   19 +++
 7 files changed, 292 insertions(+), 37 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..120d147 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,34 +186,18 @@ 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
 seal_import(JSContext       *cx,
             JS::HandleObject obj,
+            JS::HandleId     id,
             const char      *name)
 {
     JS::Rooted<JSPropertyDescriptor> descr(cx);
 
-    if (!JS_GetOwnPropertyDescriptor(cx, obj, name, &descr) ||
+    if (!JS_GetOwnPropertyDescriptorById(cx, obj, id, &descr) ||
         descr.object() == NULL) {
         gjs_debug(GJS_DEBUG_IMPORTER,
                   "Failed to get attributes to seal '%s' in importer",
@@ -223,10 +208,10 @@ seal_import(JSContext       *cx,
     /* COMPAT: in mozjs45 use .setConfigurable(false) and the form of
      * JS_DefineProperty that takes the JSPropertyDescriptor directly */
 
-    if (!JS_DefineProperty(cx, descr.object(), name, descr.value(),
-                           descr.attributes() | JSPROP_PERMANENT,
-                           JS_PROPERTYOP_GETTER(descr.getter()),
-                           JS_PROPERTYOP_SETTER(descr.setter()))) {
+    if (!JS_DefinePropertyById(cx, descr.object(), id, descr.value(),
+                               descr.attributes() | JSPROP_PERMANENT,
+                               JS_PROPERTYOP_GETTER(descr.getter()),
+                               JS_PROPERTYOP_SETTER(descr.setter()))) {
         gjs_debug(GJS_DEBUG_IMPORTER,
                   "Failed to redefine attributes to seal '%s' in importer",
                   name);
@@ -327,10 +312,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 +371,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,
@@ -456,18 +440,16 @@ import_symbol_from_init_js(JSContext       *cx,
 static bool
 import_file_on_module(JSContext       *context,
                       JS::HandleObject obj,
+                      JS::HandleId     id,
                       const char      *name,
                       GFile           *file)
 {
     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, id, file));
+    if (!module_obj)
         goto out;
 
     full_path = g_file_get_parse_name (file);
@@ -478,7 +460,7 @@ import_file_on_module(JSContext       *context,
                            0, 0))
         goto out;
 
-    if (!seal_import(context, obj, name))
+    if (!seal_import(context, obj, id, name))
         goto out;
 
     retval = true;
@@ -495,6 +477,7 @@ static bool
 do_import(JSContext       *context,
           JS::HandleObject obj,
           Importer        *priv,
+          JS::HandleId     id,
           const char      *name)
 {
     char *filename;
@@ -617,7 +600,7 @@ do_import(JSContext       *context,
             continue;
         }
 
-        if (import_file_on_module (context, obj, name, gfile)) {
+        if (import_file_on_module(context, obj, id, name, gfile)) {
             gjs_debug(GJS_DEBUG_IMPORTER,
                       "successfully imported module '%s'", name);
             result = true;
@@ -817,7 +800,7 @@ importer_resolve(JSContext        *context,
     }
 
     JSAutoRequest ar(context);
-    if (!do_import(context, obj, priv, name))
+    if (!do_import(context, obj, priv, id, name))
         return false;
 
     *resolved = true;
diff --git a/gjs/module.cpp b/gjs/module.cpp
new file mode 100644
index 0000000..ed53312
--- /dev/null
+++ b/gjs/module.cpp
@@ -0,0 +1,194 @@
+/* -*- 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 {
+    /* Private data accessors */
+
+    enum Slot {
+        NAME,
+        NSLOTS
+    };
+
+    static inline GjsAutoJSChar
+    module_name(JSContext *cx,
+                JSObject  *module)
+    {
+        JS::Value v_name = JS_GetReservedSlot(module, Slot::NAME);
+        g_assert(v_name.isString());
+        GjsAutoJSChar retval(cx);
+        bool ok = gjs_string_to_utf8(cx, v_name, &retval);
+        g_assert(ok);
+        return retval;
+    }
+
+    /* Creates a JS module object. Use instead of the class's constructor */
+    static JSObject *
+    create(JSContext   *cx,
+           JS::HandleId name)
+    {
+        JSObject *module = JS_NewObject(cx, &GjsModule::klass);
+        JS::RootedValue v_name(cx);
+        if (!JS_IdToValue(cx, name, &v_name))
+            return nullptr;
+        JS_SetReservedSlot(module, Slot::NAME, v_name);
+        return module;
+    }
+
+    /* Defines the empty module as a property on the importer */
+    static bool
+    define_import(JSContext       *cx,
+                  JS::HandleObject module,
+                  JS::HandleObject importer,
+                  JS::HandleId     name)
+    {
+        if (!JS_DefinePropertyById(cx, importer, name, module,
+                                   GJS_MODULE_PROP_FLAGS & ~JSPROP_PERMANENT)) {
+            GjsAutoJSChar n = module_name(cx, module);
+            gjs_debug(GJS_DEBUG_IMPORTER, "Failed to define '%s' in importer",
+                      n.get());
+            return false;
+        }
+
+        return true;
+    }
+
+    /* Carries out the actual execution of the module code */
+    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);
+
+        GjsAutoJSChar n = module_name(cx, module);
+        gjs_debug(GJS_DEBUG_IMPORTER, "Importing module %s succeeded", n.get());
+
+        return true;
+    }
+
+    /* Loads JS code from a file and imports it */
+    static bool
+    import_file(JSContext       *cx,
+                JS::HandleObject module,
+                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_HAS_RESERVED_SLOTS(Slot::NSLOTS),
+    };
+
+public:
+
+    /* Carries out the import operation */
+    static JSObject *
+    import(JSContext       *cx,
+           JS::HandleObject importer,
+           JS::HandleId     name,
+           GFile           *file)
+    {
+        JS::RootedObject module(cx, GjsModule::create(cx, name));
+        if (!module ||
+            !define_import(cx, module, importer, name) ||
+            !import_file(cx, module, file))
+            return nullptr;
+
+        return module;
+    }
+};
+
+/**
+ * gjs_module_import:
+ * @cx: the JS context
+ * @importer: the JS importer object, parent of the module to be imported
+ * @name: module name
+ * @file: location of the file to import
+ *
+ * Carries out an import of a GJS module.
+ * Defines a property @name on @importer pointing to the module object, which
+ * is necessary in the case of cyclic imports.
+ * This property is not permanent; the caller is responsible for making it
+ * permanent if the import succeeds.
+ *
+ * Returns: the JS module object, or nullptr on failure.
+ */
+JSObject *
+gjs_module_import(JSContext       *cx,
+                  JS::HandleObject importer,
+                  JS::HandleId     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..ae3e238
--- /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,
+                  JS::HandleId     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..5f15d4e
--- /dev/null
+++ b/installed-tests/js/modules/lexicalScope.js
@@ -0,0 +1,15 @@
+/* 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;
+
+// It's not clear whether this should be exported in ES6, but for compatibility
+// it should be:
+this.d = 4;
diff --git a/installed-tests/js/testImporter.js b/installed-tests/js/testImporter.js
index 6b73643..cad4773 100644
--- a/installed-tests/js/testImporter.js
+++ b/installed-tests/js/testImporter.js
@@ -156,6 +156,25 @@ describe('Importer', function () {
         expect(ModUnicode.uval).toEqual('const \u2665 utf8');
     });
 
+    describe("properties defined in the module's lexical scope", function () {
+        let LexicalScope;
+
+        beforeAll(function () {
+            LexicalScope = imports.lexicalScope;
+        });
+
+        it('can be accessed', function () {
+            expect(LexicalScope.a).toEqual(1);
+            expect(LexicalScope.b).toEqual(2);
+            expect(LexicalScope.c).toEqual(3);
+            expect(LexicalScope.d).toEqual(4);
+        });
+
+        it('does not leak module properties into the global scope', function () {
+            expect(window.d).not.toBeDefined();
+        });
+    });
+
     describe('enumerating modules', function () {
         let keys;
         beforeEach(function () {


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