Branch data Line data Source code
1 : : /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
2 : : // SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
3 : : // SPDX-FileCopyrightText: 2008-2010 litl, LLC
4 : :
5 : : #include <config.h>
6 : :
7 : : #include <tuple> // for tie
8 : : #include <unordered_map>
9 : : #include <utility> // for ignore
10 : :
11 : : #include <glib.h>
12 : :
13 : : #include <js/RootingAPI.h>
14 : : #include <js/TypeDecls.h>
15 : :
16 : : #include "gjs/jsapi-util.h"
17 : : #include "gjs/native.h"
18 : : #include "util/log.h"
19 : :
20 : 1026 : void Gjs::NativeModuleDefineFuncs::add(const char* module_id,
21 : : GjsDefineModuleFunc func) {
22 : : bool inserted;
23 : 1026 : std::tie(std::ignore, inserted) = m_modules.insert({module_id, func});
24 [ - + ]: 1026 : if (!inserted) {
25 : 0 : g_warning("A second native module tried to register the same id '%s'",
26 : : module_id);
27 : 0 : return;
28 : : }
29 : :
30 : 1026 : gjs_debug(GJS_DEBUG_NATIVE,
31 : : "Registered native JS module '%s'",
32 : : module_id);
33 : : }
34 : :
35 : : /**
36 : : * is_registered:
37 : : * @name: name of the module
38 : : *
39 : : * Checks if a native module corresponding to @name has already
40 : : * been registered. This is used to check to see if a name is a
41 : : * builtin module without starting to try and load it.
42 : : */
43 : 861 : bool Gjs::NativeModuleDefineFuncs::is_registered(const char* name) const {
44 : 2583 : return m_modules.count(name) > 0;
45 : : }
46 : :
47 : : /**
48 : : * define:
49 : : * @cx: the #JSContext
50 : : * @id: Name under which the module was registered with add()
51 : : * @module_out: Return location for a #JSObject
52 : : *
53 : : * Loads a builtin native-code module called @name into @module_out by calling
54 : : * the function to define it.
55 : : *
56 : : * Returns: true on success, false if an exception was thrown.
57 : : */
58 : 589 : bool Gjs::NativeModuleDefineFuncs::define(
59 : : JSContext* cx, const char* id, JS::MutableHandleObject module_out) const {
60 : 589 : gjs_debug(GJS_DEBUG_NATIVE, "Defining native module '%s'", id);
61 : :
62 : 1178 : const auto& iter = m_modules.find(id);
63 : :
64 [ - + ]: 589 : if (iter == m_modules.end()) {
65 : 0 : gjs_throw(cx, "No native module '%s' has registered itself", id);
66 : 0 : return false;
67 : : }
68 : :
69 : 589 : return iter->second(cx, module_out);
70 : : }
|