stringify.c++ 10.4 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 23
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Kenton Varda's avatar
Kenton Varda committed
24
#include "dynamic.h"
Kenton Varda's avatar
Kenton Varda committed
25
#include <kj/debug.h>
26
#include <kj/vector.h>
27

28
namespace capnp {
29 30 31 32 33

namespace {

static const char HEXDIGITS[] = "0123456789abcdef";

34 35 36 37 38 39 40 41 42 43 44 45
enum PrintMode {
  BARE,
  // The value is planned to be printed on its own line, unless it is very short and contains
  // no inner newlines.

  PREFIXED,
  // The value is planned to be printed with a prefix, like "memberName = " (a struct field).

  PARENTHESIZED
  // The value is printed in parenthesized (a union value).
};

46 47 48 49 50
enum class PrintKind {
  LIST,
  RECORD
};

51 52
class Indent {
public:
53
  explicit Indent(bool enable): amount(enable ? 1 : 0) {}
54

55 56
  Indent next() {
    return Indent(amount == 0 ? 0 : amount + 1);
57 58
  }

59 60
  kj::StringTree delimit(kj::Array<kj::StringTree> items, PrintMode mode, PrintKind kind) {
    if (amount == 0 || canPrintAllInline(items, kind)) {
61 62 63 64 65 66 67 68 69 70 71 72 73 74
      return kj::StringTree(kj::mv(items), ", ");
    } else {
      char delim[amount * 2 + 3];
      delim[0] = ',';
      delim[1] = '\n';
      memset(delim + 2, ' ', amount * 2);
      delim[amount * 2 + 2] = '\0';

      // If the outer value isn't being printed on its own line, we need to add a newline/indent
      // before the first item, otherwise we only add a space on the assumption that it is preceded
      // by an open bracket or parenthesis.
      return kj::strTree(mode == BARE ? " " : delim + 1,
          kj::StringTree(kj::mv(items), kj::StringPtr(delim, amount * 2 + 2)), ' ');
    }
75 76 77 78
  }

private:
  uint amount;
79 80 81 82

  explicit Indent(uint amount): amount(amount) {}

  static constexpr size_t maxInlineValueSize = 24;
83
  static constexpr size_t maxInlineRecordSize = 64;
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

  static bool canPrintInline(const kj::StringTree& text) {
    if (text.size() > maxInlineValueSize) {
      return false;
    }

    char flat[maxInlineValueSize + 1];
    text.flattenTo(flat);
    flat[text.size()] = '\0';
    if (strchr(flat, '\n') != nullptr) {
      return false;
    }

    return true;
  }

100 101
  static bool canPrintAllInline(const kj::Array<kj::StringTree>& items, PrintKind kind) {
    size_t totalSize = 0;
102 103
    for (auto& item: items) {
      if (!canPrintInline(item)) return false;
104 105 106 107
      if (kind == PrintKind::RECORD) {
        totalSize += item.size();
        if (totalSize > maxInlineRecordSize) return false;
      }
108 109 110
    }
    return true;
  }
111 112
};

Kenton Varda's avatar
Kenton Varda committed
113
static schema::Type::Which whichFieldType(const StructSchema::Field& field) {
Kenton Varda's avatar
Kenton Varda committed
114 115
  auto proto = field.getProto();
  switch (proto.which()) {
116 117
    case schema::Field::SLOT:
      return proto.getSlot().getType().which();
Kenton Varda's avatar
Kenton Varda committed
118 119
    case schema::Field::GROUP:
      return schema::Type::STRUCT;
120 121 122
  }
  KJ_UNREACHABLE;
}
123

124
static kj::StringTree print(const DynamicValue::Reader& value,
Kenton Varda's avatar
Kenton Varda committed
125
                            schema::Type::Which which, Indent indent,
126
                            PrintMode mode) {
127 128
  switch (value.getType()) {
    case DynamicValue::UNKNOWN:
129
      return kj::strTree("?");
130
    case DynamicValue::VOID:
131
      return kj::strTree("void");
132
    case DynamicValue::BOOL:
133
      return kj::strTree(value.as<bool>() ? "true" : "false");
134
    case DynamicValue::INT:
135
      return kj::strTree(value.as<int64_t>());
136
    case DynamicValue::UINT:
137 138
      return kj::strTree(value.as<uint64_t>());
    case DynamicValue::FLOAT:
Kenton Varda's avatar
Kenton Varda committed
139
      if (which == schema::Type::FLOAT32) {
140
        return kj::strTree(value.as<float>());
141
      } else {
142
        return kj::strTree(value.as<double>());
143 144 145
      }
    case DynamicValue::TEXT:
    case DynamicValue::DATA: {
146 147 148 149 150 151 152 153
      // TODO(someday):  Data probably shouldn't be printed as a string.
      kj::ArrayPtr<const char> chars;
      if (value.getType() == DynamicValue::DATA) {
        auto reader = value.as<Data>();
        chars = kj::arrayPtr(reinterpret_cast<const char*>(reader.begin()), reader.size());
      } else {
        chars = value.as<Text>();
      }
154 155 156

      kj::Vector<char> escaped(chars.size());

157
      for (char c: chars) {
158
        switch (c) {
159 160 161 162 163 164 165 166 167 168
          case '\a': escaped.addAll(kj::StringPtr("\\a")); 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;
          case '\v': escaped.addAll(kj::StringPtr("\\v")); break;
          case '\'': escaped.addAll(kj::StringPtr("\\\'")); break;
          case '\"': escaped.addAll(kj::StringPtr("\\\"")); break;
          case '\\': escaped.addAll(kj::StringPtr("\\\\")); break;
169 170
          default:
            if (c < 0x20) {
171 172
              escaped.add('\\');
              escaped.add('x');
173
              uint8_t c2 = c;
174 175
              escaped.add(HEXDIGITS[c2 / 16]);
              escaped.add(HEXDIGITS[c2 % 16]);
176
            } else {
177
              escaped.add(c);
178 179 180 181
            }
            break;
        }
      }
182
      return kj::strTree('"', escaped, '"');
183 184 185
    }
    case DynamicValue::LIST: {
      auto listValue = value.as<DynamicList>();
186
      auto which = listValue.getSchema().whichElementType();
187
      kj::Array<kj::StringTree> elements = KJ_MAP(element, listValue) {
188 189
        return print(element, which, indent.next(), BARE);
      };
190
      return kj::strTree('[', indent.delimit(kj::mv(elements), mode, PrintKind::LIST), ']');
191 192 193
    }
    case DynamicValue::ENUM: {
      auto enumValue = value.as<DynamicEnum>();
194
      KJ_IF_MAYBE(enumerant, enumValue.getEnumerant()) {
195
        return kj::strTree(enumerant->getProto().getName());
196
      } else {
197
        // Unknown enum value; output raw number.
Kenton Varda's avatar
Kenton Varda committed
198
        return kj::strTree('(', enumValue.getRaw(), ')');
199 200 201 202 203
      }
      break;
    }
    case DynamicValue::STRUCT: {
      auto structValue = value.as<DynamicStruct>();
Kenton Varda's avatar
Kenton Varda committed
204 205 206 207 208
      auto unionFields = structValue.getSchema().getUnionFields();
      auto nonUnionFields = structValue.getSchema().getNonUnionFields();

      kj::Vector<kj::StringTree> printedFields(nonUnionFields.size() + (unionFields.size() != 0));

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

212 213 214 215 216 217 218 219 220
      kj::StringTree unionValue;
      KJ_IF_MAYBE(field, which) {
        // Even if the union field has its default value, if it is not the default field of the
        // union then we have to print it anyway.
        auto fieldProto = field->getProto();
        if (fieldProto.getDiscriminantValue() != 0 || structValue.has(*field)) {
          unionValue = kj::strTree(
              fieldProto.getName(), " = ",
              print(structValue.get(*field), whichFieldType(*field), indent.next(), PREFIXED));
221 222
        } else {
          which = nullptr;
223 224 225
        }
      }

Kenton Varda's avatar
Kenton Varda committed
226
      for (auto field: nonUnionFields) {
227 228
        KJ_IF_MAYBE(unionField, which) {
          if (unionField->getIndex() < field.getIndex()) {
229
            printedFields.add(kj::mv(unionValue));
230 231 232
            which = nullptr;
          }
        }
Kenton Varda's avatar
Kenton Varda committed
233 234 235 236 237
        if (structValue.has(field)) {
          printedFields.add(kj::strTree(
              field.getProto().getName(), " = ",
              print(structValue.get(field), whichFieldType(field), indent.next(), PREFIXED)));
        }
238
      }
239 240 241
      if (which != nullptr) {
        // Union value is last.
        printedFields.add(kj::mv(unionValue));
242
      }
Kenton Varda's avatar
Kenton Varda committed
243 244

      if (mode == PARENTHESIZED) {
245
        return indent.delimit(printedFields.releaseAsArray(), mode, PrintKind::RECORD);
246
      } else {
247 248
        return kj::strTree(
            '(', indent.delimit(printedFields.releaseAsArray(), mode, PrintKind::RECORD), ')');
249 250
      }
    }
251 252
    case DynamicValue::CAPABILITY:
      return kj::strTree("<external capability>");
253 254
    case DynamicValue::ANY_POINTER:
      return kj::strTree("<opaque pointer>");
255
  }
256 257

  KJ_UNREACHABLE;
258 259
}

260
kj::StringTree stringify(DynamicValue::Reader value) {
Kenton Varda's avatar
Kenton Varda committed
261
  return print(value, schema::Type::STRUCT, Indent(false), BARE);
262 263
}

Kenton Varda's avatar
Kenton Varda committed
264 265
}  // namespace

266
kj::StringTree prettyPrint(DynamicStruct::Reader value) {
Kenton Varda's avatar
Kenton Varda committed
267
  return print(value, schema::Type::STRUCT, Indent(true), BARE);
268 269
}

270
kj::StringTree prettyPrint(DynamicList::Reader value) {
Kenton Varda's avatar
Kenton Varda committed
271
  return print(value, schema::Type::LIST, Indent(true), BARE);
272 273
}

274 275
kj::StringTree prettyPrint(DynamicStruct::Builder value) { return prettyPrint(value.asReader()); }
kj::StringTree prettyPrint(DynamicList::Builder value) { return prettyPrint(value.asReader()); }
276

277 278 279 280 281 282 283
kj::StringTree KJ_STRINGIFY(const DynamicValue::Reader& value) { return stringify(value); }
kj::StringTree KJ_STRINGIFY(const DynamicValue::Builder& value) { return stringify(value.asReader()); }
kj::StringTree KJ_STRINGIFY(DynamicEnum value) { return stringify(value); }
kj::StringTree KJ_STRINGIFY(const DynamicStruct::Reader& value) { return stringify(value); }
kj::StringTree KJ_STRINGIFY(const DynamicStruct::Builder& value) { return stringify(value.asReader()); }
kj::StringTree KJ_STRINGIFY(const DynamicList::Reader& value) { return stringify(value); }
kj::StringTree KJ_STRINGIFY(const DynamicList::Builder& value) { return stringify(value.asReader()); }
Kenton Varda's avatar
Kenton Varda committed
284

285
namespace _ {  // private
286

287
kj::StringTree structString(StructReader reader, const RawSchema& schema) {
288 289 290
  return stringify(DynamicStruct::Reader(StructSchema(&schema), reader));
}

291
}  // namespace _ (private)
292

293
}  // namespace capnp