json.c++ 51 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "json.h"
23 24 25
#include <math.h>    // for HUGEVAL to check for overflow in strtod
#include <stdlib.h>  // strtod
#include <errno.h>   // for strtod errors
26
#include <capnp/orphan.h>
27
#include <kj/debug.h>
28 29
#include <kj/function.h>
#include <kj/vector.h>
30
#include <kj/one-of.h>
31
#include <kj/encoding.h>
32
#include <kj/map.h>
33 34 35 36 37

namespace capnp {

struct JsonCodec::Impl {
  bool prettyPrint = false;
38
  HasMode hasMode = HasMode::NON_NULL;
39
  size_t maxNestingDepth = 64;
40

41 42 43 44
  kj::HashMap<Type, HandlerBase*> typeHandlers;
  kj::HashMap<StructSchema::Field, HandlerBase*> fieldHandlers;
  kj::HashMap<Type, kj::Maybe<kj::Own<AnnotatedHandler>>> annotatedHandlers;
  kj::HashMap<Type, kj::Own<AnnotatedEnumHandler>> annotatedEnumHandlers;
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

  kj::StringTree encodeRaw(JsonValue::Reader value, uint indent, bool& multiline,
                           bool hasPrefix) const {
    switch (value.which()) {
      case JsonValue::NULL_:
        return kj::strTree("null");
      case JsonValue::BOOLEAN:
        return kj::strTree(value.getBoolean());
      case JsonValue::NUMBER:
        return kj::strTree(value.getNumber());

      case JsonValue::STRING:
        return kj::strTree(encodeString(value.getString()));

      case JsonValue::ARRAY: {
        auto array = value.getArray();
        uint subIndent = indent + (array.size() > 1);
        bool childMultiline = false;
        auto encodedElements = KJ_MAP(element, array) {
          return encodeRaw(element, subIndent, childMultiline, false);
        };

        return kj::strTree('[', encodeList(
            kj::mv(encodedElements), childMultiline, indent, multiline, hasPrefix), ']');
      }

      case JsonValue::OBJECT: {
        auto object = value.getObject();
        uint subIndent = indent + (object.size() > 1);
        bool childMultiline = false;
        kj::StringPtr colon = prettyPrint ? ": " : ":";
        auto encodedElements = KJ_MAP(field, object) {
          return kj::strTree(
              encodeString(field.getName()), colon,
              encodeRaw(field.getValue(), subIndent, childMultiline, true));
        };

        return kj::strTree('{', encodeList(
            kj::mv(encodedElements), childMultiline, indent, multiline, hasPrefix), '}');
      }

      case JsonValue::CALL: {
        auto call = value.getCall();
        auto params = call.getParams();
        uint subIndent = indent + (params.size() > 1);
        bool childMultiline = false;
        auto encodedElements = KJ_MAP(element, params) {
          return encodeRaw(element, subIndent, childMultiline, false);
        };

        return kj::strTree(call.getFunction(), '(', encodeList(
            kj::mv(encodedElements), childMultiline, indent, multiline, true), ')');
      }
    }

    KJ_FAIL_ASSERT("unknown JsonValue type", static_cast<uint>(value.which()));
  }

  kj::String encodeString(kj::StringPtr chars) const {
    static const char HEXDIGITS[] = "0123456789abcdef";
    kj::Vector<char> escaped(chars.size() + 3);

    escaped.add('"');
    for (char c: chars) {
      switch (c) {
        case '\"': escaped.addAll(kj::StringPtr("\\\"")); break;
        case '\\': escaped.addAll(kj::StringPtr("\\\\")); break;
        case '/' : escaped.addAll(kj::StringPtr("\\/" )); break;
        case '\b': escaped.addAll(kj::StringPtr("\\b")); break;
        case '\f': escaped.addAll(kj::StringPtr("\\f")); break;
        case '\n': escaped.addAll(kj::StringPtr("\\n")); break;
        case '\r': escaped.addAll(kj::StringPtr("\\r")); break;
        case '\t': escaped.addAll(kj::StringPtr("\\t")); break;
        default:
119
          if (static_cast<uint8_t>(c) < 0x20) {
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
            escaped.addAll(kj::StringPtr("\\u00"));
            uint8_t c2 = c;
            escaped.add(HEXDIGITS[c2 / 16]);
            escaped.add(HEXDIGITS[c2 % 16]);
          } else {
            escaped.add(c);
          }
          break;
      }
    }
    escaped.add('"');
    escaped.add('\0');

    return kj::String(escaped.releaseAsArray());
  }

  kj::StringTree encodeList(kj::Array<kj::StringTree> elements,
                            bool hasMultilineElement, uint indent, bool& multiline,
                            bool hasPrefix) const {
    size_t maxChildSize = 0;
    for (auto& e: elements) maxChildSize = kj::max(maxChildSize, e.size());

    kj::StringPtr prefix;
    kj::StringPtr delim;
    kj::StringPtr suffix;
    kj::String ownPrefix;
    kj::String ownDelim;
    if (!prettyPrint) {
      // No whitespace.
      delim = ",";
      prefix = "";
      suffix = "";
    } else if ((elements.size() > 1) && (hasMultilineElement || maxChildSize > 50)) {
      // If the array contained any multi-line elements, OR it contained sufficiently long
      // elements, then put each element on its own line.
      auto indentSpace = kj::repeat(' ', (indent + 1) * 2);
      delim = ownDelim = kj::str(",\n", indentSpace);
      multiline = true;
      if (hasPrefix) {
        // We're producing a multi-line list, and the first line has some garbage in front of it.
        // Therefore, move the first element to the next line.
        prefix = ownPrefix = kj::str("\n", indentSpace);
      } else {
        prefix = " ";
      }
      suffix = " ";
    } else {
      // Put everything on one line, but add spacing between elements for legibility.
      delim = ", ";
      prefix = "";
      suffix = "";
    }

    return kj::strTree(prefix, kj::StringTree(kj::mv(elements), delim), suffix);
  }
};

JsonCodec::JsonCodec()
    : impl(kj::heap<Impl>()) {}
JsonCodec::~JsonCodec() noexcept(false) {}

void JsonCodec::setPrettyPrint(bool enabled) { impl->prettyPrint = enabled; }

183 184 185 186
void JsonCodec::setMaxNestingDepth(size_t maxNestingDepth) {
  impl->maxNestingDepth = maxNestingDepth;
}

187 188
void JsonCodec::setHasMode(HasMode mode) { impl->hasMode = mode; }

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
kj::String JsonCodec::encode(DynamicValue::Reader value, Type type) const {
  MallocMessageBuilder message;
  auto json = message.getRoot<JsonValue>();
  encode(value, type, json);
  return encodeRaw(json);
}

void JsonCodec::decode(kj::ArrayPtr<const char> input, DynamicStruct::Builder output) const {
  MallocMessageBuilder message;
  auto json = message.getRoot<JsonValue>();
  decodeRaw(input, json);
  decode(json, output);
}

Orphan<DynamicValue> JsonCodec::decode(
    kj::ArrayPtr<const char> input, Type type, Orphanage orphanage) const {
  MallocMessageBuilder message;
  auto json = message.getRoot<JsonValue>();
  decodeRaw(input, json);
  return decode(json, type, orphanage);
}

kj::String JsonCodec::encodeRaw(JsonValue::Reader value) const {
  bool multiline = false;
  return impl->encodeRaw(value, 0, multiline, false).flatten();
}

void JsonCodec::encode(DynamicValue::Reader input, Type type, JsonValue::Builder output) const {
217 218
  // TODO(someday): For interfaces, check for handlers on superclasses, per documentation...
  // TODO(someday): For branded types, should we check for handlers on the generic?
219
  // TODO(someday): Allow registering handlers for "all structs", "all lists", etc?
220 221
  KJ_IF_MAYBE(handler, impl->typeHandlers.find(type)) {
    (*handler)->encodeBase(*this, input, output);
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    return;
  }

  switch (type.which()) {
    case schema::Type::VOID:
      output.setNull();
      break;
    case schema::Type::BOOL:
      output.setBoolean(input.as<bool>());
      break;
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
238 239
      output.setNumber(input.as<double>());
      break;
240 241
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
242 243
      {
        double value = input.as<double>();
244 245 246 247 248 249 250
        // Inf, -inf and NaN are not allowed in the JSON spec. Storing into string.
        if (kj::inf() == value) {
          output.setString("Infinity");
        } else if (-kj::inf() == value) {
          output.setString("-Infinity");
        } else if (kj::isNaN(value)) {
          output.setString("NaN");
251 252 253 254
        } else {
          output.setNumber(value);
        }
      }
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
      break;
    case schema::Type::INT64:
      output.setString(kj::str(input.as<int64_t>()));
      break;
    case schema::Type::UINT64:
      output.setString(kj::str(input.as<uint64_t>()));
      break;
    case schema::Type::TEXT:
      output.setString(kj::str(input.as<Text>()));
      break;
    case schema::Type::DATA: {
      // Turn into array of byte values. Yep, this is pretty ugly. People really need to override
      // this with a handler.
      auto bytes = input.as<Data>();
      auto array = output.initArray(bytes.size());
      for (auto i: kj::indices(bytes)) {
        array[i].setNumber(bytes[i]);
      }
      break;
    }
    case schema::Type::LIST: {
      auto list = input.as<DynamicList>();
      auto elementType = type.asList().getElementType();
      auto array = output.initArray(list.size());
      for (auto i: kj::indices(list)) {
        encode(list[i], elementType, array[i]);
      }
      break;
    }
    case schema::Type::ENUM: {
      auto e = input.as<DynamicEnum>();
      KJ_IF_MAYBE(symbol, e.getEnumerant()) {
        output.setString(symbol->getProto().getName());
      } else {
        output.setNumber(e.getRaw());
      }
      break;
    }
    case schema::Type::STRUCT: {
      auto structValue = input.as<capnp::DynamicStruct>();
      auto nonUnionFields = structValue.getSchema().getNonUnionFields();

      KJ_STACK_ARRAY(bool, hasField, nonUnionFields.size(), 32, 128);

      uint fieldCount = 0;
      for (auto i: kj::indices(nonUnionFields)) {
301
        fieldCount += (hasField[i] = structValue.has(nonUnionFields[i], impl->hasMode));
302 303 304 305 306 307 308 309 310
      }

      // We try to write the union field, if any, in proper order with the rest.
      auto which = structValue.which();
      bool unionFieldIsNull = false;

      KJ_IF_MAYBE(field, which) {
        // Even if the union field is null, if it is not the default field of the union then we
        // have to print it anyway.
311
        unionFieldIsNull = !structValue.has(*field, impl->hasMode);
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
        if (field->getProto().getDiscriminantValue() != 0 || !unionFieldIsNull) {
          ++fieldCount;
        } else {
          which = nullptr;
        }
      }

      auto object = output.initObject(fieldCount);

      size_t pos = 0;
      for (auto i: kj::indices(nonUnionFields)) {
        auto field = nonUnionFields[i];
        KJ_IF_MAYBE(unionField, which) {
          if (unionField->getIndex() < field.getIndex()) {
            auto outField = object[pos++];
            outField.setName(unionField->getProto().getName());
            if (unionFieldIsNull) {
              outField.initValue().setNull();
            } else {
              encodeField(*unionField, structValue.get(*unionField), outField.initValue());
            }
            which = nullptr;
          }
        }
        if (hasField[i]) {
          auto outField = object[pos++];
          outField.setName(field.getProto().getName());
          encodeField(field, structValue.get(field), outField.initValue());
        }
      }
      if (which != nullptr) {
        // Union field not printed yet; must be last.
        auto unionField = KJ_ASSERT_NONNULL(which);
        auto outField = object[pos++];
        outField.setName(unionField.getProto().getName());
        if (unionFieldIsNull) {
          outField.initValue().setNull();
        } else {
          encodeField(unionField, structValue.get(unionField), outField.initValue());
        }
      }
      KJ_ASSERT(pos == fieldCount);
      break;
    }
    case schema::Type::INTERFACE:
      KJ_FAIL_REQUIRE("don't know how to JSON-encode capabilities; "
                      "please register a JsonCodec::Handler for this");
    case schema::Type::ANY_POINTER:
      KJ_FAIL_REQUIRE("don't know how to JSON-encode AnyPointer; "
                      "please register a JsonCodec::Handler for this");
  }
}

void JsonCodec::encodeField(StructSchema::Field field, DynamicValue::Reader input,
                            JsonValue::Builder output) const {
367 368
  KJ_IF_MAYBE(handler, impl->fieldHandlers.find(field)) {
    (*handler)->encodeBase(*this, input, output);
369 370 371 372 373 374
    return;
  }

  encode(input, field.getType(), output);
}

375 376 377 378 379 380 381 382 383 384
Orphan<DynamicList> JsonCodec::decodeArray(List<JsonValue>::Reader input, ListSchema type, Orphanage orphanage) const {
  auto orphan = orphanage.newOrphan(type, input.size());
  auto output = orphan.get();
  for (auto i: kj::indices(input)) {
    output.adopt(i, decode(input[i], type.getElementType(), orphanage));
  }
  return orphan;
}

void JsonCodec::decodeObject(JsonValue::Reader input, StructSchema type, Orphanage orphanage, DynamicStruct::Builder output) const {
385
  KJ_REQUIRE(input.isObject(), "Expected object value") { return; }
386 387
  for (auto field: input.getObject()) {
    KJ_IF_MAYBE(fieldSchema, type.findFieldByName(field.getName())) {
388
      decodeField(*fieldSchema, field.getValue(), orphanage, output);
389 390 391 392 393 394
    } else {
      // Unknown json fields are ignored to allow schema evolution
    }
  }
}

395 396 397 398
void JsonCodec::decodeField(StructSchema::Field fieldSchema, JsonValue::Reader fieldValue,
                            Orphanage orphanage, DynamicStruct::Builder output) const {
  auto fieldType = fieldSchema.getType();

399 400
  KJ_IF_MAYBE(handler, impl->fieldHandlers.find(fieldSchema)) {
    output.adopt(fieldSchema, (*handler)->decodeBase(*this, fieldValue, fieldType, orphanage));
401 402 403 404 405
  } else {
    output.adopt(fieldSchema, decode(fieldValue, fieldType, orphanage));
  }
}

406 407 408
void JsonCodec::decode(JsonValue::Reader input, DynamicStruct::Builder output) const {
  auto type = output.getSchema();

409 410
  KJ_IF_MAYBE(handler, impl->typeHandlers.find(type)) {
    return (*handler)->decodeStructBase(*this, input, output);
411 412 413 414 415 416 417
  }

  decodeObject(input, type, Orphanage::getForMessageContaining(output), output);
}

Orphan<DynamicValue> JsonCodec::decode(
    JsonValue::Reader input, Type type, Orphanage orphanage) const {
418 419
  KJ_IF_MAYBE(handler, impl->typeHandlers.find(type)) {
    return (*handler)->decodeBase(*this, input, type, orphanage);
420
  }
421 422 423

  switch(type.which()) {
    case schema::Type::VOID:
424
      return capnp::VOID;
425
    case schema::Type::BOOL:
426
      switch (input.which()) {
427
        case JsonValue::BOOLEAN:
428
          return input.getBoolean();
429 430
        default:
          KJ_FAIL_REQUIRE("Expected boolean value");
431 432 433 434 435
      }
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
436
      // Relies on range check in DynamicValue::Reader::as<IntType>
437
      switch (input.which()) {
438
        case JsonValue::NUMBER:
439
          return input.getNumber();
440
        case JsonValue::STRING:
441
          return input.getString().parseAs<int64_t>();
442 443
        default:
          KJ_FAIL_REQUIRE("Expected integer value");
444 445 446 447 448
      }
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
449
      // Relies on range check in DynamicValue::Reader::as<IntType>
450
      switch (input.which()) {
451
        case JsonValue::NUMBER:
452
          return input.getNumber();
453
        case JsonValue::STRING:
454
          return input.getString().parseAs<uint64_t>();
455 456
        default:
          KJ_FAIL_REQUIRE("Expected integer value");
457
      }
458 459
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
460
      switch (input.which()) {
461
        case JsonValue::NULL_:
462
          return kj::nan();
463
        case JsonValue::NUMBER:
464
          return input.getNumber();
465
        case JsonValue::STRING:
466
          return input.getString().parseAs<double>();
467 468
        default:
          KJ_FAIL_REQUIRE("Expected float value");
469 470
      }
    case schema::Type::TEXT:
471
      switch (input.which()) {
472
        case JsonValue::STRING:
473
          return orphanage.newOrphanCopy(input.getString());
474 475
        default:
          KJ_FAIL_REQUIRE("Expected text value");
476 477
      }
    case schema::Type::DATA:
478
      switch (input.which()) {
479
        case JsonValue::ARRAY: {
480 481 482 483 484
          auto array = input.getArray();
          auto orphan = orphanage.newOrphan<Data>(array.size());
          auto data = orphan.get();
          for (auto i: kj::indices(array)) {
            auto x = array[i].getNumber();
485
            KJ_REQUIRE(byte(x) == x, "Number in byte array is not an integer in [0, 255]");
486
            data[i] = x;
487
          }
488
          return kj::mv(orphan);
489
        }
490 491
        default:
          KJ_FAIL_REQUIRE("Expected data value");
492
      }
493
    case schema::Type::LIST:
494
      switch (input.which()) {
495
        case JsonValue::ARRAY:
496
          return decodeArray(input.getArray(), type.asList(), orphanage);
497
        default:
498 499
          KJ_FAIL_REQUIRE("Expected list value") { break; }
          return orphanage.newOrphan(type.asList(), 0);
500 501
      }
    case schema::Type::ENUM:
502
      switch (input.which()) {
503
        case JsonValue::STRING:
504
          return DynamicEnum(type.asEnum().getEnumerantByName(input.getString()));
505
        default:
506 507
          KJ_FAIL_REQUIRE("Expected enum value") { break; }
          return DynamicEnum(type.asEnum(), 0);
508
      }
509 510 511 512
    case schema::Type::STRUCT: {
      auto structType = type.asStruct();
      auto orphan = orphanage.newOrphan(structType);
      decodeObject(input, structType, orphanage, orphan.get());
513
      return kj::mv(orphan);
514
    }
515
    case schema::Type::INTERFACE:
516
      KJ_FAIL_REQUIRE("don't know how to JSON-decode capabilities; "
517
                      "please register a JsonCodec::Handler for this");
518
    case schema::Type::ANY_POINTER:
519
      KJ_FAIL_REQUIRE("don't know how to JSON-decode AnyPointer; "
520
                      "please register a JsonCodec::Handler for this");
521
  }
522 523

  KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT;
524 525
}

526 527
// -----------------------------------------------------------------------------

528
namespace {
529

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
class Input {
public:
  Input(kj::ArrayPtr<const char> input) : wrapped(input) {}

  bool exhausted() {
    return wrapped.size() == 0 || wrapped.front() == '\0';
  }

  char nextChar() {
    KJ_REQUIRE(!exhausted(), "JSON message ends prematurely.");
    return wrapped.front();
  }

  void advance(size_t numBytes = 1) {
    KJ_REQUIRE(numBytes <= wrapped.size(), "JSON message ends prematurely.");
    wrapped = kj::arrayPtr(wrapped.begin() + numBytes, wrapped.end());
  }

  void advanceTo(const char *newPos) {
    KJ_REQUIRE(wrapped.begin() <= newPos && newPos < wrapped.end(),
        "JSON message ends prematurely.");
    wrapped = kj::arrayPtr(newPos, wrapped.end());
  }

  kj::ArrayPtr<const char> consume(size_t numBytes = 1) {
    auto originalPos = wrapped.begin();
    advance(numBytes);

    return kj::arrayPtr(originalPos, wrapped.begin());
  }

  void consume(char expected) {
    char current = nextChar();
    KJ_REQUIRE(current == expected, "Unexpected input in JSON message.");

    advance();
  }

  void consume(kj::ArrayPtr<const char> expected) {
    KJ_REQUIRE(wrapped.size() >= expected.size());

    auto prefix = wrapped.slice(0, expected.size());
    KJ_REQUIRE(prefix == expected, "Unexpected input in JSON message.");

    advance(expected.size());
  }

  bool tryConsume(char expected) {
    bool found = !exhausted() && nextChar() == expected;
    if (found) { advance(); }

    return found;
  }

  template <typename Predicate>
  void consumeOne(Predicate&& predicate) {
    char current = nextChar();
    KJ_REQUIRE(predicate(current), "Unexpected input in JSON message.");

    advance();
  }

  template <typename Predicate>
  kj::ArrayPtr<const char> consumeWhile(Predicate&& predicate) {
    auto originalPos = wrapped.begin();
    while (!exhausted() && predicate(nextChar())) { advance(); }

    return kj::arrayPtr(originalPos, wrapped.begin());
  }

  template <typename F>  // Function<void(Input&)>
  kj::ArrayPtr<const char> consumeCustom(F&& f) {
    // Allows consuming in a custom manner without exposing the wrapped ArrayPtr.
    auto originalPos = wrapped.begin();
    f(*this);

    return kj::arrayPtr(originalPos, wrapped.begin());
  }
608

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
  void consumeWhitespace() {
    consumeWhile([](char chr) {
      return (
        chr == ' '  ||
        chr == '\n' ||
        chr == '\r' ||
        chr == '\t'
      );
    });
  }


private:
  kj::ArrayPtr<const char> wrapped;

};  // class Input

626 627
class Parser {
public:
628
  Parser(size_t maxNestingDepth, kj::ArrayPtr<const char> input) :
629
    maxNestingDepth(maxNestingDepth), input(input), nestingDepth(0) {}
630

631
  void parseValue(JsonValue::Builder& output) {
632 633
    input.consumeWhitespace();
    KJ_DEFER(input.consumeWhitespace());
634

635
    KJ_REQUIRE(!input.exhausted(), "JSON message ends prematurely.");
636

637 638 639 640
    switch (input.nextChar()) {
      case 'n': input.consume(kj::StringPtr("null"));  output.setNull();         break;
      case 'f': input.consume(kj::StringPtr("false")); output.setBoolean(false); break;
      case 't': input.consume(kj::StringPtr("true"));  output.setBoolean(true);  break;
641 642 643
      case '"': parseString(output); break;
      case '[': parseArray(output);  break;
      case '{': parseObject(output); break;
644 645 646 647
      case '-': case '0': case '1': case '2': case '3':
      case '4': case '5': case '6': case '7': case '8':
      case '9': parseNumber(output); break;
      default: KJ_FAIL_REQUIRE("Unexpected input in JSON message.");
648 649 650
    }
  }

651
  void parseNumber(JsonValue::Builder& output) {
652
    output.setNumber(consumeNumber().parseAs<double>());
653 654
  }

655
  void parseString(JsonValue::Builder& output) {
656 657 658
    output.setString(consumeQuotedString());
  }

659
  void parseArray(JsonValue::Builder& output) {
660 661
    // TODO(perf): Using orphans leaves holes in the message. It's expected
    // that a JsonValue is used for interop, and won't be sent or written as a
662
    // Cap'n Proto message.  This also applies to parseObject below.
663 664
    kj::Vector<Orphan<JsonValue>> values;
    auto orphanage = Orphanage::getForMessageContaining(output);
665
    bool expectComma = false;
666

667
    input.consume('[');
668 669
    KJ_REQUIRE(++nestingDepth <= maxNestingDepth, "JSON message nested too deeply.");
    KJ_DEFER(--nestingDepth);
670

671
    while (input.consumeWhitespace(), input.nextChar() != ']') {
672 673 674
      auto orphan = orphanage.newOrphan<JsonValue>();
      auto builder = orphan.get();

675
      if (expectComma) {
676 677 678
        input.consumeWhitespace();
        input.consume(',');
        input.consumeWhitespace();
679
      }
680 681 682 683 684

      parseValue(builder);
      values.add(kj::mv(orphan));

      expectComma = true;
685 686 687 688 689
    }

    output.initArray(values.size());
    auto array = output.getArray();

690
    for (auto i : kj::indices(values)) {
691 692 693
      array.adoptWithCaveats(i, kj::mv(values[i]));
    }

694
    input.consume(']');
695 696
  }

697
  void parseObject(JsonValue::Builder& output) {
698 699
    kj::Vector<Orphan<JsonValue::Field>> fields;
    auto orphanage = Orphanage::getForMessageContaining(output);
700
    bool expectComma = false;
701

702
    input.consume('{');
703 704
    KJ_REQUIRE(++nestingDepth <= maxNestingDepth, "JSON message nested too deeply.");
    KJ_DEFER(--nestingDepth);
705

706
    while (input.consumeWhitespace(), input.nextChar() != '}') {
707 708 709
      auto orphan = orphanage.newOrphan<JsonValue::Field>();
      auto builder = orphan.get();

710
      if (expectComma) {
711 712 713
        input.consumeWhitespace();
        input.consume(',');
        input.consumeWhitespace();
714 715
      }

716 717
      builder.setName(consumeQuotedString());

718 719 720
      input.consumeWhitespace();
      input.consume(':');
      input.consumeWhitespace();
721 722 723 724 725 726

      auto valueBuilder = builder.getValue();
      parseValue(valueBuilder);

      fields.add(kj::mv(orphan));

727
      expectComma = true;
728 729 730 731 732
    }

    output.initObject(fields.size());
    auto object = output.getObject();

733
    for (auto i : kj::indices(fields)) {
734 735 736
      object.adoptWithCaveats(i, kj::mv(fields[i]));
    }

737
    input.consume('}');
738 739
  }

740
  bool inputExhausted() { return input.exhausted(); }
741

742
private:
743
  kj::String consumeQuotedString() {
744
    input.consume('"');
745 746 747 748 749
    // TODO(perf): Avoid copy / alloc if no escapes encoutered.
    // TODO(perf): Get statistics on string size and preallocate?
    kj::Vector<char> decoded;

    do {
750
      auto stringValue = input.consumeWhile([](const char chr) {
751 752 753 754 755
          return chr != '"' && chr != '\\';
      });

      decoded.addAll(stringValue);

756 757 758 759 760 761 762 763 764 765 766
      if (input.nextChar() == '\\') {  // handle escapes.
        input.advance();
        switch(input.nextChar()) {
          case '"' : decoded.add('"' ); input.advance(); break;
          case '\\': decoded.add('\\'); input.advance(); break;
          case '/' : decoded.add('/' ); input.advance(); break;
          case 'b' : decoded.add('\b'); input.advance(); break;
          case 'f' : decoded.add('\f'); input.advance(); break;
          case 'n' : decoded.add('\n'); input.advance(); break;
          case 'r' : decoded.add('\r'); input.advance(); break;
          case 't' : decoded.add('\t'); input.advance(); break;
767
          case 'u' :
768 769
            input.consume('u');
            unescapeAndAppend(input.consume(size_t(4)), decoded);
770
            break;
771
          default: KJ_FAIL_REQUIRE("Invalid escape in JSON string."); break;
772 773 774
        }
      }

775
    } while(input.nextChar() != '"');
776

777
    input.consume('"');
778 779 780 781 782 783
    decoded.add('\0');

    // TODO(perf): This copy can be eliminated, but I can't find the kj::wayToDoIt();
    return kj::String(decoded.releaseAsArray());
  }

784
  kj::String consumeNumber() {
785 786 787 788 789 790
    auto numArrayPtr = input.consumeCustom([](Input& input) {
      input.tryConsume('-');
      if (!input.tryConsume('0')) {
        input.consumeOne([](char c) { return '1' <= c && c <= '9'; });
        input.consumeWhile([](char c) { return '0' <= c && c <= '9'; });
      }
791

792 793 794
      if (input.tryConsume('.')) {
        input.consumeWhile([](char c) { return '0' <= c && c <= '9'; });
      }
795

796 797 798 799 800
      if (input.tryConsume('e') || input.tryConsume('E')) {
        input.tryConsume('+') || input.tryConsume('-');
        input.consumeWhile([](char c) { return '0' <= c && c <= '9'; });
      }
    });
801

802
    KJ_REQUIRE(numArrayPtr.size() > 0, "Expected number in JSON input.");
803 804

    kj::Vector<char> number;
805
    number.addAll(numArrayPtr);
806 807 808 809 810
    number.add('\0');

    return kj::String(number.releaseAsArray());
  }

811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
  // TODO(someday): This "interface" is ugly, and won't work if/when surrogates are handled.
  void unescapeAndAppend(kj::ArrayPtr<const char> hex, kj::Vector<char>& target) {
    KJ_REQUIRE(hex.size() == 4);
    int codePoint = 0;

    for (int i = 0; i < 4; ++i) {
      char c = hex[i];
      codePoint <<= 4;

      if ('0' <= c && c <= '9') {
        codePoint |= c - '0';
      } else if ('a' <= c && c <= 'f') {
        codePoint |= c - 'a';
      } else if ('A' <= c && c <= 'F') {
        codePoint |= c - 'A';
      } else {
827
        KJ_FAIL_REQUIRE("Invalid hex digit in unicode escape.", c);
828 829 830
      }
    }

831 832 833 834 835 836 837
    if (codePoint < 128) {
      target.add(0x7f & static_cast<char>(codePoint));
    } else {
      // TODO(perf): This is sorta malloc-heavy...
      char16_t u = codePoint;
      target.addAll(kj::decodeUtf16(kj::arrayPtr(&u, 1)));
    }
838 839
  }

840
  const size_t maxNestingDepth;
841
  Input input;
842
  size_t nestingDepth;
843

844

845 846
};  // class Parser

847 848
}  // namespace

849

850
void JsonCodec::decodeRaw(kj::ArrayPtr<const char> input, JsonValue::Builder output) const {
851
  Parser parser(impl->maxNestingDepth, input);
852
  parser.parseValue(output);
853 854

  KJ_REQUIRE(parser.inputExhausted(), "Input remains after parsing JSON.");
855 856 857 858
}

// -----------------------------------------------------------------------------

859
Orphan<DynamicValue> JsonCodec::HandlerBase::decodeBase(
860
    const JsonCodec& codec, JsonValue::Reader input, Type type, Orphanage orphanage) const {
861 862 863 864 865 866 867 868
  KJ_FAIL_ASSERT("JSON decoder handler type / value type mismatch");
}
void JsonCodec::HandlerBase::decodeStructBase(
    const JsonCodec& codec, JsonValue::Reader input, DynamicStruct::Builder output) const {
  KJ_FAIL_ASSERT("JSON decoder handler type / value type mismatch");
}

void JsonCodec::addTypeHandlerImpl(Type type, HandlerBase& handler) {
869 870 871
  impl->typeHandlers.upsert(type, &handler, [](HandlerBase*& existing, HandlerBase* replacement) {
    KJ_REQUIRE(existing == replacement, "type already has a different registered handler");
  });
872 873 874 875 876
}

void JsonCodec::addFieldHandlerImpl(StructSchema::Field field, Type type, HandlerBase& handler) {
  KJ_REQUIRE(type == field.getType(),
      "handler type did not match field type for addFieldHandler()");
877 878 879
  impl->fieldHandlers.upsert(field, &handler, [](HandlerBase*& existing, HandlerBase* replacement) {
    KJ_REQUIRE(existing == replacement, "field already has a different registered handler");
  });
880 881
}

882 883 884 885 886
// =======================================================================================

static constexpr uint64_t JSON_NAME_ANNOTATION_ID = 0xfa5b1fd61c2e7c3dull;
static constexpr uint64_t JSON_FLATTEN_ANNOTATION_ID = 0x82d3e852af0336bfull;
static constexpr uint64_t JSON_DISCRIMINATOR_ANNOTATION_ID = 0xcfa794e8d19a0162ull;
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
static constexpr uint64_t JSON_BASE64_ANNOTATION_ID = 0xd7d879450a253e4bull;
static constexpr uint64_t JSON_HEX_ANNOTATION_ID = 0xf061e22f0ae5c7b5ull;

class JsonCodec::Base64Handler final: public JsonCodec::Handler<capnp::Data> {
public:
  void encode(const JsonCodec& codec, capnp::Data::Reader input, JsonValue::Builder output) const {
    output.setString(kj::encodeBase64(input));
  }

  Orphan<capnp::Data> decode(const JsonCodec& codec, JsonValue::Reader input,
                             Orphanage orphanage) const {
    return orphanage.newOrphanCopy(capnp::Data::Reader(kj::decodeBase64(input.getString())));
  }
};

class JsonCodec::HexHandler final: public JsonCodec::Handler<capnp::Data> {
public:
  void encode(const JsonCodec& codec, capnp::Data::Reader input, JsonValue::Builder output) const {
    output.setString(kj::encodeHex(input));
  }

  Orphan<capnp::Data> decode(const JsonCodec& codec, JsonValue::Reader input,
                             Orphanage orphanage) const {
    return orphanage.newOrphanCopy(capnp::Data::Reader(kj::decodeHex(input.getString())));
  }
};
913 914 915

class JsonCodec::AnnotatedHandler final: public JsonCodec::Handler<DynamicStruct> {
public:
916 917 918
  AnnotatedHandler(JsonCodec& codec, StructSchema schema,
                   kj::Maybe<json::DiscriminatorOptions::Reader> discriminator,
                   kj::Maybe<kj::StringPtr> unionDeclName,
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
                   kj::Vector<Schema>& dependencies)
      : schema(schema) {
    auto schemaProto = schema.getProto();
    auto typeName = schemaProto.getDisplayName();

    if (discriminator == nullptr) {
      // There are two cases of unions:
      // * Named unions, which are special cases of named groups. In this case, the union may be
      //   annotated by annotating the field. In this case, we receive a non-null `discriminator`
      //   as a constructor parameter, and schemaProto.getAnnotations() must be empty because
      //   it's not possible to annotate a group's type (becaues the type is anonymous).
      // * Unnamed unions, of which there can only be one in any particular scope. In this case,
      //   the parent struct type itself is annotated.
      // So if we received `null` as the constructor parameter, check for annotations on the struct
      // type.
      for (auto anno: schemaProto.getAnnotations()) {
        switch (anno.getId()) {
          case JSON_DISCRIMINATOR_ANNOTATION_ID:
937
            discriminator = anno.getValue().getStruct().getAs<json::DiscriminatorOptions>();
938 939 940 941 942 943
            break;
        }
      }
    }

    KJ_IF_MAYBE(d, discriminator) {
944 945 946 947 948 949
      if (d->hasName()) {
        unionTagName = d->getName();
      } else {
        unionTagName = unionDeclName;
      }
      KJ_IF_MAYBE(u, unionTagName) {
950
        fieldsByName.insert(*u, FieldNameInfo {
951
          FieldNameInfo::UNION_TAG, 0, 0, nullptr
952
        });
953 954 955
      }

      if (d->hasValueName()) {
956
        fieldsByName.insert(d->getValueName(), FieldNameInfo {
957
          FieldNameInfo::UNION_VALUE, 0, 0, nullptr
958
        });
959
      }
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    }

    discriminantOffset = schemaProto.getStruct().getDiscriminantOffset();

    fields = KJ_MAP(field, schema.getFields()) {
      auto fieldProto = field.getProto();
      auto type = field.getType();
      auto fieldName = fieldProto.getName();

      FieldNameInfo nameInfo;
      nameInfo.index = field.getIndex();
      nameInfo.type = FieldNameInfo::NORMAL;
      nameInfo.prefixLength = 0;

      FieldInfo info;
      info.name = fieldName;

977
      kj::Maybe<json::DiscriminatorOptions::Reader> subDiscriminator;
978 979 980 981 982 983 984 985 986
      bool flattened = false;
      for (auto anno: field.getProto().getAnnotations()) {
        switch (anno.getId()) {
          case JSON_NAME_ANNOTATION_ID:
            info.name = anno.getValue().getText();
            break;
          case JSON_FLATTEN_ANNOTATION_ID:
            KJ_REQUIRE(type.isStruct(), "only struct types can be flattened", fieldName, typeName);
            flattened = true;
987
            info.prefix = anno.getValue().getStruct().getAs<json::FlattenOptions>().getPrefix();
988 989 990
            break;
          case JSON_DISCRIMINATOR_ANNOTATION_ID:
            KJ_REQUIRE(fieldProto.isGroup(), "only unions can have discriminator");
991
            subDiscriminator = anno.getValue().getStruct().getAs<json::DiscriminatorOptions>();
992
            break;
993 994 995 996 997 998 999 1000 1001 1002 1003 1004
          case JSON_BASE64_ANNOTATION_ID: {
            KJ_REQUIRE(field.getType().isData(), "only Data can be marked for base64 encoding");
            static Base64Handler handler;
            codec.addFieldHandler(field, handler);
            break;
          }
          case JSON_HEX_ANNOTATION_ID: {
            KJ_REQUIRE(field.getType().isData(), "only Data can be marked for hex encoding");
            static HexHandler handler;
            codec.addFieldHandler(field, handler);
            break;
          }
1005 1006 1007
        }
      }

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
      if (fieldProto.isGroup()) {
        // Load group type handler now, even if not flattened, so that we can pass its
        // `subDiscriminator`.
        kj::Maybe<kj::StringPtr> subFieldName;
        if (flattened) {
          // If the group was flattened, then we allow its field name to be used as the
          // discriminator name, so that the discriminator doesn't have to explicitly specify a
          // name.
          subFieldName = fieldName;
        }
        auto& subHandler = codec.loadAnnotatedHandler(
            type.asStruct(), subDiscriminator, subFieldName, dependencies);
        if (flattened) {
          info.flattenHandler = subHandler;
        }
1023 1024 1025 1026 1027
      } else if (type.isStruct()) {
        if (flattened) {
          info.flattenHandler = codec.loadAnnotatedHandler(
              type.asStruct(), nullptr, nullptr, dependencies);
        }
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
      }

      bool isUnionMember = fieldProto.getDiscriminantValue() != schema::Field::NO_DISCRIMINANT;

      KJ_IF_MAYBE(fh, info.flattenHandler) {
        // Set up fieldsByName for each of the child's fields.
        for (auto& entry: fh->fieldsByName) {
          kj::StringPtr flattenedName;
          kj::String ownName;
          if (info.prefix.size() > 0) {
1038
            ownName = kj::str(info.prefix, entry.key);
1039 1040
            flattenedName = ownName;
          } else {
1041
            flattenedName = entry.key;
1042
          }
1043

1044
          fieldsByName.upsert(flattenedName, FieldNameInfo {
1045 1046
            isUnionMember ? FieldNameInfo::FLATTENED_FROM_UNION : FieldNameInfo::FLATTENED,
            field.getIndex(), (uint)info.prefix.size(), kj::mv(ownName)
1047 1048 1049 1050 1051
          }, [&](FieldNameInfo& existing, FieldNameInfo&& replacement) {
            KJ_REQUIRE(existing.type == FieldNameInfo::FLATTENED_FROM_UNION &&
                       replacement.type == FieldNameInfo::FLATTENED_FROM_UNION,
                "flattened members have the same name and are not mutually exclusive");
          });
1052 1053 1054
        }
      }

1055 1056
      info.nameForDiscriminant = info.name;

1057
      if (!flattened) {
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        bool isUnionWithValueName = false;
        if (isUnionMember) {
          KJ_IF_MAYBE(d, discriminator) {
            if (d->hasValueName()) {
              info.name = d->getValueName();
              isUnionWithValueName = true;
            }
          }
        }

        if (!isUnionWithValueName) {
1069
          fieldsByName.insert(info.name, kj::mv(nameInfo));
1070
        }
1071 1072 1073
      }

      if (isUnionMember) {
1074
        unionTagValues.insert(info.nameForDiscriminant, field);
1075 1076 1077 1078
      }

      // Look for dependencies that we need to add.
      while (type.isList()) type = type.asList().getElementType();
1079
      if (codec.impl->typeHandlers.find(type) == nullptr) {
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
        switch (type.which()) {
          case schema::Type::STRUCT:
            dependencies.add(type.asStruct());
            break;
          case schema::Type::ENUM:
            dependencies.add(type.asEnum());
            break;
          case schema::Type::INTERFACE:
            dependencies.add(type.asInterface());
            break;
          default:
            break;
        }
      }

      return info;
    };
  }

  const StructSchema schema;

  void encode(const JsonCodec& codec, DynamicStruct::Reader input,
              JsonValue::Builder output) const override {
    kj::Vector<FlattenedField> flattenedFields;
    gatherForEncode(codec, input, nullptr, nullptr, flattenedFields);

    auto outs = output.initObject(flattenedFields.size());
    for (auto i: kj::indices(flattenedFields)) {
      auto& in = flattenedFields[i];
      auto out = outs[i];
      out.setName(in.name);
1111 1112 1113 1114 1115 1116 1117 1118
      KJ_SWITCH_ONEOF(in.type) {
        KJ_CASE_ONEOF(type, Type) {
          codec.encode(in.value, type, out.initValue());
        }
        KJ_CASE_ONEOF(field, StructSchema::Field) {
          codec.encodeField(field, in.value, out.initValue());
        }
      }
1119 1120 1121 1122 1123 1124
    }
  }

  void decode(const JsonCodec& codec, JsonValue::Reader input,
              DynamicStruct::Builder output) const override {
    KJ_REQUIRE(input.isObject());
1125
    kj::HashSet<const void*> unionsSeen;
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    kj::Vector<JsonValue::Field::Reader> retries;
    for (auto field: input.getObject()) {
      if (!decodeField(codec, field.getName(), field.getValue(), output, unionsSeen)) {
        retries.add(field);
      }
    }
    while (!retries.empty()) {
      auto retriesCopy = kj::mv(retries);
      KJ_ASSERT(retries.empty());
      for (auto field: retriesCopy) {
        if (!decodeField(codec, field.getName(), field.getValue(), output, unionsSeen)) {
          retries.add(field);
        }
      }
      if (retries.size() == retriesCopy.size()) {
        // We made no progress in this iteration. Give up on the remaining fields.
        break;
      }
    }
  }

private:
  struct FieldInfo {
    kj::StringPtr name;
1150
    kj::StringPtr nameForDiscriminant;
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    kj::Maybe<const AnnotatedHandler&> flattenHandler;
    kj::StringPtr prefix;
  };

  kj::Array<FieldInfo> fields;
  // Maps field index -> info about the field

  struct FieldNameInfo {
    enum {
      NORMAL,
      // This is a normal field with the given `index`.

      FLATTENED,
      // This is a field of a flattened inner struct or group (that is not in a union). `index`
      // is the field index of the particular struct/group field.

      UNION_TAG,
      // The parent struct is a flattened union, and this field is the discriminant tag. It is a
      // string field whose name determines the union type. `index` is not used.

1171
      FLATTENED_FROM_UNION,
1172 1173 1174 1175 1176
      // The parent struct is a flattened union, and some of the union's members are flattened
      // structs or groups, and this field is possibly a member of one or more of them. `index`
      // is not used, because it's possible that the same field name appears in multiple variants.
      // Intsead, the parser must find the union tag, and then can descend and attempt to parse
      // the field in the context of whichever variant is selected.
1177 1178 1179

      UNION_VALUE
      // This field is the value of a discriminated union that has `valueName` set.
1180 1181 1182 1183 1184 1185 1186 1187 1188
    } type;

    uint index;
    // For `NORMAL` and `FLATTENED`, the index of the field in schema.getFields().

    uint prefixLength;
    kj::String ownName;
  };

1189
  kj::HashMap<kj::StringPtr, FieldNameInfo> fieldsByName;
1190 1191
  // Maps JSON names to info needed to parse them.

1192
  kj::HashMap<kj::StringPtr, StructSchema::Field> unionTagValues;
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
  // If the parent struct is a flattened union, it has a tag field which is a string with one of
  // these values. The map maps to the union member to set.

  kj::Maybe<kj::StringPtr> unionTagName;
  // If the parent struct is a flattened union, the name of the "tag" field.

  uint discriminantOffset;
  // Shortcut for schema.getProto().getStruct().getDiscriminantOffset(), used in a hack to identify
  // which unions have been seen.

  struct FlattenedField {
    kj::String ownName;
    kj::StringPtr name;
1206
    kj::OneOf<StructSchema::Field, Type> type;
1207 1208
    DynamicValue::Reader value;

1209 1210
    FlattenedField(kj::StringPtr prefix, kj::StringPtr name,
                   kj::OneOf<StructSchema::Field, Type> type, DynamicValue::Reader value)
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
        : ownName(prefix.size() > 0 ? kj::str(prefix, name) : nullptr),
          name(prefix.size() > 0 ? ownName : name),
          type(type), value(value) {}
  };

  void gatherForEncode(const JsonCodec& codec, DynamicValue::Reader input,
                       kj::StringPtr prefix, kj::StringPtr morePrefix,
                       kj::Vector<FlattenedField>& flattenedFields) const {
    kj::String ownPrefix;
    if (morePrefix.size() > 0) {
      if (prefix.size() > 0) {
        ownPrefix = kj::str(prefix, morePrefix);
        prefix = ownPrefix;
      } else {
        prefix = morePrefix;
      }
    }

    auto reader = input.as<DynamicStruct>();
    auto schema = reader.getSchema();
    for (auto field: schema.getNonUnionFields()) {
      auto& info = fields[field.getIndex()];
      if (!reader.has(field, codec.impl->hasMode)) {
        // skip
      } else KJ_IF_MAYBE(handler, info.flattenHandler) {
        handler->gatherForEncode(codec, reader.get(field), prefix, info.prefix, flattenedFields);
      } else {
        flattenedFields.add(FlattenedField {
1239
            prefix, info.name, field, reader.get(field) });
1240 1241 1242 1243 1244 1245 1246
      }
    }

    KJ_IF_MAYBE(which, reader.which()) {
      auto& info = fields[which->getIndex()];
      KJ_IF_MAYBE(tag, unionTagName) {
        flattenedFields.add(FlattenedField {
1247
            prefix, *tag, Type(schema::Type::TEXT), Text::Reader(info.nameForDiscriminant) });
1248 1249 1250 1251 1252
      }

      KJ_IF_MAYBE(handler, info.flattenHandler) {
        handler->gatherForEncode(codec, reader.get(*which), prefix, info.prefix, flattenedFields);
      } else {
1253 1254 1255 1256 1257
        auto type = which->getType();
        if (type.which() == schema::Type::VOID && unionTagName != nullptr) {
          // When we have an explicit union discriminant, we don't need to encode void fields.
        } else {
          flattenedFields.add(FlattenedField {
1258
              prefix, info.name, *which, reader.get(*which) });
1259
        }
1260 1261 1262 1263 1264
      }
    }
  }

  bool decodeField(const JsonCodec& codec, kj::StringPtr name, JsonValue::Reader value,
1265
                   DynamicStruct::Builder output, kj::HashSet<const void*>& unionsSeen) const {
Kenton Varda's avatar
Kenton Varda committed
1266 1267
    KJ_ASSERT(output.getSchema() == schema);

1268 1269 1270 1271 1272 1273
    KJ_IF_MAYBE(info, fieldsByName.find(name)) {
      switch (info->type) {
        case FieldNameInfo::NORMAL: {
          auto field = output.getSchema().getFields()[info->index];
          codec.decodeField(field, value, Orphanage::getForMessageContaining(output), output);
          return true;
1274
        }
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
        case FieldNameInfo::FLATTENED:
          return KJ_ASSERT_NONNULL(fields[info->index].flattenHandler)
              .decodeField(codec, name.slice(info->prefixLength), value,
                  output.get(output.getSchema().getFields()[info->index]).as<DynamicStruct>(),
                  unionsSeen);
        case FieldNameInfo::UNION_TAG: {
          KJ_REQUIRE(value.isString(), "Expected string value.");

          // Mark that we've seen a union tag for this struct.
          const void* ptr = getUnionInstanceIdentifier(output);
          KJ_IF_MAYBE(field, unionTagValues.find(value.getString())) {
1286 1287 1288 1289
            // clear() has the side-effect of activating this member of the union, without
            // allocating any objects.
            output.clear(*field);
            unionsSeen.insert(ptr);
1290
          }
1291
          return true;
1292 1293 1294
        }
        case FieldNameInfo::FLATTENED_FROM_UNION: {
          const void* ptr = getUnionInstanceIdentifier(output);
1295 1296 1297
          if (unionsSeen.contains(ptr)) {
            auto variant = KJ_ASSERT_NONNULL(output.which());
            return KJ_ASSERT_NONNULL(fields[variant.getIndex()].flattenHandler)
1298
                .decodeField(codec, name.slice(info->prefixLength), value,
1299
                    output.get(variant).as<DynamicStruct>(), unionsSeen);
1300 1301 1302 1303 1304 1305 1306
          } else {
            // We haven't seen the union tag yet, so we can't parse this field yet. Try again later.
            return false;
          }
        }
        case FieldNameInfo::UNION_VALUE: {
          const void* ptr = getUnionInstanceIdentifier(output);
1307 1308 1309
          if (unionsSeen.contains(ptr)) {
            auto variant = KJ_ASSERT_NONNULL(output.which());
            codec.decodeField(variant, value, Orphanage::getForMessageContaining(output), output);
1310 1311 1312 1313 1314
            return true;
          } else {
            // We haven't seen the union tag yet, so we can't parse this field yet. Try again later.
            return false;
          }
1315 1316
        }
      }
1317

1318 1319 1320 1321 1322
      KJ_UNREACHABLE;
    } else {
      // Ignore undefined field.
      return true;
    }
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
  }

  const void* getUnionInstanceIdentifier(DynamicStruct::Builder obj) const {
    // Gets a value uniquely identifying an instance of a union.
    // HACK: We return a poniter to the union's discriminant within the underlying buffer.
    return reinterpret_cast<const uint16_t*>(
        AnyStruct::Reader(obj.asReader()).getDataSection().begin()) + discriminantOffset;
  }
};

class JsonCodec::AnnotatedEnumHandler final: public JsonCodec::Handler<DynamicEnum> {
public:
  AnnotatedEnumHandler(EnumSchema schema): schema(schema) {
    auto enumerants = schema.getEnumerants();
    auto builder = kj::heapArrayBuilder<kj::StringPtr>(enumerants.size());

    for (auto e: enumerants) {
      auto proto = e.getProto();
      kj::StringPtr name = proto.getName();

      for (auto anno: proto.getAnnotations()) {
        switch (anno.getId()) {
          case JSON_NAME_ANNOTATION_ID:
            name = anno.getValue().getText();
            break;
        }
      }

      builder.add(name);
1352
      nameToValue.insert(name, e.getIndex());
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    }

    valueToName = builder.finish();
  }

  void encode(const JsonCodec& codec, DynamicEnum input, JsonValue::Builder output) const override {
    KJ_IF_MAYBE(e, input.getEnumerant()) {
      KJ_ASSERT(e->getIndex() < valueToName.size());
      output.setString(valueToName[e->getIndex()]);
    } else {
      output.setNumber(input.getRaw());
    }
  }

  DynamicEnum decode(const JsonCodec& codec, JsonValue::Reader input) const override {
    if (input.isNumber()) {
      return DynamicEnum(schema, static_cast<uint16_t>(input.getNumber()));
    } else {
1371 1372 1373
      uint16_t val = KJ_REQUIRE_NONNULL(nameToValue.find(input.getString()),
          "invalid enum value", input.getString());
      return DynamicEnum(schema.getEnumerants()[val]);
1374 1375 1376 1377 1378 1379
    }
  }

private:
  EnumSchema schema;
  kj::Array<kj::StringPtr> valueToName;
1380
  kj::HashMap<kj::StringPtr, uint16_t> nameToValue;
1381 1382
};

1383 1384 1385 1386
class JsonCodec::JsonValueHandler final: public JsonCodec::Handler<DynamicStruct> {
public:
  void encode(const JsonCodec& codec, DynamicStruct::Reader input,
              JsonValue::Builder output) const override {
Kenton Varda's avatar
Kenton Varda committed
1387 1388 1389 1390
#if _MSC_VER
    // TODO(msvc): Hack to work around missing AnyStruct::Builder constructor on MSVC.
    rawCopy(input, toDynamic(output));
#else
1391
    rawCopy(input, kj::mv(output));
Kenton Varda's avatar
Kenton Varda committed
1392
#endif
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
  }

  void decode(const JsonCodec& codec, JsonValue::Reader input,
              DynamicStruct::Builder output) const override {
    rawCopy(input, kj::mv(output));
  }

private:
  void rawCopy(AnyStruct::Reader input, AnyStruct::Builder output) const {
    // HACK: Manually copy using AnyStruct, so that if JsonValue's definition changes, this code
    //   doesn't need to be updated. However, note that if JsonValue ever adds new fields that
    //   change its size, and the input struct is a newer version than the output, we may lose
    //   the new fields. Technically the "correct" thing to do would be to allocate the output
    //   struct to be exactly the same size as the input, but JsonCodec's Handler interface is
    //   not designed to allow that -- it passes in an already-allocated builder. Oops.
    auto dataIn = input.getDataSection();
    auto dataOut = output.getDataSection();
    memcpy(dataOut.begin(), dataIn.begin(), kj::min(dataOut.size(), dataIn.size()));

    auto ptrIn = input.getPointerSection();
    auto ptrOut = output.getPointerSection();
    for (auto i: kj::zeroTo(kj::min(ptrIn.size(), ptrOut.size()))) {
      ptrOut[i].set(ptrIn[i]);
    }
  }
};

1420
JsonCodec::AnnotatedHandler& JsonCodec::loadAnnotatedHandler(
1421 1422
      StructSchema schema, kj::Maybe<json::DiscriminatorOptions::Reader> discriminator,
      kj::Maybe<kj::StringPtr> unionDeclName, kj::Vector<Schema>& dependencies) {
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
  auto& entry = impl->annotatedHandlers.upsert(schema, nullptr,
      [&](kj::Maybe<kj::Own<AnnotatedHandler>>& existing, auto dummy) {
    KJ_ASSERT(existing != nullptr,
        "cyclic JSON flattening detected", schema.getProto().getDisplayName());
  });

  KJ_IF_MAYBE(v, entry.value) {
    // Already exists.
    return **v;
  } else {
1433
    // Not seen before.
1434 1435
    auto newHandler = kj::heap<AnnotatedHandler>(
          *this, schema, discriminator, unionDeclName, dependencies);
1436
    auto& result = *newHandler;
1437 1438 1439 1440

    // Map may have changed, so we have to look up again.
    KJ_ASSERT_NONNULL(impl->annotatedHandlers.find(schema)) = kj::mv(newHandler);

1441 1442
    addTypeHandler(schema, result);
    return result;
1443
  };
1444 1445 1446 1447 1448
}

void JsonCodec::handleByAnnotation(Schema schema) {
  switch (schema.getProto().which()) {
    case schema::Node::STRUCT: {
1449 1450 1451 1452 1453 1454
      if (schema.getProto().getId() == capnp::typeId<JsonValue>()) {
        // Special handler for JsonValue.
        static JsonValueHandler GLOBAL_HANDLER;
        addTypeHandler(schema.asStruct(), GLOBAL_HANDLER);
      } else {
        kj::Vector<Schema> dependencies;
1455
        loadAnnotatedHandler(schema.asStruct(), nullptr, nullptr, dependencies);
1456 1457 1458
        for (auto dep: dependencies) {
          handleByAnnotation(dep);
        }
1459 1460 1461 1462 1463
      }
      break;
    }
    case schema::Node::ENUM: {
      auto enumSchema = schema.asEnum();
1464 1465 1466 1467 1468 1469
      impl->annotatedEnumHandlers.findOrCreate(enumSchema, [&]() {
        auto handler = kj::heap<AnnotatedEnumHandler>(enumSchema);
        addTypeHandler(enumSchema, *handler);
        return kj::HashMap<Type, kj::Own<AnnotatedEnumHandler>>::Entry {
            enumSchema, kj::mv(handler) };
      });
1470 1471 1472 1473 1474 1475 1476
      break;
    }
    default:
      break;
  }
}

1477
} // namespace capnp