Debian Codegraph @

src/capnp/compat/json.c++

raw
1 // Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors
2 // Licensed under the MIT License:
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 #include "json.h"
23 #include <capnp/orphan.h>
24 #include <kj/debug.h>
25 #include <kj/function.h>
26 #include <kj/vector.h>
27 #include <kj/one-of.h>
28 #include <kj/encoding.h>
29 #include <kj/map.h>
30
31 namespace capnp {
32
33 struct JsonCodec::Impl {
34 bool prettyPrint = false;
35 HasMode hasMode = HasMode::NON_NULL;
36 size_t maxNestingDepth = 64;
37 bool rejectUnknownFields = false;
38
39 kj::HashMap<Type, HandlerBase*> typeHandlers;
40 kj::HashMap<StructSchema::Field, HandlerBase*> fieldHandlers;
41 kj::HashMap<Type, kj::Maybe<kj::Own<AnnotatedHandler>>> annotatedHandlers;
42 kj::HashMap<Type, kj::Own<AnnotatedEnumHandler>> annotatedEnumHandlers;
43
44 kj::StringTree encodeRaw(JsonValue::Reader value, uint indent, bool& multiline,
45 bool hasPrefix) const {
46 switch (value.which()) {
47 case JsonValue::NULL_:
48 return kj::strTree("null");
49 case JsonValue::BOOLEAN:
50 return kj::strTree(value.getBoolean());
51 case JsonValue::NUMBER:
52 return kj::strTree(value.getNumber());
53
54 case JsonValue::STRING:
55 return kj::strTree(encodeString(value.getString()));
56
57 case JsonValue::ARRAY: {
58 auto array = value.getArray();
59 uint subIndent = indent + (array.size() > 1);
60 bool childMultiline = false;
61 auto encodedElements = KJ_MAP(element, array) {
62 return encodeRaw(element, subIndent, childMultiline, false);
63 };
64
65 return kj::strTree('[', encodeList(
66 kj::mv(encodedElements), childMultiline, indent, multiline, hasPrefix), ']');
67 }
68
69 case JsonValue::OBJECT: {
70 auto object = value.getObject();
71 uint subIndent = indent + (object.size() > 1);
72 bool childMultiline = false;
73 kj::StringPtr colon = prettyPrint ? ": " : ":";
74 auto encodedElements = KJ_MAP(field, object) {
75 return kj::strTree(
76 encodeString(field.getName()), colon,
77 encodeRaw(field.getValue(), subIndent, childMultiline, true));
78 };
79
80 return kj::strTree('{', encodeList(
81 kj::mv(encodedElements), childMultiline, indent, multiline, hasPrefix), '}');
82 }
83
84 case JsonValue::CALL: {
85 auto call = value.getCall();
86 auto params = call.getParams();
87 uint subIndent = indent + (params.size() > 1);
88 bool childMultiline = false;
89 auto encodedElements = KJ_MAP(element, params) {
90 return encodeRaw(element, subIndent, childMultiline, false);
91 };
92
93 return kj::strTree(call.getFunction(), '(', encodeList(
94 kj::mv(encodedElements), childMultiline, indent, multiline, true), ')');
95 }
96
97 case JsonValue::RAW: {
98 return kj::strTree(value.getRaw());
99 }
100 }
101
102 KJ_FAIL_ASSERT("unknown JsonValue type", static_cast<uint>(value.which()));
103 }
104
105 kj::String encodeString(kj::StringPtr chars) const {
106 static const char HEXDIGITS[] = "0123456789abcdef";
107 kj::Vector<char> escaped(chars.size() + 3);
108
109 escaped.add('"');
110 for (char c: chars) {
111 switch (c) {
112 case '\"': escaped.addAll(kj::StringPtr("\\\"")); break;
113 case '\\': escaped.addAll(kj::StringPtr("\\\\")); break;
114 case '\b': escaped.addAll(kj::StringPtr("\\b")); break;
115 case '\f': escaped.addAll(kj::StringPtr("\\f")); break;
116 case '\n': escaped.addAll(kj::StringPtr("\\n")); break;
117 case '\r': escaped.addAll(kj::StringPtr("\\r")); break;
118 case '\t': escaped.addAll(kj::StringPtr("\\t")); break;
119 default:
120 if (static_cast<uint8_t>(c) < 0x20) {
121 escaped.addAll(kj::StringPtr("\\u00"));
122 uint8_t c2 = c;
123 escaped.add(HEXDIGITS[c2 / 16]);
124 escaped.add(HEXDIGITS[c2 % 16]);
125 } else {
126 escaped.add(c);
127 }
128 break;
129 }
130 }
131 escaped.add('"');
132 escaped.add('\0');
133
134 return kj::String(escaped.releaseAsArray());
135 }
136
137 kj::StringTree encodeList(kj::Array<kj::StringTree> elements,
138 bool hasMultilineElement, uint indent, bool& multiline,
139 bool hasPrefix) const {
140 size_t maxChildSize = 0;
141 for (auto& e: elements) maxChildSize = kj::max(maxChildSize, e.size());
142
143 kj::StringPtr prefix;
144 kj::StringPtr delim;
145 kj::StringPtr suffix;
146 kj::String ownPrefix;
147 kj::String ownDelim;
148 if (!prettyPrint) {
149 // No whitespace.
150 delim = ",";
151 prefix = "";
152 suffix = "";
153 } else if ((elements.size() > 1) && (hasMultilineElement || maxChildSize > 50)) {
154 // If the array contained any multi-line elements, OR it contained sufficiently long
155 // elements, then put each element on its own line.
156 auto indentSpace = kj::repeat(' ', (indent + 1) * 2);
157 delim = ownDelim = kj::str(",\n", indentSpace);
158 multiline = true;
159 if (hasPrefix) {
160 // We're producing a multi-line list, and the first line has some garbage in front of it.
161 // Therefore, move the first element to the next line.
162 prefix = ownPrefix = kj::str("\n", indentSpace);
163 } else {
164 prefix = " ";
165 }
166 suffix = " ";
167 } else {
168 // Put everything on one line, but add spacing between elements for legibility.
169 delim = ", ";
170 prefix = "";
171 suffix = "";
172 }
173
174 return kj::strTree(prefix, kj::StringTree(kj::mv(elements), delim), suffix);
175 }
176 };
177
178 JsonCodec::JsonCodec()
179 : impl(kj::heap<Impl>()) {}
180 JsonCodec::~JsonCodec() noexcept(false) {}
181
182 void JsonCodec::setPrettyPrint(bool enabled) { impl->prettyPrint = enabled; }
183
184 void JsonCodec::setMaxNestingDepth(size_t maxNestingDepth) {
185 impl->maxNestingDepth = maxNestingDepth;
186 }
187
188 void JsonCodec::setHasMode(HasMode mode) { impl->hasMode = mode; }
189
190 void JsonCodec::setRejectUnknownFields(bool enabled) { impl->rejectUnknownFields = enabled; }
191
192 kj::String JsonCodec::encode(DynamicValue::Reader value, Type type) const {
193 MallocMessageBuilder message;
194 auto json = message.getRoot<JsonValue>();
195 encode(value, type, json);
196 return encodeRaw(json);
197 }
198
199 void JsonCodec::decode(kj::ArrayPtr<const char> input, DynamicStruct::Builder output) const {
200 MallocMessageBuilder message;
201 auto json = message.getRoot<JsonValue>();
202 decodeRaw(input, json);
203 decode(json, output);
204 }
205
206 Orphan<DynamicValue> JsonCodec::decode(
207 kj::ArrayPtr<const char> input, Type type, Orphanage orphanage) const {
208 MallocMessageBuilder message;
209 auto json = message.getRoot<JsonValue>();
210 decodeRaw(input, json);
211 return decode(json, type, orphanage);
212 }
213
214 kj::String JsonCodec::encodeRaw(JsonValue::Reader value) const {
215 bool multiline = false;
216 return impl->encodeRaw(value, 0, multiline, false).flatten();
217 }
218
219 void JsonCodec::encode(DynamicValue::Reader input, Type type, JsonValue::Builder output) const {
220 // TODO(someday): For interfaces, check for handlers on superclasses, per documentation...
221 // TODO(someday): For branded types, should we check for handlers on the generic?
222 // TODO(someday): Allow registering handlers for "all structs", "all lists", etc?
223 KJ_IF_MAYBE(handler, impl->typeHandlers.find(type)) {
224 (*handler)->encodeBase(*this, input, output);
225 return;
226 }
227
228 switch (type.which()) {
229 case schema::Type::VOID:
230 output.setNull();
231 break;
232 case schema::Type::BOOL:
233 output.setBoolean(input.as<bool>());
234 break;
235 case schema::Type::INT8:
236 case schema::Type::INT16:
237 case schema::Type::INT32:
238 case schema::Type::UINT8:
239 case schema::Type::UINT16:
240 case schema::Type::UINT32:
241 output.setNumber(input.as<double>());
242 break;
243 case schema::Type::FLOAT32:
244 case schema::Type::FLOAT64:
245 {
246 double value = input.as<double>();
247 // Inf, -inf and NaN are not allowed in the JSON spec. Storing into string.
248 if (kj::inf() == value) {
249 output.setString("Infinity");
250 } else if (-kj::inf() == value) {
251 output.setString("-Infinity");
252 } else if (kj::isNaN(value)) {
253 output.setString("NaN");
254 } else {
255 output.setNumber(value);
256 }
257 }
258 break;
259 case schema::Type::INT64:
260 output.setString(kj::str(input.as<int64_t>()));
261 break;
262 case schema::Type::UINT64:
263 output.setString(kj::str(input.as<uint64_t>()));
264 break;
265 case schema::Type::TEXT:
266 output.setString(kj::str(input.as<Text>()));
267 break;
268 case schema::Type::DATA: {
269 // Turn into array of byte values. Yep, this is pretty ugly. People really need to override
270 // this with a handler.
271 auto bytes = input.as<Data>();
272 auto array = output.initArray(bytes.size());
273 for (auto i: kj::indices(bytes)) {
274 array[i].setNumber(bytes[i]);
275 }
276 break;
277 }
278 case schema::Type::LIST: {
279 auto list = input.as<DynamicList>();
280 auto elementType = type.asList().getElementType();
281 auto array = output.initArray(list.size());
282 for (auto i: kj::indices(list)) {
283 encode(list[i], elementType, array[i]);
284 }
285 break;
286 }
287 case schema::Type::ENUM: {
288 auto e = input.as<DynamicEnum>();
289 KJ_IF_MAYBE(symbol, e.getEnumerant()) {
290 output.setString(symbol->getProto().getName());
291 } else {
292 output.setNumber(e.getRaw());
293 }
294 break;
295 }
296 case schema::Type::STRUCT: {
297 auto structValue = input.as<capnp::DynamicStruct>();
298 auto nonUnionFields = structValue.getSchema().getNonUnionFields();
299
300 KJ_STACK_ARRAY(bool, hasField, nonUnionFields.size(), 32, 128);
301
302 uint fieldCount = 0;
303 for (auto i: kj::indices(nonUnionFields)) {
304 fieldCount += (hasField[i] = structValue.has(nonUnionFields[i], impl->hasMode));
305 }
306
307 // We try to write the union field, if any, in proper order with the rest.
308 auto which = structValue.which();
309 bool unionFieldIsNull = false;
310
311 KJ_IF_MAYBE(field, which) {
312 // Even if the union field is null, if it is not the default field of the union then we
313 // have to print it anyway.
314 unionFieldIsNull = !structValue.has(*field, impl->hasMode);
315 if (field->getProto().getDiscriminantValue() != 0 || !unionFieldIsNull) {
316 ++fieldCount;
317 } else {
318 which = nullptr;
319 }
320 }
321
322 auto object = output.initObject(fieldCount);
323
324 size_t pos = 0;
325 for (auto i: kj::indices(nonUnionFields)) {
326 auto field = nonUnionFields[i];
327 KJ_IF_MAYBE(unionField, which) {
328 if (unionField->getIndex() < field.getIndex()) {
329 auto outField = object[pos++];
330 outField.setName(unionField->getProto().getName());
331 if (unionFieldIsNull) {
332 outField.initValue().setNull();
333 } else {
334 encodeField(*unionField, structValue.get(*unionField), outField.initValue());
335 }
336 which = nullptr;
337 }
338 }
339 if (hasField[i]) {
340 auto outField = object[pos++];
341 outField.setName(field.getProto().getName());
342 encodeField(field, structValue.get(field), outField.initValue());
343 }
344 }
345 if (which != nullptr) {
346 // Union field not printed yet; must be last.
347 auto unionField = KJ_ASSERT_NONNULL(which);
348 auto outField = object[pos++];
349 outField.setName(unionField.getProto().getName());
350 if (unionFieldIsNull) {
351 outField.initValue().setNull();
352 } else {
353 encodeField(unionField, structValue.get(unionField), outField.initValue());
354 }
355 }
356 KJ_ASSERT(pos == fieldCount);
357 break;
358 }
359 case schema::Type::INTERFACE:
360 KJ_FAIL_REQUIRE("don't know how to JSON-encode capabilities; "
361 "please register a JsonCodec::Handler for this");
362 case schema::Type::ANY_POINTER:
363 KJ_FAIL_REQUIRE("don't know how to JSON-encode AnyPointer; "
364 "please register a JsonCodec::Handler for this");
365 }
366 }
367
368 void JsonCodec::encodeField(StructSchema::Field field, DynamicValue::Reader input,
369 JsonValue::Builder output) const {
370 KJ_IF_MAYBE(handler, impl->fieldHandlers.find(field)) {
371 (*handler)->encodeBase(*this, input, output);
372 return;
373 }
374
375 encode(input, field.getType(), output);
376 }
377
378 Orphan<DynamicList> JsonCodec::decodeArray(List<JsonValue>::Reader input, ListSchema type, Orphanage orphanage) const {
379 auto orphan = orphanage.newOrphan(type, input.size());
380 auto output = orphan.get();
381 for (auto i: kj::indices(input)) {
382 output.adopt(i, decode(input[i], type.getElementType(), orphanage));
383 }
384 return orphan;
385 }
386
387 void JsonCodec::decodeObject(JsonValue::Reader input, StructSchema type, Orphanage orphanage, DynamicStruct::Builder output) const {
388 KJ_REQUIRE(input.isObject(), "Expected object value") { return; }
389 for (auto field: input.getObject()) {
390 KJ_IF_MAYBE(fieldSchema, type.findFieldByName(field.getName())) {
391 decodeField(*fieldSchema, field.getValue(), orphanage, output);
392 } else {
393 KJ_REQUIRE(!impl->rejectUnknownFields, "Unknown field", field.getName());
394 }
395 }
396 }
397
398 void JsonCodec::decodeField(StructSchema::Field fieldSchema, JsonValue::Reader fieldValue,
399 Orphanage orphanage, DynamicStruct::Builder output) const {
400 auto fieldType = fieldSchema.getType();
401
402 KJ_IF_MAYBE(handler, impl->fieldHandlers.find(fieldSchema)) {
403 output.adopt(fieldSchema, (*handler)->decodeBase(*this, fieldValue, fieldType, orphanage));
404 } else {
405 output.adopt(fieldSchema, decode(fieldValue, fieldType, orphanage));
406 }
407 }
408
409 void JsonCodec::decode(JsonValue::Reader input, DynamicStruct::Builder output) const {
410 auto type = output.getSchema();
411
412 KJ_IF_MAYBE(handler, impl->typeHandlers.find(type)) {
413 return (*handler)->decodeStructBase(*this, input, output);
414 }
415
416 decodeObject(input, type, Orphanage::getForMessageContaining(output), output);
417 }
418
419 Orphan<DynamicValue> JsonCodec::decode(
420 JsonValue::Reader input, Type type, Orphanage orphanage) const {
421 KJ_IF_MAYBE(handler, impl->typeHandlers.find(type)) {
422 return (*handler)->decodeBase(*this, input, type, orphanage);
423 }
424
425 switch(type.which()) {
426 case schema::Type::VOID:
427 return capnp::VOID;
428 case schema::Type::BOOL:
429 switch (input.which()) {
430 case JsonValue::BOOLEAN:
431 return input.getBoolean();
432 default:
433 KJ_FAIL_REQUIRE("Expected boolean value");
434 }
435 case schema::Type::INT8:
436 case schema::Type::INT16:
437 case schema::Type::INT32:
438 case schema::Type::INT64:
439 // Relies on range check in DynamicValue::Reader::as<IntType>
440 switch (input.which()) {
441 case JsonValue::NUMBER:
442 return input.getNumber();
443 case JsonValue::STRING:
444 return input.getString().parseAs<int64_t>();
445 default:
446 KJ_FAIL_REQUIRE("Expected integer value");
447 }
448 case schema::Type::UINT8:
449 case schema::Type::UINT16:
450 case schema::Type::UINT32:
451 case schema::Type::UINT64:
452 // Relies on range check in DynamicValue::Reader::as<IntType>
453 switch (input.which()) {
454 case JsonValue::NUMBER:
455 return input.getNumber();
456 case JsonValue::STRING:
457 return input.getString().parseAs<uint64_t>();
458 default:
459 KJ_FAIL_REQUIRE("Expected integer value");
460 }
461 case schema::Type::FLOAT32:
462 case schema::Type::FLOAT64:
463 switch (input.which()) {
464 case JsonValue::NULL_:
465 return kj::nan();
466 case JsonValue::NUMBER:
467 return input.getNumber();
468 case JsonValue::STRING:
469 return input.getString().parseAs<double>();
470 default:
471 KJ_FAIL_REQUIRE("Expected float value");
472 }
473 case schema::Type::TEXT:
474 switch (input.which()) {
475 case JsonValue::STRING:
476 return orphanage.newOrphanCopy(input.getString());
477 default:
478 KJ_FAIL_REQUIRE("Expected text value");
479 }
480 case schema::Type::DATA:
481 switch (input.which()) {
482 case JsonValue::ARRAY: {
483 auto array = input.getArray();
484 auto orphan = orphanage.newOrphan<Data>(array.size());
485 auto data = orphan.get();
486 for (auto i: kj::indices(array)) {
487 auto x = array[i].getNumber();
488 KJ_REQUIRE(byte(x) == x, "Number in byte array is not an integer in [0, 255]");
489 data[i] = x;
490 }
491 return kj::mv(orphan);
492 }
493 default:
494 KJ_FAIL_REQUIRE("Expected data value");
495 }
496 case schema::Type::LIST:
497 switch (input.which()) {
498 case JsonValue::ARRAY:
499 return decodeArray(input.getArray(), type.asList(), orphanage);
500 default:
501 KJ_FAIL_REQUIRE("Expected list value") { break; }
502 return orphanage.newOrphan(type.asList(), 0);
503 }
504 case schema::Type::ENUM:
505 switch (input.which()) {
506 case JsonValue::STRING:
507 return DynamicEnum(type.asEnum().getEnumerantByName(input.getString()));
508 default:
509 KJ_FAIL_REQUIRE("Expected enum value") { break; }
510 return DynamicEnum(type.asEnum(), 0);
511 }
512 case schema::Type::STRUCT: {
513 auto structType = type.asStruct();
514 auto orphan = orphanage.newOrphan(structType);
515 decodeObject(input, structType, orphanage, orphan.get());
516 return kj::mv(orphan);
517 }
518 case schema::Type::INTERFACE:
519 KJ_FAIL_REQUIRE("don't know how to JSON-decode capabilities; "
520 "please register a JsonCodec::Handler for this");
521 case schema::Type::ANY_POINTER:
522 KJ_FAIL_REQUIRE("don't know how to JSON-decode AnyPointer; "
523 "please register a JsonCodec::Handler for this");
524 }
525
526 KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT;
527 }
528
529 // -----------------------------------------------------------------------------
530
531 namespace {
532
533 class Input {
534 public:
535 Input(kj::ArrayPtr<const char> input) : wrapped(input) {}
536
537 bool exhausted() {
538 return wrapped.size() == 0 || wrapped.front() == '\0';
539 }
540
541 char nextChar() {
542 KJ_REQUIRE(!exhausted(), "JSON message ends prematurely.");
543 return wrapped.front();
544 }
545
546 void advance(size_t numBytes = 1) {
547 KJ_REQUIRE(numBytes <= wrapped.size(), "JSON message ends prematurely.");
548 wrapped = kj::arrayPtr(wrapped.begin() + numBytes, wrapped.end());
549 }
550
551 void advanceTo(const char *newPos) {
552 KJ_REQUIRE(wrapped.begin() <= newPos && newPos < wrapped.end(),
553 "JSON message ends prematurely.");
554 wrapped = kj::arrayPtr(newPos, wrapped.end());
555 }
556
557 kj::ArrayPtr<const char> consume(size_t numBytes = 1) {
558 auto originalPos = wrapped.begin();
559 advance(numBytes);
560
561 return kj::arrayPtr(originalPos, wrapped.begin());
562 }
563
564 void consume(char expected) {
565 char current = nextChar();
566 KJ_REQUIRE(current == expected, "Unexpected input in JSON message.");
567
568 advance();
569 }
570
571 void consume(kj::ArrayPtr<const char> expected) {
572 KJ_REQUIRE(wrapped.size() >= expected.size());
573
574 auto prefix = wrapped.slice(0, expected.size());
575 KJ_REQUIRE(prefix == expected, "Unexpected input in JSON message.");
576
577 advance(expected.size());
578 }
579
580 bool tryConsume(char expected) {
581 bool found = !exhausted() && nextChar() == expected;
582 if (found) { advance(); }
583
584 return found;
585 }
586
587 template <typename Predicate>
588 void consumeOne(Predicate&& predicate) {
589 char current = nextChar();
590 KJ_REQUIRE(predicate(current), "Unexpected input in JSON message.");
591
592 advance();
593 }
594
595 template <typename Predicate>
596 kj::ArrayPtr<const char> consumeWhile(Predicate&& predicate) {
597 auto originalPos = wrapped.begin();
598 while (!exhausted() && predicate(nextChar())) { advance(); }
599
600 return kj::arrayPtr(originalPos, wrapped.begin());
601 }
602
603 template <typename F> // Function<void(Input&)>
604 kj::ArrayPtr<const char> consumeCustom(F&& f) {
605 // Allows consuming in a custom manner without exposing the wrapped ArrayPtr.
606 auto originalPos = wrapped.begin();
607 f(*this);
608
609 return kj::arrayPtr(originalPos, wrapped.begin());
610 }
611
612 void consumeWhitespace() {
613 consumeWhile([](char chr) {
614 return (
615 chr == ' ' ||
616 chr == '\n' ||
617 chr == '\r' ||
618 chr == '\t'
619 );
620 });
621 }
622
623
624 private:
625 kj::ArrayPtr<const char> wrapped;
626
627 }; // class Input
628
629 class Parser {
630 public:
631 Parser(size_t maxNestingDepth, kj::ArrayPtr<const char> input) :
632 maxNestingDepth(maxNestingDepth), input(input), nestingDepth(0) {}
633
634 void parseValue(JsonValue::Builder& output) {
635 input.consumeWhitespace();
636 KJ_DEFER(input.consumeWhitespace());
637
638 KJ_REQUIRE(!input.exhausted(), "JSON message ends prematurely.");
639
640 switch (input.nextChar()) {
641 case 'n': input.consume(kj::StringPtr("null")); output.setNull(); break;
642 case 'f': input.consume(kj::StringPtr("false")); output.setBoolean(false); break;
643 case 't': input.consume(kj::StringPtr("true")); output.setBoolean(true); break;
644 case '"': parseString(output); break;
645 case '[': parseArray(output); break;
646 case '{': parseObject(output); break;
647 case '-': case '0': case '1': case '2': case '3':
648 case '4': case '5': case '6': case '7': case '8':
649 case '9': parseNumber(output); break;
650 default: KJ_FAIL_REQUIRE("Unexpected input in JSON message.");
651 }
652 }
653
654 void parseNumber(JsonValue::Builder& output) {
655 output.setNumber(consumeNumber().parseAs<double>());
656 }
657
658 void parseString(JsonValue::Builder& output) {
659 output.setString(consumeQuotedString());
660 }
661
662 void parseArray(JsonValue::Builder& output) {
663 // TODO(perf): Using orphans leaves holes in the message. It's expected
664 // that a JsonValue is used for interop, and won't be sent or written as a
665 // Cap'n Proto message. This also applies to parseObject below.
666 kj::Vector<Orphan<JsonValue>> values;
667 auto orphanage = Orphanage::getForMessageContaining(output);
668 bool expectComma = false;
669
670 input.consume('[');
671 KJ_REQUIRE(++nestingDepth <= maxNestingDepth, "JSON message nested too deeply.");
672 KJ_DEFER(--nestingDepth);
673
674 while (input.consumeWhitespace(), input.nextChar() != ']') {
675 auto orphan = orphanage.newOrphan<JsonValue>();
676 auto builder = orphan.get();
677
678 if (expectComma) {
679 input.consumeWhitespace();
680 input.consume(',');
681 input.consumeWhitespace();
682 }
683
684 parseValue(builder);
685 values.add(kj::mv(orphan));
686
687 expectComma = true;
688 }
689
690 output.initArray(values.size());
691 auto array = output.getArray();
692
693 for (auto i : kj::indices(values)) {
694 array.adoptWithCaveats(i, kj::mv(values[i]));
695 }
696
697 input.consume(']');
698 }
699
700 void parseObject(JsonValue::Builder& output) {
701 kj::Vector<Orphan<JsonValue::Field>> fields;
702 auto orphanage = Orphanage::getForMessageContaining(output);
703 bool expectComma = false;
704
705 input.consume('{');
706 KJ_REQUIRE(++nestingDepth <= maxNestingDepth, "JSON message nested too deeply.");
707 KJ_DEFER(--nestingDepth);
708
709 while (input.consumeWhitespace(), input.nextChar() != '}') {
710 auto orphan = orphanage.newOrphan<JsonValue::Field>();
711 auto builder = orphan.get();
712
713 if (expectComma) {
714 input.consumeWhitespace();
715 input.consume(',');
716 input.consumeWhitespace();
717 }
718
719 builder.setName(consumeQuotedString());
720
721 input.consumeWhitespace();
722 input.consume(':');
723 input.consumeWhitespace();
724
725 auto valueBuilder = builder.getValue();
726 parseValue(valueBuilder);
727
728 fields.add(kj::mv(orphan));
729
730 expectComma = true;
731 }
732
733 output.initObject(fields.size());
734 auto object = output.getObject();
735
736 for (auto i : kj::indices(fields)) {
737 object.adoptWithCaveats(i, kj::mv(fields[i]));
738 }
739
740 input.consume('}');
741 }
742
743 bool inputExhausted() { return input.exhausted(); }
744
745 private:
746 kj::String consumeQuotedString() {
747 input.consume('"');
748 // TODO(perf): Avoid copy / alloc if no escapes encountered.
749 // TODO(perf): Get statistics on string size and preallocate?
750 kj::Vector<char> decoded;
751
752 do {
753 auto stringValue = input.consumeWhile([](const char chr) {
754 return chr != '"' && chr != '\\';
755 });
756
757 decoded.addAll(stringValue);
758
759 if (input.nextChar() == '\\') { // handle escapes.
760 input.advance();
761 switch(input.nextChar()) {
762 case '"' : decoded.add('"' ); input.advance(); break;
763 case '\\': decoded.add('\\'); input.advance(); break;
764 case '/' : decoded.add('/' ); input.advance(); break;
765 case 'b' : decoded.add('\b'); input.advance(); break;
766 case 'f' : decoded.add('\f'); input.advance(); break;
767 case 'n' : decoded.add('\n'); input.advance(); break;
768 case 'r' : decoded.add('\r'); input.advance(); break;
769 case 't' : decoded.add('\t'); input.advance(); break;
770 case 'u' :
771 input.consume('u');
772 unescapeAndAppend(input.consume(size_t(4)), decoded);
773 break;
774 default: KJ_FAIL_REQUIRE("Invalid escape in JSON string."); break;
775 }
776 }
777
778 } while(input.nextChar() != '"');
779
780 input.consume('"');
781 decoded.add('\0');
782
783 // TODO(perf): This copy can be eliminated, but I can't find the kj::wayToDoIt();
784 return kj::String(decoded.releaseAsArray());
785 }
786
787 kj::String consumeNumber() {
788 auto numArrayPtr = input.consumeCustom([](Input& input) {
789 input.tryConsume('-');
790 if (!input.tryConsume('0')) {
791 input.consumeOne([](char c) { return '1' <= c && c <= '9'; });
792 input.consumeWhile([](char c) { return '0' <= c && c <= '9'; });
793 }
794
795 if (input.tryConsume('.')) {
796 input.consumeWhile([](char c) { return '0' <= c && c <= '9'; });
797 }
798
799 if (input.tryConsume('e') || input.tryConsume('E')) {
800 input.tryConsume('+') || input.tryConsume('-');
801 input.consumeWhile([](char c) { return '0' <= c && c <= '9'; });
802 }
803 });
804
805 KJ_REQUIRE(numArrayPtr.size() > 0, "Expected number in JSON input.");
806
807 kj::Vector<char> number;
808 number.addAll(numArrayPtr);
809 number.add('\0');
810
811 return kj::String(number.releaseAsArray());
812 }
813
814 // TODO(someday): This "interface" is ugly, and won't work if/when surrogates are handled.
815 void unescapeAndAppend(kj::ArrayPtr<const char> hex, kj::Vector<char>& target) {
816 KJ_REQUIRE(hex.size() == 4);
817 int codePoint = 0;
818
819 for (int i = 0; i < 4; ++i) {
820 char c = hex[i];
821 codePoint <<= 4;
822
823 if ('0' <= c && c <= '9') {
824 codePoint |= c - '0';
825 } else if ('a' <= c && c <= 'f') {
826 codePoint |= c - 'a' + 10;
827 } else if ('A' <= c && c <= 'F') {
828 codePoint |= c - 'A' + 10;
829 } else {
830 KJ_FAIL_REQUIRE("Invalid hex digit in unicode escape.", c);
831 }
832 }
833
834 if (codePoint < 128) {
835 target.add(0x7f & static_cast<char>(codePoint));
836 } else {
837 // TODO(perf): This is sorta malloc-heavy...
838 char16_t u = codePoint;
839 target.addAll(kj::decodeUtf16(kj::arrayPtr(&u, 1)));
840 }
841 }
842
843 const size_t maxNestingDepth;
844 Input input;
845 size_t nestingDepth;
846
847
848 }; // class Parser
849
850 } // namespace
851
852
853 void JsonCodec::decodeRaw(kj::ArrayPtr<const char> input, JsonValue::Builder output) const {
854 Parser parser(impl->maxNestingDepth, input);
855 parser.parseValue(output);
856
857 KJ_REQUIRE(parser.inputExhausted(), "Input remains after parsing JSON.");
858 }
859
860 // -----------------------------------------------------------------------------
861
862 Orphan<DynamicValue> JsonCodec::HandlerBase::decodeBase(
863 const JsonCodec& codec, JsonValue::Reader input, Type type, Orphanage orphanage) const {
864 KJ_FAIL_ASSERT("JSON decoder handler type / value type mismatch");
865 }
866 void JsonCodec::HandlerBase::decodeStructBase(
867 const JsonCodec& codec, JsonValue::Reader input, DynamicStruct::Builder output) const {
868 KJ_FAIL_ASSERT("JSON decoder handler type / value type mismatch");
869 }
870
871 void JsonCodec::addTypeHandlerImpl(Type type, HandlerBase& handler) {
872 impl->typeHandlers.upsert(type, &handler, [](HandlerBase*& existing, HandlerBase* replacement) {
873 KJ_REQUIRE(existing == replacement, "type already has a different registered handler");
874 });
875 }
876
877 void JsonCodec::addFieldHandlerImpl(StructSchema::Field field, Type type, HandlerBase& handler) {
878 KJ_REQUIRE(type == field.getType(),
879 "handler type did not match field type for addFieldHandler()");
880 impl->fieldHandlers.upsert(field, &handler, [](HandlerBase*& existing, HandlerBase* replacement) {
881 KJ_REQUIRE(existing == replacement, "field already has a different registered handler");
882 });
883 }
884
885 // =======================================================================================
886
887 static constexpr uint64_t JSON_NAME_ANNOTATION_ID = 0xfa5b1fd61c2e7c3dull;
888 static constexpr uint64_t JSON_FLATTEN_ANNOTATION_ID = 0x82d3e852af0336bfull;
889 static constexpr uint64_t JSON_DISCRIMINATOR_ANNOTATION_ID = 0xcfa794e8d19a0162ull;
890 static constexpr uint64_t JSON_BASE64_ANNOTATION_ID = 0xd7d879450a253e4bull;
891 static constexpr uint64_t JSON_HEX_ANNOTATION_ID = 0xf061e22f0ae5c7b5ull;
892
893 class JsonCodec::Base64Handler final: public JsonCodec::Handler<capnp::Data> {
894 public:
895 void encode(const JsonCodec& codec, capnp::Data::Reader input, JsonValue::Builder output) const {
896 output.setString(kj::encodeBase64(input));
897 }
898
899 Orphan<capnp::Data> decode(const JsonCodec& codec, JsonValue::Reader input,
900 Orphanage orphanage) const {
901 return orphanage.newOrphanCopy(capnp::Data::Reader(kj::decodeBase64(input.getString())));
902 }
903 };
904
905 class JsonCodec::HexHandler final: public JsonCodec::Handler<capnp::Data> {
906 public:
907 void encode(const JsonCodec& codec, capnp::Data::Reader input, JsonValue::Builder output) const {
908 output.setString(kj::encodeHex(input));
909 }
910
911 Orphan<capnp::Data> decode(const JsonCodec& codec, JsonValue::Reader input,
912 Orphanage orphanage) const {
913 return orphanage.newOrphanCopy(capnp::Data::Reader(kj::decodeHex(input.getString())));
914 }
915 };
916
917 class JsonCodec::AnnotatedHandler final: public JsonCodec::Handler<DynamicStruct> {
918 public:
919 AnnotatedHandler(JsonCodec& codec, StructSchema schema,
920 kj::Maybe<json::DiscriminatorOptions::Reader> discriminator,
921 kj::Maybe<kj::StringPtr> unionDeclName,
922 kj::Vector<Schema>& dependencies)
923 : schema(schema) {
924 auto schemaProto = schema.getProto();
925 auto typeName = schemaProto.getDisplayName();
926
927 if (discriminator == nullptr) {
928 // There are two cases of unions:
929 // * Named unions, which are special cases of named groups. In this case, the union may be
930 // annotated by annotating the field. In this case, we receive a non-null `discriminator`
931 // as a constructor parameter, and schemaProto.getAnnotations() must be empty because
932 // it's not possible to annotate a group's type (because the type is anonymous).
933 // * Unnamed unions, of which there can only be one in any particular scope. In this case,
934 // the parent struct type itself is annotated.
935 // So if we received `null` as the constructor parameter, check for annotations on the struct
936 // type.
937 for (auto anno: schemaProto.getAnnotations()) {
938 switch (anno.getId()) {
939 case JSON_DISCRIMINATOR_ANNOTATION_ID:
940 discriminator = anno.getValue().getStruct().getAs<json::DiscriminatorOptions>();
941 break;
942 }
943 }
944 }
945
946 KJ_IF_MAYBE(d, discriminator) {
947 if (d->hasName()) {
948 unionTagName = d->getName();
949 } else {
950 unionTagName = unionDeclName;
951 }
952 KJ_IF_MAYBE(u, unionTagName) {
953 fieldsByName.insert(*u, FieldNameInfo {
954 FieldNameInfo::UNION_TAG, 0, 0, nullptr
955 });
956 }
957
958 if (d->hasValueName()) {
959 fieldsByName.insert(d->getValueName(), FieldNameInfo {
960 FieldNameInfo::UNION_VALUE, 0, 0, nullptr
961 });
962 }
963 }
964
965 discriminantOffset = schemaProto.getStruct().getDiscriminantOffset();
966
967 fields = KJ_MAP(field, schema.getFields()) {
968 auto fieldProto = field.getProto();
969 auto type = field.getType();
970 auto fieldName = fieldProto.getName();
971
972 FieldNameInfo nameInfo;
973 nameInfo.index = field.getIndex();
974 nameInfo.type = FieldNameInfo::NORMAL;
975 nameInfo.prefixLength = 0;
976
977 FieldInfo info;
978 info.name = fieldName;
979
980 kj::Maybe<json::DiscriminatorOptions::Reader> subDiscriminator;
981 bool flattened = false;
982 for (auto anno: field.getProto().getAnnotations()) {
983 switch (anno.getId()) {
984 case JSON_NAME_ANNOTATION_ID:
985 info.name = anno.getValue().getText();
986 break;
987 case JSON_FLATTEN_ANNOTATION_ID:
988 KJ_REQUIRE(type.isStruct(), "only struct types can be flattened", fieldName, typeName);
989 flattened = true;
990 info.prefix = anno.getValue().getStruct().getAs<json::FlattenOptions>().getPrefix();
991 break;
992 case JSON_DISCRIMINATOR_ANNOTATION_ID:
993 KJ_REQUIRE(fieldProto.isGroup(), "only unions can have discriminator");
994 subDiscriminator = anno.getValue().getStruct().getAs<json::DiscriminatorOptions>();
995 break;
996 case JSON_BASE64_ANNOTATION_ID: {
997 KJ_REQUIRE(field.getType().isData(), "only Data can be marked for base64 encoding");
998 static Base64Handler handler;
999 codec.addFieldHandler(field, handler);
1000 break;
1001 }
1002 case JSON_HEX_ANNOTATION_ID: {
1003 KJ_REQUIRE(field.getType().isData(), "only Data can be marked for hex encoding");
1004 static HexHandler handler;
1005 codec.addFieldHandler(field, handler);
1006 break;
1007 }
1008 }
1009 }
1010
1011 if (fieldProto.isGroup()) {
1012 // Load group type handler now, even if not flattened, so that we can pass its
1013 // `subDiscriminator`.
1014 kj::Maybe<kj::StringPtr> subFieldName;
1015 if (flattened) {
1016 // If the group was flattened, then we allow its field name to be used as the
1017 // discriminator name, so that the discriminator doesn't have to explicitly specify a
1018 // name.
1019 subFieldName = fieldName;
1020 }
1021 auto& subHandler = codec.loadAnnotatedHandler(
1022 type.asStruct(), subDiscriminator, subFieldName, dependencies);
1023 if (flattened) {
1024 info.flattenHandler = subHandler;
1025 }
1026 } else if (type.isStruct()) {
1027 if (flattened) {
1028 info.flattenHandler = codec.loadAnnotatedHandler(
1029 type.asStruct(), nullptr, nullptr, dependencies);
1030 }
1031 }
1032
1033 bool isUnionMember = fieldProto.getDiscriminantValue() != schema::Field::NO_DISCRIMINANT;
1034
1035 KJ_IF_MAYBE(fh, info.flattenHandler) {
1036 // Set up fieldsByName for each of the child's fields.
1037 for (auto& entry: fh->fieldsByName) {
1038 kj::StringPtr flattenedName;
1039 kj::String ownName;
1040 if (info.prefix.size() > 0) {
1041 ownName = kj::str(info.prefix, entry.key);
1042 flattenedName = ownName;
1043 } else {
1044 flattenedName = entry.key;
1045 }
1046
1047 fieldsByName.upsert(flattenedName, FieldNameInfo {
1048 isUnionMember ? FieldNameInfo::FLATTENED_FROM_UNION : FieldNameInfo::FLATTENED,
1049 field.getIndex(), (uint)info.prefix.size(), kj::mv(ownName)
1050 }, [&](FieldNameInfo& existing, FieldNameInfo&& replacement) {
1051 KJ_REQUIRE(existing.type == FieldNameInfo::FLATTENED_FROM_UNION &&
1052 replacement.type == FieldNameInfo::FLATTENED_FROM_UNION,
1053 "flattened members have the same name and are not mutually exclusive");
1054 });
1055 }
1056 }
1057
1058 info.nameForDiscriminant = info.name;
1059
1060 if (!flattened) {
1061 bool isUnionWithValueName = false;
1062 if (isUnionMember) {
1063 KJ_IF_MAYBE(d, discriminator) {
1064 if (d->hasValueName()) {
1065 info.name = d->getValueName();
1066 isUnionWithValueName = true;
1067 }
1068 }
1069 }
1070
1071 if (!isUnionWithValueName) {
1072 fieldsByName.insert(info.name, kj::mv(nameInfo));
1073 }
1074 }
1075
1076 if (isUnionMember) {
1077 unionTagValues.insert(info.nameForDiscriminant, field);
1078 }
1079
1080 // Look for dependencies that we need to add.
1081 while (type.isList()) type = type.asList().getElementType();
1082 if (codec.impl->typeHandlers.find(type) == nullptr) {
1083 switch (type.which()) {
1084 case schema::Type::STRUCT:
1085 dependencies.add(type.asStruct());
1086 break;
1087 case schema::Type::ENUM:
1088 dependencies.add(type.asEnum());
1089 break;
1090 case schema::Type::INTERFACE:
1091 dependencies.add(type.asInterface());
1092 break;
1093 default:
1094 break;
1095 }
1096 }
1097
1098 return info;
1099 };
1100 }
1101
1102 const StructSchema schema;
1103
1104 void encode(const JsonCodec& codec, DynamicStruct::Reader input,
1105 JsonValue::Builder output) const override {
1106 kj::Vector<FlattenedField> flattenedFields;
1107 gatherForEncode(codec, input, nullptr, nullptr, flattenedFields);
1108
1109 auto outs = output.initObject(flattenedFields.size());
1110 for (auto i: kj::indices(flattenedFields)) {
1111 auto& in = flattenedFields[i];
1112 auto out = outs[i];
1113 out.setName(in.name);
1114 KJ_SWITCH_ONEOF(in.type) {
1115 KJ_CASE_ONEOF(type, Type) {
1116 codec.encode(in.value, type, out.initValue());
1117 }
1118 KJ_CASE_ONEOF(field, StructSchema::Field) {
1119 codec.encodeField(field, in.value, out.initValue());
1120 }
1121 }
1122 }
1123 }
1124
1125 void decode(const JsonCodec& codec, JsonValue::Reader input,
1126 DynamicStruct::Builder output) const override {
1127 KJ_REQUIRE(input.isObject());
1128 kj::HashSet<const void*> unionsSeen;
1129 kj::Vector<JsonValue::Field::Reader> retries;
1130 for (auto field: input.getObject()) {
1131 if (!decodeField(codec, field.getName(), field.getValue(), output, unionsSeen)) {
1132 retries.add(field);
1133 }
1134 }
1135 while (!retries.empty()) {
1136 auto retriesCopy = kj::mv(retries);
1137 KJ_ASSERT(retries.empty());
1138 for (auto field: retriesCopy) {
1139 if (!decodeField(codec, field.getName(), field.getValue(), output, unionsSeen)) {
1140 retries.add(field);
1141 }
1142 }
1143 if (retries.size() == retriesCopy.size()) {
1144 // We made no progress in this iteration. Give up on the remaining fields.
1145 break;
1146 }
1147 }
1148 }
1149
1150 private:
1151 struct FieldInfo {
1152 kj::StringPtr name;
1153 kj::StringPtr nameForDiscriminant;
1154 kj::Maybe<const AnnotatedHandler&> flattenHandler;
1155 kj::StringPtr prefix;
1156 };
1157
1158 kj::Array<FieldInfo> fields;
1159 // Maps field index -> info about the field
1160
1161 struct FieldNameInfo {
1162 enum {
1163 NORMAL,
1164 // This is a normal field with the given `index`.
1165
1166 FLATTENED,
1167 // This is a field of a flattened inner struct or group (that is not in a union). `index`
1168 // is the field index of the particular struct/group field.
1169
1170 UNION_TAG,
1171 // The parent struct is a flattened union, and this field is the discriminant tag. It is a
1172 // string field whose name determines the union type. `index` is not used.
1173
1174 FLATTENED_FROM_UNION,
1175 // The parent struct is a flattened union, and some of the union's members are flattened
1176 // structs or groups, and this field is possibly a member of one or more of them. `index`
1177 // is not used, because it's possible that the same field name appears in multiple variants.
1178 // Instead, the parser must find the union tag, and then can descend and attempt to parse
1179 // the field in the context of whichever variant is selected.
1180
1181 UNION_VALUE
1182 // This field is the value of a discriminated union that has `valueName` set.
1183 } type;
1184
1185 uint index;
1186 // For `NORMAL` and `FLATTENED`, the index of the field in schema.getFields().
1187
1188 uint prefixLength;
1189 kj::String ownName;
1190 };
1191
1192 kj::HashMap<kj::StringPtr, FieldNameInfo> fieldsByName;
1193 // Maps JSON names to info needed to parse them.
1194
1195 kj::HashMap<kj::StringPtr, StructSchema::Field> unionTagValues;
1196 // If the parent struct is a flattened union, it has a tag field which is a string with one of
1197 // these values. The map maps to the union member to set.
1198
1199 kj::Maybe<kj::StringPtr> unionTagName;
1200 // If the parent struct is a flattened union, the name of the "tag" field.
1201
1202 uint discriminantOffset;
1203 // Shortcut for schema.getProto().getStruct().getDiscriminantOffset(), used in a hack to identify
1204 // which unions have been seen.
1205
1206 struct FlattenedField {
1207 kj::String ownName;
1208 kj::StringPtr name;
1209 kj::OneOf<StructSchema::Field, Type> type;
1210 DynamicValue::Reader value;
1211
1212 FlattenedField(kj::StringPtr prefix, kj::StringPtr name,
1213 kj::OneOf<StructSchema::Field, Type> type, DynamicValue::Reader value)
1214 : ownName(prefix.size() > 0 ? kj::str(prefix, name) : nullptr),
1215 name(prefix.size() > 0 ? ownName : name),
1216 type(type), value(value) {}
1217 };
1218
1219 void gatherForEncode(const JsonCodec& codec, DynamicValue::Reader input,
1220 kj::StringPtr prefix, kj::StringPtr morePrefix,
1221 kj::Vector<FlattenedField>& flattenedFields) const {
1222 kj::String ownPrefix;
1223 if (morePrefix.size() > 0) {
1224 if (prefix.size() > 0) {
1225 ownPrefix = kj::str(prefix, morePrefix);
1226 prefix = ownPrefix;
1227 } else {
1228 prefix = morePrefix;
1229 }
1230 }
1231
1232 auto reader = input.as<DynamicStruct>();
1233 auto schema = reader.getSchema();
1234 for (auto field: schema.getNonUnionFields()) {
1235 auto& info = fields[field.getIndex()];
1236 if (!reader.has(field, codec.impl->hasMode)) {
1237 // skip
1238 } else KJ_IF_MAYBE(handler, info.flattenHandler) {
1239 handler->gatherForEncode(codec, reader.get(field), prefix, info.prefix, flattenedFields);
1240 } else {
1241 flattenedFields.add(FlattenedField {
1242 prefix, info.name, field, reader.get(field) });
1243 }
1244 }
1245
1246 KJ_IF_MAYBE(which, reader.which()) {
1247 auto& info = fields[which->getIndex()];
1248 KJ_IF_MAYBE(tag, unionTagName) {
1249 flattenedFields.add(FlattenedField {
1250 prefix, *tag, Type(schema::Type::TEXT), Text::Reader(info.nameForDiscriminant) });
1251 }
1252
1253 KJ_IF_MAYBE(handler, info.flattenHandler) {
1254 handler->gatherForEncode(codec, reader.get(*which), prefix, info.prefix, flattenedFields);
1255 } else {
1256 auto type = which->getType();
1257 if (type.which() == schema::Type::VOID && unionTagName != nullptr) {
1258 // When we have an explicit union discriminant, we don't need to encode void fields.
1259 } else {
1260 flattenedFields.add(FlattenedField {
1261 prefix, info.name, *which, reader.get(*which) });
1262 }
1263 }
1264 }
1265 }
1266
1267 bool decodeField(const JsonCodec& codec, kj::StringPtr name, JsonValue::Reader value,
1268 DynamicStruct::Builder output, kj::HashSet<const void*>& unionsSeen) const {
1269 KJ_ASSERT(output.getSchema() == schema);
1270
1271 KJ_IF_MAYBE(info, fieldsByName.find(name)) {
1272 switch (info->type) {
1273 case FieldNameInfo::NORMAL: {
1274 auto field = output.getSchema().getFields()[info->index];
1275 codec.decodeField(field, value, Orphanage::getForMessageContaining(output), output);
1276 return true;
1277 }
1278 case FieldNameInfo::FLATTENED:
1279 return KJ_ASSERT_NONNULL(fields[info->index].flattenHandler)
1280 .decodeField(codec, name.slice(info->prefixLength), value,
1281 output.get(output.getSchema().getFields()[info->index]).as<DynamicStruct>(),
1282 unionsSeen);
1283 case FieldNameInfo::UNION_TAG: {
1284 KJ_REQUIRE(value.isString(), "Expected string value.");
1285
1286 // Mark that we've seen a union tag for this struct.
1287 const void* ptr = getUnionInstanceIdentifier(output);
1288 KJ_IF_MAYBE(field, unionTagValues.find(value.getString())) {
1289 // clear() has the side-effect of activating this member of the union, without
1290 // allocating any objects.
1291 output.clear(*field);
1292 unionsSeen.insert(ptr);
1293 }
1294 return true;
1295 }
1296 case FieldNameInfo::FLATTENED_FROM_UNION: {
1297 const void* ptr = getUnionInstanceIdentifier(output);
1298 if (unionsSeen.contains(ptr)) {
1299 auto variant = KJ_ASSERT_NONNULL(output.which());
1300 return KJ_ASSERT_NONNULL(fields[variant.getIndex()].flattenHandler)
1301 .decodeField(codec, name.slice(info->prefixLength), value,
1302 output.get(variant).as<DynamicStruct>(), unionsSeen);
1303 } else {
1304 // We haven't seen the union tag yet, so we can't parse this field yet. Try again later.
1305 return false;
1306 }
1307 }
1308 case FieldNameInfo::UNION_VALUE: {
1309 const void* ptr = getUnionInstanceIdentifier(output);
1310 if (unionsSeen.contains(ptr)) {
1311 auto variant = KJ_ASSERT_NONNULL(output.which());
1312 codec.decodeField(variant, value, Orphanage::getForMessageContaining(output), output);
1313 return true;
1314 } else {
1315 // We haven't seen the union tag yet, so we can't parse this field yet. Try again later.
1316 return false;
1317 }
1318 }
1319 }
1320
1321 KJ_UNREACHABLE;
1322 } else {
1323 // Ignore undefined field -- unless the flag is set to reject them.
1324 KJ_REQUIRE(!codec.impl->rejectUnknownFields, "Unknown field", name);
1325 return true;
1326 }
1327 }
1328
1329 const void* getUnionInstanceIdentifier(DynamicStruct::Builder obj) const {
1330 // Gets a value uniquely identifying an instance of a union.
1331 // HACK: We return a pointer to the union's discriminant within the underlying buffer.
1332 return reinterpret_cast<const uint16_t*>(
1333 AnyStruct::Reader(obj.asReader()).getDataSection().begin()) + discriminantOffset;
1334 }
1335 };
1336
1337 class JsonCodec::AnnotatedEnumHandler final: public JsonCodec::Handler<DynamicEnum> {
1338 public:
1339 AnnotatedEnumHandler(EnumSchema schema): schema(schema) {
1340 auto enumerants = schema.getEnumerants();
1341 auto builder = kj::heapArrayBuilder<kj::StringPtr>(enumerants.size());
1342
1343 for (auto e: enumerants) {
1344 auto proto = e.getProto();
1345 kj::StringPtr name = proto.getName();
1346
1347 for (auto anno: proto.getAnnotations()) {
1348 switch (anno.getId()) {
1349 case JSON_NAME_ANNOTATION_ID:
1350 name = anno.getValue().getText();
1351 break;
1352 }
1353 }
1354
1355 builder.add(name);
1356 nameToValue.insert(name, e.getIndex());
1357 }
1358
1359 valueToName = builder.finish();
1360 }
1361
1362 void encode(const JsonCodec& codec, DynamicEnum input, JsonValue::Builder output) const override {
1363 KJ_IF_MAYBE(e, input.getEnumerant()) {
1364 KJ_ASSERT(e->getIndex() < valueToName.size());
1365 output.setString(valueToName[e->getIndex()]);
1366 } else {
1367 output.setNumber(input.getRaw());
1368 }
1369 }
1370
1371 DynamicEnum decode(const JsonCodec& codec, JsonValue::Reader input) const override {
1372 if (input.isNumber()) {
1373 return DynamicEnum(schema, static_cast<uint16_t>(input.getNumber()));
1374 } else {
1375 uint16_t val = KJ_REQUIRE_NONNULL(nameToValue.find(input.getString()),
1376 "invalid enum value", input.getString());
1377 return DynamicEnum(schema.getEnumerants()[val]);
1378 }
1379 }
1380
1381 private:
1382 EnumSchema schema;
1383 kj::Array<kj::StringPtr> valueToName;
1384 kj::HashMap<kj::StringPtr, uint16_t> nameToValue;
1385 };
1386
1387 class JsonCodec::JsonValueHandler final: public JsonCodec::Handler<DynamicStruct> {
1388 public:
1389 void encode(const JsonCodec& codec, DynamicStruct::Reader input,
1390 JsonValue::Builder output) const override {
1391 #if _MSC_VER && !defined(__clang__)
1392 // TODO(msvc): Hack to work around missing AnyStruct::Builder constructor on MSVC.
1393 rawCopy(input, toDynamic(output));
1394 #else
1395 rawCopy(input, kj::mv(output));
1396 #endif
1397 }
1398
1399 void decode(const JsonCodec& codec, JsonValue::Reader input,
1400 DynamicStruct::Builder output) const override {
1401 rawCopy(input, kj::mv(output));
1402 }
1403
1404 private:
1405 void rawCopy(AnyStruct::Reader input, AnyStruct::Builder output) const {
1406 // HACK: Manually copy using AnyStruct, so that if JsonValue's definition changes, this code
1407 // doesn't need to be updated. However, note that if JsonValue ever adds new fields that
1408 // change its size, and the input struct is a newer version than the output, we may lose
1409 // the new fields. Technically the "correct" thing to do would be to allocate the output
1410 // struct to be exactly the same size as the input, but JsonCodec's Handler interface is
1411 // not designed to allow that -- it passes in an already-allocated builder. Oops.
1412 auto dataIn = input.getDataSection();
1413 auto dataOut = output.getDataSection();
1414 memcpy(dataOut.begin(), dataIn.begin(), kj::min(dataOut.size(), dataIn.size()));
1415
1416 auto ptrIn = input.getPointerSection();
1417 auto ptrOut = output.getPointerSection();
1418 for (auto i: kj::zeroTo(kj::min(ptrIn.size(), ptrOut.size()))) {
1419 ptrOut[i].set(ptrIn[i]);
1420 }
1421 }
1422 };
1423
1424 JsonCodec::AnnotatedHandler& JsonCodec::loadAnnotatedHandler(
1425 StructSchema schema, kj::Maybe<json::DiscriminatorOptions::Reader> discriminator,
1426 kj::Maybe<kj::StringPtr> unionDeclName, kj::Vector<Schema>& dependencies) {
1427 auto& entry = impl->annotatedHandlers.upsert(schema, nullptr,
1428 [&](kj::Maybe<kj::Own<AnnotatedHandler>>& existing, auto dummy) {
1429 KJ_ASSERT(existing != nullptr,
1430 "cyclic JSON flattening detected", schema.getProto().getDisplayName());
1431 });
1432
1433 KJ_IF_MAYBE(v, entry.value) {
1434 // Already exists.
1435 return **v;
1436 } else {
1437 // Not seen before.
1438 auto newHandler = kj::heap<AnnotatedHandler>(
1439 *this, schema, discriminator, unionDeclName, dependencies);
1440 auto& result = *newHandler;
1441
1442 // Map may have changed, so we have to look up again.
1443 KJ_ASSERT_NONNULL(impl->annotatedHandlers.find(schema)) = kj::mv(newHandler);
1444
1445 addTypeHandler(schema, result);
1446 return result;
1447 };
1448 }
1449
1450 void JsonCodec::handleByAnnotation(Schema schema) {
1451 switch (schema.getProto().which()) {
1452 case schema::Node::STRUCT: {
1453 if (schema.getProto().getId() == capnp::typeId<JsonValue>()) {
1454 // Special handler for JsonValue.
1455 static JsonValueHandler GLOBAL_HANDLER;
1456 addTypeHandler(schema.asStruct(), GLOBAL_HANDLER);
1457 } else {
1458 kj::Vector<Schema> dependencies;
1459 loadAnnotatedHandler(schema.asStruct(), nullptr, nullptr, dependencies);
1460 for (auto dep: dependencies) {
1461 handleByAnnotation(dep);
1462 }
1463 }
1464 break;
1465 }
1466 case schema::Node::ENUM: {
1467 auto enumSchema = schema.asEnum();
1468 impl->annotatedEnumHandlers.findOrCreate(enumSchema, [&]() {
1469 auto handler = kj::heap<AnnotatedEnumHandler>(enumSchema);
1470 addTypeHandler(enumSchema, *handler);
1471 return kj::HashMap<Type, kj::Own<AnnotatedEnumHandler>>::Entry {
1472 enumSchema, kj::mv(handler) };
1473 });
1474 break;
1475 }
1476 default:
1477 break;
1478 }
1479 }
1480
1481 } // namespace capnp