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 <js/RootingAPI.h>
12 : : #include <js/TypeDecls.h>
13 : :
14 : : #include "gjs/jsapi-util.h"
15 : : #include "gjs/native.h"
16 : : #include "util/log.h"
17 : :
18 : 1116 : void Gjs::NativeModuleDefineFuncs::add(const char* module_id,
19 : : DefineModuleFunc func) {
20 : : bool inserted;
21 : 1116 : std::tie(std::ignore, inserted) = m_modules.insert({module_id, func});
22 [ - + ]: 1116 : if (!inserted) {
23 : 0 : gjs_warning("A second native module tried to register the same id '{}'",
24 : : module_id);
25 : 0 : return;
26 : : }
27 : :
28 : 1116 : gjs_debug(GJS_DEBUG_NATIVE, "Registered native JS module '{}'", module_id);
29 : : }
30 : :
31 : : /**
32 : : * is_registered:
33 : : * @module_id: name of the module
34 : : *
35 : : * Checks if a native module corresponding to @module_id has already been
36 : : * registered. This is used to check to see if a name is a builtin module
37 : : * without starting to try and load it.
38 : : */
39 : 873 : bool Gjs::NativeModuleDefineFuncs::is_registered(const char* module_id) const {
40 : 2619 : return m_modules.contains(module_id);
41 : : }
42 : :
43 : : /**
44 : : * define:
45 : : * @cx: the #JSContext
46 : : * @module_id: Name under which the module was registered with add()
47 : : * @module_out: Return location for a #JSObject
48 : : *
49 : : * Loads a builtin native-code module called @name into @module_out by calling
50 : : * the function to define it.
51 : : *
52 : : * Returns: true on success, false if an exception was thrown.
53 : : */
54 : 653 : bool Gjs::NativeModuleDefineFuncs::define(
55 : : JSContext* cx, const char* module_id,
56 : : JS::MutableHandleObject module_out) const {
57 : 653 : gjs_debug(GJS_DEBUG_NATIVE, "Defining native module '{}'", module_id);
58 : :
59 : 1306 : const auto& iter = m_modules.find(module_id);
60 : :
61 [ - + ]: 653 : if (iter == m_modules.end()) {
62 : 0 : gjs_throw(cx, "No native module '{}' has registered itself", module_id);
63 : 0 : return false;
64 : : }
65 : :
66 : 653 : return iter->second(cx, module_out);
67 : : }
|