blob: 84a5724fece10c7299e1594add58798fd0ecaa16 [file] [log] [blame]
Florin Malita7796f002018-06-08 12:25:38 -04001/*
2 * Copyright 2018 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkJSON.h"
9
Florin Malitad7bfcaf2018-06-14 18:03:26 -040010#include "SkMalloc.h"
Florin Malita7796f002018-06-08 12:25:38 -040011#include "SkStream.h"
12#include "SkString.h"
Florin Malita7796f002018-06-08 12:25:38 -040013
14#include <cmath>
Florin Malitafedfd542018-06-14 15:03:21 -040015#include <tuple>
Florin Malita7796f002018-06-08 12:25:38 -040016#include <vector>
17
18namespace skjson {
19
Florin Malitafedfd542018-06-14 15:03:21 -040020// #define SK_JSON_REPORT_ERRORS
Florin Malita7796f002018-06-08 12:25:38 -040021
Florin Malita7796f002018-06-08 12:25:38 -040022static_assert( sizeof(Value) == 8, "");
23static_assert(alignof(Value) == 8, "");
24
25static constexpr size_t kRecAlign = alignof(Value);
26
Florin Malitaae252792018-06-14 11:24:50 -040027void Value::init_tagged(Tag t) {
28 memset(fData8, 0, sizeof(fData8));
29 fData8[Value::kTagOffset] = SkTo<uint8_t>(t);
30 SkASSERT(this->getTag() == t);
31}
Florin Malita7796f002018-06-08 12:25:38 -040032
Florin Malitaae252792018-06-14 11:24:50 -040033// Pointer values store a type (in the upper kTagBits bits) and a pointer.
34void Value::init_tagged_pointer(Tag t, void* p) {
35 *this->cast<uintptr_t>() = reinterpret_cast<uintptr_t>(p);
Florin Malita7796f002018-06-08 12:25:38 -040036
Florin Malitaae252792018-06-14 11:24:50 -040037 if (sizeof(Value) == sizeof(uintptr_t)) {
38 // For 64-bit, we rely on the pointer upper bits being unused/zero.
39 SkASSERT(!(fData8[kTagOffset] & kTagMask));
40 fData8[kTagOffset] |= SkTo<uint8_t>(t);
41 } else {
42 // For 32-bit, we need to zero-initialize the upper 32 bits
43 SkASSERT(sizeof(Value) == sizeof(uintptr_t) * 2);
44 this->cast<uintptr_t>()[kTagOffset >> 2] = 0;
45 fData8[kTagOffset] = SkTo<uint8_t>(t);
Florin Malita7796f002018-06-08 12:25:38 -040046 }
47
Florin Malitaae252792018-06-14 11:24:50 -040048 SkASSERT(this->getTag() == t);
49 SkASSERT(this->ptr<void>() == p);
50}
51
52NullValue::NullValue() {
53 this->init_tagged(Tag::kNull);
54 SkASSERT(this->getTag() == Tag::kNull);
55}
56
57BoolValue::BoolValue(bool b) {
58 this->init_tagged(Tag::kBool);
59 *this->cast<bool>() = b;
60 SkASSERT(this->getTag() == Tag::kBool);
61}
62
63NumberValue::NumberValue(int32_t i) {
64 this->init_tagged(Tag::kInt);
65 *this->cast<int32_t>() = i;
66 SkASSERT(this->getTag() == Tag::kInt);
67}
68
69NumberValue::NumberValue(float f) {
70 this->init_tagged(Tag::kFloat);
71 *this->cast<float>() = f;
72 SkASSERT(this->getTag() == Tag::kFloat);
73}
74
75// Vector recs point to externally allocated slabs with the following layout:
76//
77// [size_t n] [REC_0] ... [REC_n-1] [optional extra trailing storage]
78//
79// Long strings use extra_alloc_size == 1 to store the \0 terminator.
80//
81template <typename T, size_t extra_alloc_size = 0>
82static void* MakeVector(const void* src, size_t size, SkArenaAlloc& alloc) {
83 // The Ts are already in memory, so their size should be safe.
84 const auto total_size = sizeof(size_t) + size * sizeof(T) + extra_alloc_size;
85 auto* size_ptr = reinterpret_cast<size_t*>(alloc.makeBytesAlignedTo(total_size, kRecAlign));
Florin Malita28f5dd82018-06-14 13:56:53 -040086
Florin Malitad7bfcaf2018-06-14 18:03:26 -040087 *size_ptr = size;
88 sk_careful_memcpy(size_ptr + 1, src, size * sizeof(T));
Florin Malitaae252792018-06-14 11:24:50 -040089
90 return size_ptr;
91}
92
93ArrayValue::ArrayValue(const Value* src, size_t size, SkArenaAlloc& alloc) {
94 this->init_tagged_pointer(Tag::kArray, MakeVector<Value>(src, size, alloc));
95 SkASSERT(this->getTag() == Tag::kArray);
96}
97
98// Strings have two flavors:
99//
100// -- short strings (len <= 7) -> these are stored inline, in the record
101// (one byte reserved for null terminator/type):
102//
103// [str] [\0]|[max_len - actual_len]
104//
105// Storing [max_len - actual_len] allows the 'len' field to double-up as a
106// null terminator when size == max_len (this works 'cause kShortString == 0).
107//
108// -- long strings (len > 7) -> these are externally allocated vectors (VectorRec<char>).
109//
110// The string data plus a null-char terminator are copied over.
111//
Florin Malitafb3beb02018-06-18 22:25:31 -0400112namespace {
113
114// An internal string builder with a fast 8 byte short string load path
115// (for the common case where the string is not at the end of the stream).
116class FastString final : public Value {
117public:
118 FastString(const char* src, size_t size, const char* eos, SkArenaAlloc& alloc) {
119 SkASSERT(src <= eos);
120
121 if (size > kMaxInlineStringSize) {
122 this->initLongString(src, size, alloc);
123 SkASSERT(this->getTag() == Tag::kString);
124 return;
125 }
126
127 static_assert(static_cast<uint8_t>(Tag::kShortString) == 0, "please don't break this");
128 static_assert(sizeof(Value) == 8, "");
129
130 // TODO: LIKELY
131 if (src + 7 <= eos) {
132 this->initFastShortString(src, size);
133 } else {
134 this->initShortString(src, size);
135 }
136
137 SkASSERT(this->getTag() == Tag::kShortString);
138 }
139
140private:
Florin Malitad7bfcaf2018-06-14 18:03:26 -0400141 static constexpr size_t kMaxInlineStringSize = sizeof(Value) - 1;
Florin Malitafb3beb02018-06-18 22:25:31 -0400142
143 void initLongString(const char* src, size_t size, SkArenaAlloc& alloc) {
144 SkASSERT(size > kMaxInlineStringSize);
145
Florin Malitaae252792018-06-14 11:24:50 -0400146 this->init_tagged_pointer(Tag::kString, MakeVector<char, 1>(src, size, alloc));
147
148 auto* data = this->cast<VectorValue<char, Value::Type::kString>>()->begin();
149 const_cast<char*>(data)[size] = '\0';
Florin Malita7796f002018-06-08 12:25:38 -0400150 }
151
Florin Malitafb3beb02018-06-18 22:25:31 -0400152 void initShortString(const char* src, size_t size) {
153 SkASSERT(size <= kMaxInlineStringSize);
Florin Malita7796f002018-06-08 12:25:38 -0400154
Florin Malitafb3beb02018-06-18 22:25:31 -0400155 this->init_tagged(Tag::kShortString);
156 sk_careful_memcpy(this->cast<char>(), src, size);
157 // Null terminator provided by init_tagged() above (fData8 is zero-initialized).
158 }
Florin Malita7796f002018-06-08 12:25:38 -0400159
Florin Malitafb3beb02018-06-18 22:25:31 -0400160 void initFastShortString(const char* src, size_t size) {
161 SkASSERT(size <= kMaxInlineStringSize);
162
163 // Load 8 chars and mask out the tag and \0 terminator.
164 uint64_t* s64 = this->cast<uint64_t>();
165 memcpy(s64, src, 8);
166
167#if defined(SK_CPU_LENDIAN)
168 *s64 &= 0x00ffffffffffffffULL >> ((kMaxInlineStringSize - size) * 8);
169#else
170 static_assert(false, "Big-endian builds are not supported at this time.");
171#endif
172 }
173};
174
175} // namespace
176
177StringValue::StringValue(const char* src, size_t size, SkArenaAlloc& alloc) {
178 new (this) FastString(src, size, src, alloc);
Florin Malitaae252792018-06-14 11:24:50 -0400179}
Florin Malita7796f002018-06-08 12:25:38 -0400180
Florin Malitaae252792018-06-14 11:24:50 -0400181ObjectValue::ObjectValue(const Member* src, size_t size, SkArenaAlloc& alloc) {
182 this->init_tagged_pointer(Tag::kObject, MakeVector<Member>(src, size, alloc));
183 SkASSERT(this->getTag() == Tag::kObject);
184}
Florin Malita7796f002018-06-08 12:25:38 -0400185
186
187// Boring public Value glue.
188
Florin Malita7796f002018-06-08 12:25:38 -0400189const Value& ObjectValue::operator[](const char* key) const {
190 // Reverse search for duplicates resolution (policy: return last).
191 const auto* begin = this->begin();
192 const auto* member = this->end();
193
194 while (member > begin) {
195 --member;
196 if (0 == strcmp(key, member->fKey.as<StringValue>().begin())) {
197 return member->fValue;
198 }
199 }
200
Florin Malitaae252792018-06-14 11:24:50 -0400201 static const Value g_null = NullValue();
202 return g_null;
Florin Malita7796f002018-06-08 12:25:38 -0400203}
204
205namespace {
206
207// Lexer/parser inspired by rapidjson [1], sajson [2] and pjson [3].
208//
209// [1] https://github.com/Tencent/rapidjson/
210// [2] https://github.com/chadaustin/sajson
211// [3] https://pastebin.com/hnhSTL3h
212
213
214// bit 0 (0x01) - plain ASCII string character
215// bit 1 (0x02) - whitespace
Florin Malita0052a312018-06-15 16:42:09 -0400216// bit 2 (0x04) - string terminator (" \0 [control chars] **AND } ]** <- see matchString notes)
Florin Malita7796f002018-06-08 12:25:38 -0400217// bit 3 (0x08) - 0-9
218// bit 4 (0x10) - 0-9 e E .
Florin Malita0052a312018-06-15 16:42:09 -0400219// bit 5 (0x20) - scope terminator (} ])
Florin Malita7796f002018-06-08 12:25:38 -0400220static constexpr uint8_t g_token_flags[256] = {
221 // 0 1 2 3 4 5 6 7 8 9 A B C D E F
222 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 6, 4, 4, // 0
223 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // 1
224 3, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0x11,1, // 2
225 0x19,0x19,0x19,0x19,0x19,0x19,0x19,0x19, 0x19,0x19, 1, 1, 1, 1, 1, 1, // 3
226 1, 1, 1, 1, 1, 0x11,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4
Florin Malita0052a312018-06-15 16:42:09 -0400227 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,0x25, 1, 1, // 5
Florin Malita7796f002018-06-08 12:25:38 -0400228 1, 1, 1, 1, 1, 0x11,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6
Florin Malita0052a312018-06-15 16:42:09 -0400229 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,0x25, 1, 1, // 7
Florin Malita7796f002018-06-08 12:25:38 -0400230
231 // 128-255
232 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
233 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
234 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
235 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0
236};
237
Florin Malita0052a312018-06-15 16:42:09 -0400238static inline bool is_ws(char c) { return g_token_flags[static_cast<uint8_t>(c)] & 0x02; }
239static inline bool is_eostring(char c) { return g_token_flags[static_cast<uint8_t>(c)] & 0x04; }
240static inline bool is_digit(char c) { return g_token_flags[static_cast<uint8_t>(c)] & 0x08; }
241static inline bool is_numeric(char c) { return g_token_flags[static_cast<uint8_t>(c)] & 0x10; }
242static inline bool is_eoscope(char c) { return g_token_flags[static_cast<uint8_t>(c)] & 0x20; }
Florin Malita7796f002018-06-08 12:25:38 -0400243
244static inline const char* skip_ws(const char* p) {
245 while (is_ws(*p)) ++p;
246 return p;
247}
248
249static inline float pow10(int32_t exp) {
250 static constexpr float g_pow10_table[63] =
251 {
252 1.e-031f, 1.e-030f, 1.e-029f, 1.e-028f, 1.e-027f, 1.e-026f, 1.e-025f, 1.e-024f,
253 1.e-023f, 1.e-022f, 1.e-021f, 1.e-020f, 1.e-019f, 1.e-018f, 1.e-017f, 1.e-016f,
254 1.e-015f, 1.e-014f, 1.e-013f, 1.e-012f, 1.e-011f, 1.e-010f, 1.e-009f, 1.e-008f,
255 1.e-007f, 1.e-006f, 1.e-005f, 1.e-004f, 1.e-003f, 1.e-002f, 1.e-001f, 1.e+000f,
256 1.e+001f, 1.e+002f, 1.e+003f, 1.e+004f, 1.e+005f, 1.e+006f, 1.e+007f, 1.e+008f,
257 1.e+009f, 1.e+010f, 1.e+011f, 1.e+012f, 1.e+013f, 1.e+014f, 1.e+015f, 1.e+016f,
258 1.e+017f, 1.e+018f, 1.e+019f, 1.e+020f, 1.e+021f, 1.e+022f, 1.e+023f, 1.e+024f,
259 1.e+025f, 1.e+026f, 1.e+027f, 1.e+028f, 1.e+029f, 1.e+030f, 1.e+031f
260 };
261
262 static constexpr int32_t k_exp_offset = SK_ARRAY_COUNT(g_pow10_table) / 2;
263
264 // We only support negative exponents for now.
265 SkASSERT(exp <= 0);
266
267 return (exp >= -k_exp_offset) ? g_pow10_table[exp + k_exp_offset]
268 : std::pow(10.0f, static_cast<float>(exp));
269}
270
271class DOMParser {
272public:
273 explicit DOMParser(SkArenaAlloc& alloc)
274 : fAlloc(alloc) {
Florin Malita7796f002018-06-08 12:25:38 -0400275 fValueStack.reserve(kValueStackReserve);
Florin Malita7796f002018-06-08 12:25:38 -0400276 }
277
Florin Malitafedfd542018-06-14 15:03:21 -0400278 const Value parse(const char* p, size_t size) {
279 if (!size) {
280 return this->error(NullValue(), p, "invalid empty input");
281 }
282
283 const char* p_stop = p + size - 1;
284
285 // We're only checking for end-of-stream on object/array close('}',']'),
286 // so we must trim any whitespace from the buffer tail.
287 while (p_stop > p && is_ws(*p_stop)) --p_stop;
288
289 SkASSERT(p_stop >= p && p_stop < p + size);
Florin Malita0052a312018-06-15 16:42:09 -0400290 if (!is_eoscope(*p_stop)) {
Florin Malitafedfd542018-06-14 15:03:21 -0400291 return this->error(NullValue(), p_stop, "invalid top-level value");
292 }
293
Florin Malita7796f002018-06-08 12:25:38 -0400294 p = skip_ws(p);
295
296 switch (*p) {
297 case '{':
298 goto match_object;
299 case '[':
300 goto match_array;
301 default:
Florin Malitaae252792018-06-14 11:24:50 -0400302 return this->error(NullValue(), p, "invalid top-level value");
Florin Malita7796f002018-06-08 12:25:38 -0400303 }
304
305 match_object:
306 SkASSERT(*p == '{');
307 p = skip_ws(p + 1);
308
309 this->pushObjectScope();
310
311 if (*p == '}') goto pop_object;
312
313 // goto match_object_key;
314 match_object_key:
315 p = skip_ws(p);
Florin Malitaae252792018-06-14 11:24:50 -0400316 if (*p != '"') return this->error(NullValue(), p, "expected object key");
Florin Malita7796f002018-06-08 12:25:38 -0400317
Florin Malitafb3beb02018-06-18 22:25:31 -0400318 p = this->matchString(p, p_stop, [this](const char* key, size_t size, const char* eos) {
319 this->pushObjectKey(key, size, eos);
Florin Malita7796f002018-06-08 12:25:38 -0400320 });
Florin Malitaae252792018-06-14 11:24:50 -0400321 if (!p) return NullValue();
Florin Malita7796f002018-06-08 12:25:38 -0400322
323 p = skip_ws(p);
Florin Malitaae252792018-06-14 11:24:50 -0400324 if (*p != ':') return this->error(NullValue(), p, "expected ':' separator");
Florin Malita7796f002018-06-08 12:25:38 -0400325
326 ++p;
327
328 // goto match_value;
329 match_value:
330 p = skip_ws(p);
331
332 switch (*p) {
333 case '\0':
Florin Malitaae252792018-06-14 11:24:50 -0400334 return this->error(NullValue(), p, "unexpected input end");
Florin Malita7796f002018-06-08 12:25:38 -0400335 case '"':
Florin Malitafb3beb02018-06-18 22:25:31 -0400336 p = this->matchString(p, p_stop, [this](const char* str, size_t size, const char* eos) {
337 this->pushString(str, size, eos);
Florin Malita7796f002018-06-08 12:25:38 -0400338 });
339 break;
340 case '[':
341 goto match_array;
342 case 'f':
343 p = this->matchFalse(p);
344 break;
345 case 'n':
346 p = this->matchNull(p);
347 break;
348 case 't':
349 p = this->matchTrue(p);
350 break;
351 case '{':
352 goto match_object;
353 default:
354 p = this->matchNumber(p);
355 break;
356 }
357
Florin Malitaae252792018-06-14 11:24:50 -0400358 if (!p) return NullValue();
Florin Malita7796f002018-06-08 12:25:38 -0400359
360 // goto match_post_value;
361 match_post_value:
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400362 SkASSERT(!this->inTopLevelScope());
Florin Malita7796f002018-06-08 12:25:38 -0400363
364 p = skip_ws(p);
365 switch (*p) {
366 case ',':
367 ++p;
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400368 if (this->inObjectScope()) {
Florin Malita7796f002018-06-08 12:25:38 -0400369 goto match_object_key;
370 } else {
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400371 SkASSERT(this->inArrayScope());
Florin Malita7796f002018-06-08 12:25:38 -0400372 goto match_value;
373 }
374 case ']':
375 goto pop_array;
376 case '}':
377 goto pop_object;
378 default:
Florin Malitaae252792018-06-14 11:24:50 -0400379 return this->error(NullValue(), p - 1, "unexpected value-trailing token");
Florin Malita7796f002018-06-08 12:25:38 -0400380 }
381
382 // unreachable
383 SkASSERT(false);
384
385 pop_object:
386 SkASSERT(*p == '}');
387
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400388 if (this->inArrayScope()) {
Florin Malitaae252792018-06-14 11:24:50 -0400389 return this->error(NullValue(), p, "unexpected object terminator");
Florin Malita7796f002018-06-08 12:25:38 -0400390 }
391
392 this->popObjectScope();
393
394 // goto pop_common
395 pop_common:
Florin Malita0052a312018-06-15 16:42:09 -0400396 SkASSERT(is_eoscope(*p));
Florin Malita7796f002018-06-08 12:25:38 -0400397
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400398 if (this->inTopLevelScope()) {
Florin Malita7796f002018-06-08 12:25:38 -0400399 SkASSERT(fValueStack.size() == 1);
Florin Malita7796f002018-06-08 12:25:38 -0400400
Florin Malitafedfd542018-06-14 15:03:21 -0400401 // Success condition: parsed the top level element and reached the stop token.
402 return p == p_stop
Florin Malitaae252792018-06-14 11:24:50 -0400403 ? fValueStack.front()
Florin Malitafedfd542018-06-14 15:03:21 -0400404 : this->error(NullValue(), p + 1, "trailing root garbage");
Florin Malita7796f002018-06-08 12:25:38 -0400405 }
406
Florin Malita587f5a92018-06-15 09:21:36 -0400407 if (p == p_stop) {
408 return this->error(NullValue(), p, "unexpected end-of-input");
409 }
410
Florin Malitafedfd542018-06-14 15:03:21 -0400411 ++p;
412
Florin Malita7796f002018-06-08 12:25:38 -0400413 goto match_post_value;
414
415 match_array:
416 SkASSERT(*p == '[');
417 p = skip_ws(p + 1);
418
419 this->pushArrayScope();
420
421 if (*p != ']') goto match_value;
422
423 // goto pop_array;
424 pop_array:
425 SkASSERT(*p == ']');
426
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400427 if (this->inObjectScope()) {
Florin Malitaae252792018-06-14 11:24:50 -0400428 return this->error(NullValue(), p, "unexpected array terminator");
Florin Malita7796f002018-06-08 12:25:38 -0400429 }
430
431 this->popArrayScope();
432
433 goto pop_common;
434
435 SkASSERT(false);
Florin Malitaae252792018-06-14 11:24:50 -0400436 return NullValue();
Florin Malita7796f002018-06-08 12:25:38 -0400437 }
438
Florin Malitafedfd542018-06-14 15:03:21 -0400439 std::tuple<const char*, const SkString> getError() const {
440 return std::make_tuple(fErrorToken, fErrorMessage);
Florin Malita7796f002018-06-08 12:25:38 -0400441 }
442
443private:
Florin Malitafedfd542018-06-14 15:03:21 -0400444 SkArenaAlloc& fAlloc;
Florin Malita7796f002018-06-08 12:25:38 -0400445
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400446 // Pending values stack.
Florin Malita7796f002018-06-08 12:25:38 -0400447 static constexpr size_t kValueStackReserve = 256;
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400448 std::vector<Value> fValueStack;
Florin Malita7796f002018-06-08 12:25:38 -0400449
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400450 // Tracks the current object/array scope, as an index into fStack:
451 //
452 // - for objects: fScopeIndex = (index of first value in scope)
453 // - for arrays : fScopeIndex = -(index of first value in scope)
454 //
455 // fScopeIndex == 0 IFF we are at the top level (no current/active scope).
456 intptr_t fScopeIndex = 0;
457
458 // Error reporting.
Florin Malitafedfd542018-06-14 15:03:21 -0400459 const char* fErrorToken = nullptr;
460 SkString fErrorMessage;
Florin Malita7796f002018-06-08 12:25:38 -0400461
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400462 bool inTopLevelScope() const { return fScopeIndex == 0; }
463 bool inObjectScope() const { return fScopeIndex > 0; }
464 bool inArrayScope() const { return fScopeIndex < 0; }
465
466 // Helper for masquerading raw primitive types as Values (bypassing tagging, etc).
467 template <typename T>
468 class RawValue final : public Value {
469 public:
470 explicit RawValue(T v) {
471 static_assert(sizeof(T) <= sizeof(Value), "");
472 *this->cast<T>() = v;
473 }
474
475 T operator *() const { return *this->cast<T>(); }
476 };
477
Florin Malitaae252792018-06-14 11:24:50 -0400478 template <typename VectorT>
479 void popScopeAsVec(size_t scope_start) {
Florin Malita7796f002018-06-08 12:25:38 -0400480 SkASSERT(scope_start > 0);
481 SkASSERT(scope_start <= fValueStack.size());
482
Florin Malitaae252792018-06-14 11:24:50 -0400483 using T = typename VectorT::ValueT;
Florin Malita7796f002018-06-08 12:25:38 -0400484 static_assert( sizeof(T) >= sizeof(Value), "");
485 static_assert( sizeof(T) % sizeof(Value) == 0, "");
486 static_assert(alignof(T) == alignof(Value), "");
487
488 const auto scope_count = fValueStack.size() - scope_start,
489 count = scope_count / (sizeof(T) / sizeof(Value));
490 SkASSERT(scope_count % (sizeof(T) / sizeof(Value)) == 0);
491
492 const auto* begin = reinterpret_cast<const T*>(fValueStack.data() + scope_start);
493
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400494 // Restore the previous scope index from saved placeholder value,
495 // and instantiate as a vector of values in scope.
496 auto& placeholder = fValueStack[scope_start - 1];
497 fScopeIndex = *static_cast<RawValue<intptr_t>&>(placeholder);
498 placeholder = VectorT(begin, count, fAlloc);
Florin Malita7796f002018-06-08 12:25:38 -0400499
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400500 // Drop the (consumed) values in scope.
Florin Malita7796f002018-06-08 12:25:38 -0400501 fValueStack.resize(scope_start);
502 }
503
504 void pushObjectScope() {
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400505 // Save a scope index now, and then later we'll overwrite this value as the Object itself.
506 fValueStack.push_back(RawValue<intptr_t>(fScopeIndex));
Florin Malita7796f002018-06-08 12:25:38 -0400507
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400508 // New object scope.
509 fScopeIndex = SkTo<intptr_t>(fValueStack.size());
Florin Malita7796f002018-06-08 12:25:38 -0400510 }
511
512 void popObjectScope() {
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400513 SkASSERT(this->inObjectScope());
514 this->popScopeAsVec<ObjectValue>(SkTo<size_t>(fScopeIndex));
Florin Malita7796f002018-06-08 12:25:38 -0400515
516 SkDEBUGCODE(
517 const auto& obj = fValueStack.back().as<ObjectValue>();
518 SkASSERT(obj.is<ObjectValue>());
519 for (const auto& member : obj) {
520 SkASSERT(member.fKey.is<StringValue>());
521 }
522 )
523 }
524
525 void pushArrayScope() {
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400526 // Save a scope index now, and then later we'll overwrite this value as the Array itself.
527 fValueStack.push_back(RawValue<intptr_t>(fScopeIndex));
Florin Malita7796f002018-06-08 12:25:38 -0400528
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400529 // New array scope.
530 fScopeIndex = -SkTo<intptr_t>(fValueStack.size());
Florin Malita7796f002018-06-08 12:25:38 -0400531 }
532
533 void popArrayScope() {
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400534 SkASSERT(this->inArrayScope());
535 this->popScopeAsVec<ArrayValue>(SkTo<size_t>(-fScopeIndex));
Florin Malita7796f002018-06-08 12:25:38 -0400536
537 SkDEBUGCODE(
538 const auto& arr = fValueStack.back().as<ArrayValue>();
539 SkASSERT(arr.is<ArrayValue>());
540 )
541 }
542
Florin Malitafb3beb02018-06-18 22:25:31 -0400543 void pushObjectKey(const char* key, size_t size, const char* eos) {
Florin Malita2e5c1ae2018-06-20 14:23:23 -0400544 SkASSERT(this->inObjectScope());
545 SkASSERT(fValueStack.size() >= SkTo<size_t>(fScopeIndex));
546 SkASSERT(!((fValueStack.size() - SkTo<size_t>(fScopeIndex)) & 1));
Florin Malitafb3beb02018-06-18 22:25:31 -0400547 this->pushString(key, size, eos);
Florin Malita7796f002018-06-08 12:25:38 -0400548 }
549
550 void pushTrue() {
Florin Malitaae252792018-06-14 11:24:50 -0400551 fValueStack.push_back(BoolValue(true));
Florin Malita7796f002018-06-08 12:25:38 -0400552 }
553
554 void pushFalse() {
Florin Malitaae252792018-06-14 11:24:50 -0400555 fValueStack.push_back(BoolValue(false));
Florin Malita7796f002018-06-08 12:25:38 -0400556 }
557
558 void pushNull() {
Florin Malitaae252792018-06-14 11:24:50 -0400559 fValueStack.push_back(NullValue());
Florin Malita7796f002018-06-08 12:25:38 -0400560 }
561
Florin Malitafb3beb02018-06-18 22:25:31 -0400562 void pushString(const char* s, size_t size, const char* eos) {
563 fValueStack.push_back(FastString(s, size, eos, fAlloc));
Florin Malita7796f002018-06-08 12:25:38 -0400564 }
565
566 void pushInt32(int32_t i) {
Florin Malitaae252792018-06-14 11:24:50 -0400567 fValueStack.push_back(NumberValue(i));
Florin Malita7796f002018-06-08 12:25:38 -0400568 }
569
570 void pushFloat(float f) {
Florin Malitaae252792018-06-14 11:24:50 -0400571 fValueStack.push_back(NumberValue(f));
Florin Malita7796f002018-06-08 12:25:38 -0400572 }
573
574 template <typename T>
Florin Malitaae252792018-06-14 11:24:50 -0400575 T error(T&& ret_val, const char* p, const char* msg) {
Florin Malita7796f002018-06-08 12:25:38 -0400576#if defined(SK_JSON_REPORT_ERRORS)
Florin Malitafedfd542018-06-14 15:03:21 -0400577 fErrorToken = p;
578 fErrorMessage.set(msg);
Florin Malita7796f002018-06-08 12:25:38 -0400579#endif
580 return ret_val;
581 }
582
583 const char* matchTrue(const char* p) {
584 SkASSERT(p[0] == 't');
585
586 if (p[1] == 'r' && p[2] == 'u' && p[3] == 'e') {
587 this->pushTrue();
588 return p + 4;
589 }
590
591 return this->error(nullptr, p, "invalid token");
592 }
593
594 const char* matchFalse(const char* p) {
595 SkASSERT(p[0] == 'f');
596
597 if (p[1] == 'a' && p[2] == 'l' && p[3] == 's' && p[4] == 'e') {
598 this->pushFalse();
599 return p + 5;
600 }
601
602 return this->error(nullptr, p, "invalid token");
603 }
604
605 const char* matchNull(const char* p) {
606 SkASSERT(p[0] == 'n');
607
608 if (p[1] == 'u' && p[2] == 'l' && p[3] == 'l') {
609 this->pushNull();
610 return p + 4;
611 }
612
613 return this->error(nullptr, p, "invalid token");
614 }
615
616 template <typename MatchFunc>
Florin Malita0052a312018-06-15 16:42:09 -0400617 const char* matchString(const char* p, const char* p_stop, MatchFunc&& func) {
Florin Malita7796f002018-06-08 12:25:38 -0400618 SkASSERT(*p == '"');
619 const auto* s_begin = p + 1;
620
621 // TODO: unescape
Florin Malita7796f002018-06-08 12:25:38 -0400622
Florin Malita0052a312018-06-15 16:42:09 -0400623 do {
624 // Consume string chars.
625 for (p = p + 1; !is_eostring(*p); ++p);
Florin Malita7796f002018-06-08 12:25:38 -0400626
Florin Malita0052a312018-06-15 16:42:09 -0400627 if (*p == '"') {
628 // Valid string found.
Florin Malitafb3beb02018-06-18 22:25:31 -0400629 func(s_begin, p - s_begin, p_stop);
Florin Malita0052a312018-06-15 16:42:09 -0400630 return p + 1;
631 }
632
633 // End-of-scope chars are special: we use them to tag the end of the input.
634 // Thus they cannot be consumed indiscriminately -- we need to check if we hit the
635 // end of the input. To that effect, we treat them as string terminators above,
636 // then we catch them here.
637 } while (is_eoscope(*p) && (p != p_stop)); // Safe scope terminator char, keep going.
638
639 // Premature end-of-input, or illegal string char.
Florin Malita7796f002018-06-08 12:25:38 -0400640 return this->error(nullptr, s_begin - 1, "invalid string");
641 }
642
643 const char* matchFastFloatDecimalPart(const char* p, int sign, float f, int exp) {
644 SkASSERT(exp <= 0);
645
646 for (;;) {
647 if (!is_digit(*p)) break;
648 f = f * 10.f + (*p++ - '0'); --exp;
649 if (!is_digit(*p)) break;
650 f = f * 10.f + (*p++ - '0'); --exp;
651 }
652
653 if (is_numeric(*p)) {
654 SkASSERT(*p == '.' || *p == 'e' || *p == 'E');
655 // We either have malformed input, or an (unsupported) exponent.
656 return nullptr;
657 }
658
659 this->pushFloat(sign * f * pow10(exp));
660
661 return p;
662 }
663
664 const char* matchFastFloatPart(const char* p, int sign, float f) {
665 for (;;) {
666 if (!is_digit(*p)) break;
667 f = f * 10.f + (*p++ - '0');
668 if (!is_digit(*p)) break;
669 f = f * 10.f + (*p++ - '0');
670 }
671
672 if (!is_numeric(*p)) {
673 // Matched (integral) float.
674 this->pushFloat(sign * f);
675 return p;
676 }
677
678 return (*p == '.') ? this->matchFastFloatDecimalPart(p + 1, sign, f, 0)
679 : nullptr;
680 }
681
682 const char* matchFast32OrFloat(const char* p) {
683 int sign = 1;
684 if (*p == '-') {
685 sign = -1;
686 ++p;
687 }
688
689 const auto* digits_start = p;
690
691 int32_t n32 = 0;
692
693 // This is the largest absolute int32 value we can handle before
694 // risking overflow *on the next digit* (214748363).
695 static constexpr int32_t kMaxInt32 = (std::numeric_limits<int32_t>::max() - 9) / 10;
696
697 if (is_digit(*p)) {
698 n32 = (*p++ - '0');
699 for (;;) {
700 if (!is_digit(*p) || n32 > kMaxInt32) break;
701 n32 = n32 * 10 + (*p++ - '0');
702 }
703 }
704
705 if (!is_numeric(*p)) {
706 // Did we actually match any digits?
707 if (p > digits_start) {
708 this->pushInt32(sign * n32);
709 return p;
710 }
711 return nullptr;
712 }
713
714 if (*p == '.') {
715 const auto* decimals_start = ++p;
716
717 int exp = 0;
718
719 for (;;) {
720 if (!is_digit(*p) || n32 > kMaxInt32) break;
721 n32 = n32 * 10 + (*p++ - '0'); --exp;
722 if (!is_digit(*p) || n32 > kMaxInt32) break;
723 n32 = n32 * 10 + (*p++ - '0'); --exp;
724 }
725
726 if (!is_numeric(*p)) {
727 // Did we actually match any digits?
728 if (p > decimals_start) {
729 this->pushFloat(sign * n32 * pow10(exp));
730 return p;
731 }
732 return nullptr;
733 }
734
735 if (n32 > kMaxInt32) {
736 // we ran out on n32 bits
737 return this->matchFastFloatDecimalPart(p, sign, n32, exp);
738 }
739 }
740
741 return this->matchFastFloatPart(p, sign, n32);
742 }
743
744 const char* matchNumber(const char* p) {
745 if (const auto* fast = this->matchFast32OrFloat(p)) return fast;
746
747 // slow fallback
748 char* matched;
749 float f = strtof(p, &matched);
750 if (matched > p) {
751 this->pushFloat(f);
752 return matched;
753 }
754 return this->error(nullptr, p, "invalid numeric token");
755 }
756};
757
758void Write(const Value& v, SkWStream* stream) {
759 switch (v.getType()) {
760 case Value::Type::kNull:
761 stream->writeText("null");
762 break;
763 case Value::Type::kBool:
764 stream->writeText(*v.as<BoolValue>() ? "true" : "false");
765 break;
766 case Value::Type::kNumber:
767 stream->writeScalarAsText(*v.as<NumberValue>());
768 break;
769 case Value::Type::kString:
770 stream->writeText("\"");
771 stream->writeText(v.as<StringValue>().begin());
772 stream->writeText("\"");
773 break;
774 case Value::Type::kArray: {
775 const auto& array = v.as<ArrayValue>();
776 stream->writeText("[");
777 bool first_value = true;
778 for (const auto& v : array) {
779 if (!first_value) stream->writeText(",");
780 Write(v, stream);
781 first_value = false;
782 }
783 stream->writeText("]");
784 break;
785 }
786 case Value::Type::kObject:
787 const auto& object = v.as<ObjectValue>();
788 stream->writeText("{");
789 bool first_member = true;
790 for (const auto& member : object) {
791 SkASSERT(member.fKey.getType() == Value::Type::kString);
792 if (!first_member) stream->writeText(",");
793 Write(member.fKey, stream);
794 stream->writeText(":");
795 Write(member.fValue, stream);
796 first_member = false;
797 }
798 stream->writeText("}");
799 break;
800 }
801}
802
803} // namespace
804
Florin Malitaae252792018-06-14 11:24:50 -0400805SkString Value::toString() const {
806 SkDynamicMemoryWStream wstream;
807 Write(*this, &wstream);
808 const auto data = wstream.detachAsData();
809 // TODO: is there a better way to pass data around without copying?
810 return SkString(static_cast<const char*>(data->data()), data->size());
811}
812
Florin Malita7796f002018-06-08 12:25:38 -0400813static constexpr size_t kMinChunkSize = 4096;
814
Florin Malitafedfd542018-06-14 15:03:21 -0400815DOM::DOM(const char* data, size_t size)
Florin Malita7796f002018-06-08 12:25:38 -0400816 : fAlloc(kMinChunkSize) {
817 DOMParser parser(fAlloc);
818
Florin Malitafedfd542018-06-14 15:03:21 -0400819 fRoot = parser.parse(data, size);
Florin Malita7796f002018-06-08 12:25:38 -0400820}
821
822void DOM::write(SkWStream* stream) const {
Florin Malitaae252792018-06-14 11:24:50 -0400823 Write(fRoot, stream);
Florin Malita7796f002018-06-08 12:25:38 -0400824}
825
826} // namespace skjson