summaryrefslogtreecommitdiffstats
path: root/source/compiler-core/slang-json-native.cpp
blob: 9c972eba389d2baea9b1fa682cfedc9bdcaa057c (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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#include "slang-json-native.h"

#include "../../slang-com-helper.h"

#include "../core/slang-rtti-util.h"

#include "slang-json-diagnostics.h"

namespace Slang {

/* !!!!!!!!!!!!!!!!!!!!!!!!!!!! JSONToNativeConverter !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */

/* static */Index JSONToNativeConverter::_getFieldCount(const StructRttiInfo* structRttiInfo)
{
    if (structRttiInfo->m_super)
    {
        return _getFieldCount(structRttiInfo->m_super) + structRttiInfo->m_fieldCount;
    }
    else
    {
        return structRttiInfo->m_fieldCount;
    }
}

/* static */Index JSONToNativeConverter::_findFieldIndex(const StructRttiInfo* structRttiInfo, const UnownedStringSlice& fieldName)
{
    if (structRttiInfo->m_super)
    {
        const Index index = _findFieldIndex(structRttiInfo->m_super, fieldName);
        if (index >= 0)
        {
            return index + _getFieldCount(structRttiInfo->m_super);
        }
    }

    ConstArrayView<StructRttiInfo::Field> fields(structRttiInfo->m_fields, structRttiInfo->m_fieldCount);

    Index index = fields.findFirstIndex([fieldName](const StructRttiInfo::Field& field) ->bool { return fieldName == field.m_name; });
    if (index >= 0 && structRttiInfo->m_super)
    {
        index += _getFieldCount(structRttiInfo->m_super);
    }

    return index;
}

SlangResult JSONToNativeConverter::_structToNative(const ConstArrayView<JSONKeyValue>& pairs, const StructRttiInfo* structRttiInfo, void* out, Index& outFieldCount)
{
    Index fieldCount = 0;

    if (structRttiInfo->m_super)
    {
        SLANG_RETURN_ON_FAIL(_structToNative(pairs, structRttiInfo->m_super, out, fieldCount));
    }

    Byte* dst = (Byte*)out;

    const Index count = structRttiInfo->m_fieldCount;

    for (Index i = 0; i < count; ++i)
    {
        const auto& field = structRttiInfo->m_fields[i];

        auto key = m_container->findKey(UnownedStringSlice(field.m_name));

        if (key == 0)
        {
            if (field.m_flags & StructRttiInfo::Flag::Optional)
            {
                continue;
            }

            m_sink->diagnose(SourceLoc(), JSONDiagnostics::fieldRequiredOnType, field.m_name, structRttiInfo->m_name);

            // Unable to find this key
            return SLANG_FAIL;
        }

        // If there are any of the pairs, that are not in the type.. it's an error
        const Index index = pairs.findFirstIndex([key](const JSONKeyValue& pair) -> bool { return pair.key == key; });
        if (index < 0)
        {
            if (field.m_flags & StructRttiInfo::Flag::Optional)
            {
                continue;
            }

            m_sink->diagnose(SourceLoc(), JSONDiagnostics::fieldRequiredOnType, field.m_name, structRttiInfo->m_name);

            // Unable to find this key
            return SLANG_FAIL;
        }

        auto& pair = pairs[index];

        // Copy the field over
        SLANG_RETURN_ON_FAIL(convert(pair.value, field.m_type, dst + field.m_offset));

        // Field was handled
        ++fieldCount;
    }

    // Write off the amount of fields converted/handled. 
    outFieldCount = fieldCount;
    return SLANG_OK;
}

SlangResult JSONToNativeConverter::convert(const JSONValue& in, const RttiInfo* rttiInfo, void* out)
{
    if (rttiInfo->isIntegral())
    {
        return RttiUtil::setInt(m_container->asInteger(in), rttiInfo, out);
    }
    else if (rttiInfo->isFloat())
    {
        return RttiUtil::setFromDouble(m_container->asFloat(in), rttiInfo, out);
    }

    switch (rttiInfo->m_kind)
    {
        case RttiInfo::Kind::Bool:
        {
            *(bool*)out = m_container->asBool(in);
            return SLANG_OK;
        }
        case RttiInfo::Kind::Struct:
        {
            if (in.getKind() != JSONValue::Kind::Object)
            {
                return SLANG_FAIL;
            }

            auto pairs = m_container->getObject(in);
            const StructRttiInfo* structRttiInfo = static_cast<const StructRttiInfo*>(rttiInfo);

            Index fieldCount = 0;
            SLANG_RETURN_ON_FAIL(_structToNative(pairs, structRttiInfo, out, fieldCount));

            if (fieldCount != pairs.getCount())
            {
                // We want to find the fields not found in the type

                for (auto& pair : pairs)
                {
                    UnownedStringSlice fieldName = m_container->getStringFromKey(pair.key);
                    const Index index = _findFieldIndex(structRttiInfo, UnownedStringSlice(fieldName));

                    if (index < 0)
                    {
                        m_sink->diagnose(pair.keyLoc, JSONDiagnostics::fieldNotDefinedOnType, fieldName, structRttiInfo->m_name);
                    }
                }

                // If these are different then there are fields defined in the object that are *not* defined in class definition
                return SLANG_FAIL;
            }

            return SLANG_OK;
        }
        case RttiInfo::Kind::Enum:
        {
            return SLANG_E_NOT_IMPLEMENTED;
        }
        case RttiInfo::Kind::String:
        {
            *(String*)out = m_container->getTransientString(in);
            return SLANG_OK;
        }
        case RttiInfo::Kind::UnownedStringSlice:
        {
            // Problem -> if the slice is a lexeme, then when we decode with getString, it will lose scope.
            // So we do something a bit odd and place the decoding string

            *(UnownedStringSlice*)out = m_container->getString(in);
            return SLANG_OK;
        }
        case RttiInfo::Kind::List:
        {
            if (in.getKind() != JSONValue::Kind::Array)
            {
                return SLANG_FAIL;
            }

            typedef List<Byte> Type;
            Type& list = *(Type*)out;

            auto arr = m_container->getArray(in);

            const Index count = arr.getCount();

            const ListRttiInfo* listRttiInfo = static_cast<const ListRttiInfo*>(rttiInfo);
            auto elementType = listRttiInfo->m_elementType;

            SLANG_RETURN_ON_FAIL(RttiUtil::setListCount(elementType, out, arr.getCount()));

            // Okay, we need to copy over one by one

            Byte* dstEles = list.getBuffer();
            for (Index i = 0; i < count; ++i, dstEles += elementType->m_size)
            {
                SLANG_RETURN_ON_FAIL(convert(arr[i], elementType, dstEles));
            }

            return SLANG_OK;
        }
        case RttiInfo::Kind::FixedArray:
        {
            if (in.getKind() != JSONValue::Kind::Array)
            {
                return SLANG_FAIL;
            }
            const FixedArrayRttiInfo* fixedArrayRttiInfo = static_cast<const FixedArrayRttiInfo*>(rttiInfo);
            const auto elementType = fixedArrayRttiInfo->m_elementType;
            const Index elementCount = Index(fixedArrayRttiInfo->m_elementCount);
            const auto elementSize = elementType->m_size;

            auto srcArray = m_container->getArray(in);

            if (srcArray.getCount() > elementCount)
            {
                m_sink->diagnose(in.loc, JSONDiagnostics::tooManyElementsForArray, srcArray.getCount(), elementCount);
                return SLANG_FAIL;
            }

            Byte* dstEles = (Byte*)out;
            for (Index i = 0; i < elementCount; ++i, dstEles += elementSize)
            {
                SLANG_RETURN_ON_FAIL(convert(srcArray[i], elementType, dstEles));
            }

            return SLANG_OK;
        }
        case RttiInfo::Kind::Dictionary:
        {
            // We can *only* serialize this into a straight JSON object iff the key is a string-like type
            // We could turn into (say) an array of keys and values
            break;
        }
        case RttiInfo::Kind::Other:
        {
            if (rttiInfo == GetRttiInfo<JSONValue>::get())
            {
                // Do we need to copy into the container?
                // As it stands we have to assume src is stored in container.
                *(JSONValue*)out = in;
                return SLANG_OK;
            }
            return SLANG_FAIL;
        }
        default: break;
    }
    return SLANG_FAIL;
}


/* !!!!!!!!!!!!!!!!!!!!!!!!!!!! NativeToJSONConverter !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */

SlangResult NativeToJSONConverter::_structToJSON(const StructRttiInfo* structRttiInfo, const void* src, List<JSONKeyValue>& outPairs)
{
    // Do the super class first
    if (structRttiInfo->m_super)
    {
        SLANG_RETURN_ON_FAIL(_structToJSON(structRttiInfo, src, outPairs));
    }

    const Byte* base = (const Byte*)src;
    const Index count = structRttiInfo->m_fieldCount;

    for (Index i = 0; i < count; ++i)
    {
        const auto& field = structRttiInfo->m_fields[i];

        if (field.m_flags & StructRttiInfo::Flag::Optional)
        {
            const RttiDefaultValue defaultValue = RttiDefaultValue(field.m_flags & uint8_t(RttiDefaultValue::Mask));
            if (RttiUtil::isDefault(defaultValue, field.m_type, base + field.m_offset))
            {
                // If it's a default, we don't bother writing it
                continue;
            }
        }

        JSONKeyValue pair;
        pair.key = m_container->getKey(UnownedStringSlice(field.m_name));
        auto res = convert(field.m_type, base + field.m_offset, pair.value);

        if (SLANG_FAILED(res))
        {
            m_sink->diagnose(SourceLoc(), JSONDiagnostics::unableToConvertField, field.m_name, structRttiInfo->m_name);
            return res;
        }

        outPairs.add(pair);
    }

    return SLANG_OK;
}


SlangResult NativeToJSONConverter::convert(const RttiInfo* rttiInfo, const void* in, JSONValue& out)
{
    if (rttiInfo->isIntegral())
    {
        out = JSONValue::makeInt(RttiUtil::getInt64(rttiInfo, in));
        return SLANG_OK;
    }
    else if (rttiInfo->isFloat())
    {
        out = JSONValue::makeFloat(RttiUtil::asDouble(rttiInfo, in));
        return SLANG_OK;
    }

    switch (rttiInfo->m_kind)
    {
        case RttiInfo::Kind::Invalid:   return SLANG_FAIL;
        case RttiInfo::Kind::Bool:
        {
            out = JSONValue::makeBool(RttiUtil::asBool(rttiInfo, in));
            return SLANG_OK;
        }
        case RttiInfo::Kind::String:
        {
            const String& str = *(const String*)in;
            out = m_container->createString(str.getUnownedSlice());
            return SLANG_OK;
        }
        case RttiInfo::Kind::UnownedStringSlice:
        {
            const UnownedStringSlice& slice = *(const UnownedStringSlice*)in;
            out = m_container->createString(slice);
            return SLANG_OK;
        }
        case RttiInfo::Kind::Struct:
        {
            const StructRttiInfo* structRttiInfo = static_cast<const StructRttiInfo*>(rttiInfo);

            List<JSONKeyValue> pairs;
            SLANG_RETURN_ON_FAIL(_structToJSON(structRttiInfo, in, pairs));
            out = m_container->createObject(pairs.getBuffer(), pairs.getCount());
            return SLANG_OK;
        }
        case RttiInfo::Kind::Enum:
        {   
            return SLANG_E_NOT_IMPLEMENTED;
        }
        case RttiInfo::Kind::List:
        {
            const ListRttiInfo* listRttiInfo = static_cast<const ListRttiInfo*>(rttiInfo);
            const auto elementRttiInfo = listRttiInfo->m_elementType;

            // The src probably *doesn't* contain bytes, but can cast like this because
            // we only need the count (which doesn't depend on <T>), and the backing buffer
            const List<Byte>& srcValuesList = *(const List<Byte>*)in;

            const Index count = srcValuesList.getCount();
            const Byte* srcValues = srcValuesList.getBuffer();

            List<JSONValue> dstValues;
            dstValues.setCount(count);

            const size_t elementStride = elementRttiInfo->m_size;

            for (Index i = 0; i < count; ++i, srcValues += elementStride)
            {
                SLANG_RETURN_ON_FAIL(convert(elementRttiInfo, srcValues, dstValues[i]));
            }

            out = m_container->createArray(dstValues.getBuffer(), count);
            return SLANG_OK;
        }
        case RttiInfo::Kind::FixedArray:
        {
            const FixedArrayRttiInfo* fixedArrayRttiInfo = static_cast<const FixedArrayRttiInfo*>(rttiInfo);
            const auto elementType = fixedArrayRttiInfo->m_elementType;
            const auto elementCount = Index(fixedArrayRttiInfo->m_elementCount);
            const auto elementSize = elementType->m_size;

            List<JSONValue> dstValues;
            dstValues.setCount(elementCount);

            const Byte* src = (const Byte*)in;
            for (Index i = 0; i < elementCount; ++i, src += elementSize)
            {
                SLANG_RETURN_ON_FAIL(convert(elementType, src, dstValues[i]));
            }

            out = m_container->createArray(dstValues.getBuffer(), elementCount);
            return SLANG_OK;
        }
        case RttiInfo::Kind::Dictionary:
        {
            const DictionaryRttiInfo* listRttiInfo = static_cast<const DictionaryRttiInfo*>(rttiInfo);
            const auto keyRttiInfo = listRttiInfo->m_keyType;
            const auto valueRttiInfo = listRttiInfo->m_valueType;

            SLANG_UNUSED(keyRttiInfo);
            SLANG_UNUSED(valueRttiInfo);

            // We can *only* serialize this into a straight JSON object iff the key is a string-like type
            // We could turn into (say) an array of keys and values

            break;
        }
        case RttiInfo::Kind::Other:
        {
            if (rttiInfo == GetRttiInfo<JSONValue>::get())
            {
                // Do we need to copy into the container?
                // As it stands we have to assume src is stored in container.
                const JSONValue& src = *(const JSONValue*)in;

                out = src;
                return SLANG_OK;
            }
            break;
        }
        default: break;
    }

    return SLANG_E_NOT_IMPLEMENTED;
}

} // namespace Slang