summaryrefslogtreecommitdiff
path: root/gi/js-value-inl.h
blob: debfe15274118467f0f6bfb3d49a916e43c12345 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
// SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
// SPDX-FileCopyrightText: 2020 Marco Trevisan <marco.trevisan@canonical.com>

#pragma once

#include <config.h>

#include <stdint.h>

#include <cmath>  // for isnan
#include <limits>

#include <girepository.h>
#include <glib-object.h>
#include <glib.h>

#include <js/BigInt.h>
#include <js/Conversions.h>
#include <js/RootingAPI.h>
#include <js/TypeDecls.h>
#include <js/Utility.h>  // for UniqueChars

#include "gi/gtype.h"
#include "gi/value.h"
#include "gjs/jsapi-util.h"
#include "gjs/macros.h"

namespace Gjs {

template <typename T>
struct TypeWrapper {
    constexpr TypeWrapper() : m_value(0) {}
    explicit constexpr TypeWrapper(T v) : m_value(v) {}
    constexpr operator T() const { return m_value; }
    constexpr operator T() { return m_value; }

 private:
    T m_value;
};

namespace JsValueHolder {

template <typename T1, typename T2>
constexpr bool comparable_types() {
    return std::is_arithmetic_v<T1> == std::is_arithmetic_v<T2> &&
           std::is_signed_v<T1> == std::is_signed_v<T2>;
}

template <typename T, typename Container>
constexpr bool type_fits() {
    if constexpr (comparable_types<T, Container>()) {
        return (std::is_integral_v<T> == std::is_integral_v<Container> &&
                std::numeric_limits<T>::max() <=
                    std::numeric_limits<Container>::max() &&
                std::numeric_limits<T>::lowest() >=
                    std::numeric_limits<Container>::lowest());
    }

    return false;
}

/* The tag is needed to disambiguate types such as gboolean and GType
 * which are in fact typedef's of other generic types.
 * Setting a tag for a type allows to perform proper specialization. */
template <typename T, GITypeTag TAG>
constexpr auto get_strict() {
    if constexpr (TAG != GI_TYPE_TAG_VOID) {
        if constexpr (std::is_same_v<T, GType> && TAG == GI_TYPE_TAG_GTYPE)
            return GType{};
        else if constexpr (std::is_same_v<T, gboolean> &&
                           TAG == GI_TYPE_TAG_BOOLEAN)
            return gboolean{};
        else
            return;
    } else {
        if constexpr (std::is_same_v<T, char32_t>)
            return char32_t{};
        else if constexpr (type_fits<T, int32_t>())
            return int32_t{};
        else if constexpr (type_fits<T, uint32_t>())
            return uint32_t{};
        else if constexpr (type_fits<T, int64_t>())
            return int64_t{};
        else if constexpr (type_fits<T, uint64_t>())
            return uint64_t{};
        else if constexpr (type_fits<T, double>())
            return double{};
        else
            return T{};
    }
}

template <typename T>
constexpr auto get_relaxed() {
    if constexpr (std::is_same_v<T, int64_t> || std::is_same_v<T, uint64_t>)
        return TypeWrapper<T>{};
    else if constexpr (type_fits<T, int32_t>())
        return int32_t{};
    else if constexpr (type_fits<T, uint16_t>())
        return uint32_t{};
    else if constexpr (std::is_arithmetic_v<T>)
        return double{};
    else
        return T{};
}

template <typename T, GITypeTag TAG = GI_TYPE_TAG_VOID>
using Strict = decltype(JsValueHolder::get_strict<T, TAG>());

template <typename T>
using Relaxed = decltype(JsValueHolder::get_relaxed<T>());

}  // namespace JsValueHolder


template <typename T, typename MODE = JsValueHolder::Relaxed<T>>
constexpr bool type_has_js_getter() {
    return std::is_same_v<T, MODE>;
}

/* Avoid implicit conversions */
template <GITypeTag TAG = GI_TYPE_TAG_VOID, typename T>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c(JSContext*,
                                                      const JS::HandleValue&,
                                                      T*) = delete;

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c(
    JSContext* cx, const JS::HandleValue& value, int32_t* out) {
    return JS::ToInt32(cx, value, out);
}

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c(
    JSContext* cx, const JS::HandleValue& value, uint32_t* out) {
    return JS::ToUint32(cx, value, out);
}

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c(
    JSContext* cx, const JS::HandleValue& value, char32_t* out) {
    uint32_t tmp;
    bool retval = JS::ToUint32(cx, value, &tmp);
    *out = tmp;
    return retval;
}

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c(
    JSContext* cx, const JS::HandleValue& value, int64_t* out) {
    if (value.isBigInt()) {
        *out = JS::ToBigInt64(value.toBigInt());
        return true;
    }
    return JS::ToInt64(cx, value, out);
}

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c(
    JSContext* cx, const JS::HandleValue& value, uint64_t* out) {
    if (value.isBigInt()) {
        *out = JS::ToBigUint64(value.toBigInt());
        return true;
    }
    return JS::ToUint64(cx, value, out);
}

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c(
    JSContext* cx, const JS::HandleValue& value, double* out) {
    return JS::ToNumber(cx, value, out);
}

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c<GI_TYPE_TAG_BOOLEAN>(
    JSContext*, const JS::HandleValue& value, gboolean* out) {
    *out = !!JS::ToBoolean(value);
    return true;
}

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c<GI_TYPE_TAG_GTYPE>(
    JSContext* cx, const JS::HandleValue& value, GType* out) {
    if (!value.isObject())
        return false;

    JS::RootedObject elem_obj(cx);
    elem_obj = &value.toObject();

    if (!gjs_gtype_get_actual_gtype(cx, elem_obj, out))
        return false;

    if (*out == G_TYPE_INVALID)
        return false;

    return true;
}

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c(
    JSContext* cx, const JS::HandleValue& value, GValue* out) {
    *out = G_VALUE_INIT;
    return gjs_value_to_g_value(cx, value, out);
}

template <>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c(
    JSContext* cx, const JS::HandleValue& value, char** out) {
    JS::UniqueChars tmp_result = gjs_string_to_utf8(cx, value);

    if (!tmp_result)
        return false;

    *out = g_strdup(tmp_result.get());
    return true;
}

template <typename BigT>
[[nodiscard]] inline constexpr BigT max_safe_big_number() {
    return (BigT(1) << std::numeric_limits<double>::digits) - 1;
}

template <typename BigT>
[[nodiscard]] inline constexpr BigT min_safe_big_number() {
    if constexpr (std::is_signed_v<BigT>)
        return -(max_safe_big_number<BigT>());

    return std::numeric_limits<BigT>::lowest();
}

template <typename WantedType, typename T>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c_checked(
    JSContext* cx, const JS::HandleValue& value, T* out, bool* out_of_range) {
    static_assert(std::numeric_limits<T>::max() >=
                          std::numeric_limits<WantedType>::max() &&
                      std::numeric_limits<T>::lowest() <=
                          std::numeric_limits<WantedType>::lowest(),
                  "Container can't contain wanted type");

    if constexpr (std::is_same_v<WantedType, uint64_t> ||
                  std::is_same_v<WantedType, int64_t>) {
        if (out_of_range) {
            JS::BigInt* bi = nullptr;
            *out_of_range = false;

            if (value.isBigInt()) {
                bi = value.toBigInt();
            } else if (value.isNumber()) {
                double number = value.toNumber();
                if (!std::isfinite(number)) {
                    *out = 0;
                    return true;
                }
                number = std::trunc(number);
                bi = JS::NumberToBigInt(cx, number);
                if (!bi)
                    return false;
            }

            if (bi) {
                *out_of_range = Gjs::bigint_is_out_of_range(bi, out);
                return true;
            }
        }
    }

    if constexpr (std::is_same_v<WantedType, T>)
        return js_value_to_c(cx, value, out);

    // JS::ToIntNN() converts undefined, NaN, infinity to 0
    if constexpr (std::is_integral_v<WantedType>) {
        if (value.isUndefined() ||
            (value.isDouble() && !std::isfinite(value.toDouble()))) {
            *out = 0;
            return true;
        }
    }

    if constexpr (std::is_arithmetic_v<T>) {
        bool ret = js_value_to_c(cx, value, out);
        if (out_of_range) {
            // Infinity and NaN preserved between floating point types
            if constexpr (std::is_floating_point_v<WantedType> &&
                          std::is_floating_point_v<T>) {
                if (!std::isfinite(*out)) {
                    *out_of_range = false;
                    return ret;
                }
            }

            *out_of_range =
                (*out >
                     static_cast<T>(std::numeric_limits<WantedType>::max()) ||
                 *out <
                     static_cast<T>(std::numeric_limits<WantedType>::lowest()));

            if constexpr (std::is_integral_v<WantedType> &&
                          std::is_floating_point_v<T>)
                *out_of_range |= std::isnan(*out);
        }
        return ret;
    }
}

template <typename WantedType>
GJS_JSAPI_RETURN_CONVENTION inline bool js_value_to_c_checked(
    JSContext* cx, const JS::HandleValue& value, TypeWrapper<WantedType>* out,
    bool* out_of_range) {
    static_assert(std::is_integral_v<WantedType>);

    WantedType wanted_out;
    if (!js_value_to_c_checked<WantedType>(cx, value, &wanted_out,
                                           out_of_range))
        return false;

    *out = TypeWrapper<WantedType>{wanted_out};

    return true;
}

}  // namespace Gjs