Update Iot.js
[platform/upstream/iotjs.git] / src / iotjs_module.c
1 /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16
17 #include "iotjs_def.h"
18 #include "iotjs_module.h"
19
20
21 typedef struct {
22   ModuleKind kind;
23   iotjs_jval_t jmodule;
24   register_func fn_register;
25 } iotjs_module_t;
26
27
28 static iotjs_module_t modules[MODULE_COUNT];
29
30
31 #define DECLARE_MODULE_INITIALIZER(upper, Camel, lower) \
32   iotjs_jval_t Init##Camel();
33
34 MAP_MODULE_LIST(DECLARE_MODULE_INITIALIZER)
35
36 #undef DECLARE_MODULE_INITIALIZER
37
38
39 #define INIT_MODULE_LIST(upper, Camel, lower)                    \
40   modules[MODULE_##upper].kind = MODULE_##upper;                 \
41   modules[MODULE_##upper].jmodule = *iotjs_jval_get_undefined(); \
42   modules[MODULE_##upper].fn_register = Init##Camel;
43
44 void iotjs_module_list_init() {
45   MAP_MODULE_LIST(INIT_MODULE_LIST)
46 }
47
48 #undef INIT_MODULE_LIST
49
50
51 #define CLENUP_MODULE_LIST(upper, Camel, lower)                   \
52   if (!iotjs_jval_is_undefined(&modules[MODULE_##upper].jmodule)) \
53     iotjs_jval_destroy(&modules[MODULE_##upper].jmodule);
54
55 void iotjs_module_list_cleanup() {
56   MAP_MODULE_LIST(CLENUP_MODULE_LIST)
57 }
58
59 #undef CLENUP_MODULE_LIST
60
61
62 const iotjs_jval_t* iotjs_module_initialize_if_necessary(ModuleKind kind) {
63   IOTJS_ASSERT(kind < MODULE_COUNT);
64   IOTJS_ASSERT(&modules[kind].fn_register != NULL);
65
66   if (iotjs_jval_is_undefined(&modules[kind].jmodule)) {
67     modules[kind].jmodule = modules[kind].fn_register();
68   }
69
70   return iotjs_module_get(kind);
71 }
72
73
74 const iotjs_jval_t* iotjs_module_get(ModuleKind kind) {
75   IOTJS_ASSERT(kind < MODULE_COUNT);
76   IOTJS_ASSERT(!iotjs_jval_is_undefined(&modules[kind].jmodule));
77   return &modules[kind].jmodule;
78 }