stringify.c++ 10.5 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// 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:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// 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.
21

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

26
namespace capnp {
27 28 29 30 31

namespace {

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

32 33 34 35 36 37 38 39 40 41 42 43
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).
};

44 45 46 47 48
enum class PrintKind {
  LIST,
  RECORD
};

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

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

57 58
  kj::StringTree delimit(kj::Array<kj::StringTree> items, PrintMode mode, PrintKind kind) {
    if (amount == 0 || canPrintAllInline(items, kind)) {
59 60
      return kj::StringTree(kj::mv(items), ", ");
    } else {
61 62
      KJ_STACK_ARRAY(char, delimArrayPtr, amount * 2 + 3, 32, 256);
      auto delim = delimArrayPtr.begin();
63 64 65 66 67 68 69 70 71 72 73
      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)), ' ');
    }
74 75 76 77
  }

private:
  uint amount;
78 79 80 81

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

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

  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;
  }

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

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

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

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

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

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

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

210 211 212 213 214 215 216 217 218
      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));
219 220
        } else {
          which = nullptr;
221 222 223
        }
      }

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

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

  KJ_UNREACHABLE;
256 257
}

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

Kenton Varda's avatar
Kenton Varda committed
262 263
}  // namespace

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

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

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

275 276 277 278 279 280 281
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
282

283
namespace _ {  // private
284

285 286
kj::StringTree structString(StructReader reader, const RawBrandedSchema& schema) {
  return stringify(DynamicStruct::Reader(Schema(&schema).asStruct(), reader));
287 288
}

289 290 291 292 293 294 295 296 297
kj::String enumString(uint16_t value, const RawBrandedSchema& schema) {
  auto enumerants = Schema(&schema).asEnum().getEnumerants();
  if (value < enumerants.size()) {
    return kj::heapString(enumerants[value].getProto().getName());
  } else {
    return kj::str(value);
  }
}

298
}  // namespace _ (private)
299

300
}  // namespace capnp