1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
119
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
183
184
185
186
187
188
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
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
// Copyright (c) 2013-2014 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 "dynamic.h"
#include <kj/debug.h>
#include <kj/vector.h>
namespace capnp {
namespace {
static const char HEXDIGITS[] = "0123456789abcdef";
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).
};
enum class PrintKind {
LIST,
RECORD
};
class Indent {
public:
explicit Indent(bool enable): amount(enable ? 1 : 0) {}
Indent next() {
return Indent(amount == 0 ? 0 : amount + 1);
}
kj::StringTree delimit(kj::Array<kj::StringTree> items, PrintMode mode, PrintKind kind) {
if (amount == 0 || canPrintAllInline(items, kind)) {
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)), ' ');
}
}
private:
uint amount;
explicit Indent(uint amount): amount(amount) {}
static constexpr size_t maxInlineValueSize = 24;
static constexpr size_t maxInlineRecordSize = 64;
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;
}
static bool canPrintAllInline(const kj::Array<kj::StringTree>& items, PrintKind kind) {
size_t totalSize = 0;
for (auto& item: items) {
if (!canPrintInline(item)) return false;
if (kind == PrintKind::RECORD) {
totalSize += item.size();
if (totalSize > maxInlineRecordSize) return false;
}
}
return true;
}
};
static schema::Type::Which whichFieldType(const StructSchema::Field& field) {
auto proto = field.getProto();
switch (proto.which()) {
case schema::Field::SLOT:
return proto.getSlot().getType().which();
case schema::Field::GROUP:
return schema::Type::STRUCT;
}
KJ_UNREACHABLE;
}
static kj::StringTree print(const DynamicValue::Reader& value,
schema::Type::Which which, Indent indent,
PrintMode mode) {
switch (value.getType()) {
case DynamicValue::UNKNOWN:
return kj::strTree("?");
case DynamicValue::VOID:
return kj::strTree("void");
case DynamicValue::BOOL:
return kj::strTree(value.as<bool>() ? "true" : "false");
case DynamicValue::INT:
return kj::strTree(value.as<int64_t>());
case DynamicValue::UINT:
return kj::strTree(value.as<uint64_t>());
case DynamicValue::FLOAT:
if (which == schema::Type::FLOAT32) {
return kj::strTree(value.as<float>());
} else {
return kj::strTree(value.as<double>());
}
case DynamicValue::TEXT:
case DynamicValue::DATA: {
// TODO(now): Data should be printed as binary literal.
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>();
}
kj::Vector<char> escaped(chars.size());
for (char c: chars) {
switch (c) {
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;
default:
if (c < 0x20) {
escaped.add('\\');
escaped.add('x');
uint8_t c2 = c;
escaped.add(HEXDIGITS[c2 / 16]);
escaped.add(HEXDIGITS[c2 % 16]);
} else {
escaped.add(c);
}
break;
}
}
return kj::strTree('"', escaped, '"');
}
case DynamicValue::LIST: {
auto listValue = value.as<DynamicList>();
auto which = listValue.getSchema().whichElementType();
kj::Array<kj::StringTree> elements = KJ_MAP(element, listValue) {
return print(element, which, indent.next(), BARE);
};
return kj::strTree('[', indent.delimit(kj::mv(elements), mode, PrintKind::LIST), ']');
}
case DynamicValue::ENUM: {
auto enumValue = value.as<DynamicEnum>();
KJ_IF_MAYBE(enumerant, enumValue.getEnumerant()) {
return kj::strTree(enumerant->getProto().getName());
} else {
// Unknown enum value; output raw number.
return kj::strTree('(', enumValue.getRaw(), ')');
}
break;
}
case DynamicValue::STRUCT: {
auto structValue = value.as<DynamicStruct>();
auto unionFields = structValue.getSchema().getUnionFields();
auto nonUnionFields = structValue.getSchema().getNonUnionFields();
kj::Vector<kj::StringTree> printedFields(nonUnionFields.size() + (unionFields.size() != 0));
// We try to write the union field, if any, in proper order with the rest.
auto which = structValue.which();
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));
} else {
which = nullptr;
}
}
for (auto field: nonUnionFields) {
KJ_IF_MAYBE(unionField, which) {
if (unionField->getIndex() < field.getIndex()) {
printedFields.add(kj::mv(unionValue));
which = nullptr;
}
}
if (structValue.has(field)) {
printedFields.add(kj::strTree(
field.getProto().getName(), " = ",
print(structValue.get(field), whichFieldType(field), indent.next(), PREFIXED)));
}
}
if (which != nullptr) {
// Union value is last.
printedFields.add(kj::mv(unionValue));
}
if (mode == PARENTHESIZED) {
return indent.delimit(printedFields.releaseAsArray(), mode, PrintKind::RECORD);
} else {
return kj::strTree(
'(', indent.delimit(printedFields.releaseAsArray(), mode, PrintKind::RECORD), ')');
}
}
case DynamicValue::CAPABILITY:
return kj::strTree("<external capability>");
case DynamicValue::ANY_POINTER:
return kj::strTree("<opaque pointer>");
}
KJ_UNREACHABLE;
}
kj::StringTree stringify(DynamicValue::Reader value) {
return print(value, schema::Type::STRUCT, Indent(false), BARE);
}
} // namespace
kj::StringTree prettyPrint(DynamicStruct::Reader value) {
return print(value, schema::Type::STRUCT, Indent(true), BARE);
}
kj::StringTree prettyPrint(DynamicList::Reader value) {
return print(value, schema::Type::LIST, Indent(true), BARE);
}
kj::StringTree prettyPrint(DynamicStruct::Builder value) { return prettyPrint(value.asReader()); }
kj::StringTree prettyPrint(DynamicList::Builder value) { return prettyPrint(value.asReader()); }
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()); }
namespace _ { // private
kj::StringTree structString(StructReader reader, const RawBrandedSchema& schema) {
return stringify(DynamicStruct::Reader(Schema(&schema).asStruct(), reader));
}
} // namespace _ (private)
} // namespace capnp