-
Notifications
You must be signed in to change notification settings - Fork 40
/
generate_bindings.dart
502 lines (419 loc) · 14.6 KB
/
generate_bindings.dart
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import "dart:io";
import "dart:async";
import "package:xml/xml.dart" as xml;
import "package:http/http.dart" as http;
import "package:logging/logging.dart";
final Logger logger = Logger("tools");
class AmqpBindingsBuilder {
// The following list of messages will be excluded from
// the generated bindings
List<String> excludedMessages = const [
"BasicGet",
"BasicGetOk",
"BasicGetEmpty",
"BasicRecoverAsync"
];
StringBuffer generatedMessageFactoryFile = StringBuffer("""
// The file contains the base class for AMQP method messages
// and a factory constructor for unserializing AMQP messages
// from incoming frames
//
// File was auto-generated by generate_bindings.dart at ${DateTime.now()}
//
// Do not modify
part of "../../protocol.dart";
abstract class Message {
int get msgClassId;
int get msgMethodId;
bool get msgHasContent;
void serialize(TypeEncoder encoder);
factory Message.fromStream(TypeDecoder decoder){
int msgClassId = decoder.readUInt16();
int msgMethodId = decoder.readUInt16();
switch( msgClassId ){
""");
StringBuffer generatedMessageFactoryFooter = StringBuffer(r"""
}
// Message decoding failed; unknown message
throw ArgumentError("Unknown message type (class: ${msgClassId}, method: ${msgMethodId})");
}
}
""");
StringBuffer generatedLibraryFile = StringBuffer("""
// The file contains AMQP binding imports
//
// File was auto-generated by generate_bindings.dart at ${DateTime.now()}
//
// Do not modify
part of "../../../protocol.dart";
import "dart:async";
import "dart:convert";
import "dart:typed_data";
import "dart:collection";
import "dart:math" as math;
// Internal lib dependencies
import "enums.dart";
import "exceptions.dart";
// Stream reader/writers
part "protocol/stream/chunked_input_reader.dart";
part "protocol/stream/chunked_output_writer.dart";
part "protocol/stream/type_decoder.dart";
part "protocol/stream/type_encoder.dart";
// Message interface
part "protocol/messages/message.dart";
part "protocol/messages/message_properties.dart";
// Frame headers
part "protocol/headers/header.dart";
part "protocol/headers/protocol_header.dart";
part "protocol/headers/frame_header.dart";
part "protocol/headers/content_header.dart";
// Writers
part "protocol/io/frame_writer.dart";
part "protocol/io/tuning_settings.dart";
// Frame interfaces and implementations
part "protocol/frame/raw_frame.dart";
part "protocol/frame/impl/heartbeat_frame_impl.dart";
part "protocol/frame/decoded_message.dart";
part "protocol/frame/impl/decoded_message_impl.dart";
// Readers
part "protocol/io/raw_frame_parser.dart";
part "protocol/io/amqp_message_decoder.dart";
// Autogenerated class bindings
""");
final Map<String, String> _amqpTypeToDartType = {
"bit": "bool",
"octet": "int",
"short": "int",
"long": "int",
"longlong": "int",
"shortstr": "String",
"longstr": "String",
"timestamp": "DateTime",
"table": "Map<String, Object>"
};
final Map<String, String> _amqpCustomTypeToBasicType = {};
Future<xml.XmlDocument> _retrieveSchema(String schemaUrl) async {
logger.info("- Retrieving schema from $schemaUrl");
// Check for cached copy
File cachedCopy = File(schemaUrl.split('/').last);
bool exists = await cachedCopy.exists();
String data = exists
? await cachedCopy.readAsString()
: await http.read(Uri.parse(schemaUrl));
logger.info("- Parsing schema");
return xml.XmlDocument.parse(data);
}
String _parseMethod(
String className, int classId, xml.XmlElement amqpMethod) {
// Convert dashed field name to class case
String methodName = amqpMethod
.getAttribute("name")!
.replaceAllMapped(RegExp(r"^([a-z])"), (Match m) {
return m.group(1)!.toUpperCase();
}).replaceAllMapped(RegExp(r"-([a-z])"), (Match m) {
return m.group(1)!.toUpperCase();
});
// Check if method message should have a body
String? hasContentAttr = amqpMethod.getAttribute("content");
bool hasContent = hasContentAttr != null && hasContentAttr == "1";
// Extract clmethod id
int methodId = int.parse(amqpMethod.getAttribute("index")!, radix: 10);
bool implementedByClient = amqpMethod
.findAllElements("chassis")
.any((xml.XmlElement elem) => elem.getAttribute("name") == "client");
bool implementedByServer = amqpMethod
.findAllElements("chassis")
.any((xml.XmlElement elem) => elem.getAttribute("name") == "server");
// Update message factory
if (implementedByClient) {
generatedMessageFactoryFile.write("""
case $methodId:
return $className$methodName.fromStream(decoder);
""");
}
logger.fine(" Method: $methodName (id: $methodId)");
// Generate class
StringBuffer generatedClass = StringBuffer("""
class $className$methodName implements Message {
final bool msgHasContent = $hasContent;
final int msgClassId = $classId;
final int msgMethodId = $methodId;
// Message arguments
""");
StringBuffer serializerMethod = StringBuffer("""
void serialize(TypeEncoder encoder) {
encoder
..writeUInt16(msgClassId)
..writeUInt16(msgMethodId)
""");
StringBuffer ctors =
StringBuffer((implementedByServer || !implementedByClient)
? """
$className$methodName();
"""
: "");
if (implementedByClient) {
ctors.write("""
$className$methodName.fromStream(TypeDecoder decoder) {
""");
}
StringBuffer toStringMethod = StringBuffer("""
String toString(){
return \"\"\"
$className.$methodName
${String.fromCharCodes(List<int>.filled(className.length + methodName.length + 1, "-".codeUnitAt(0)))}
""");
bool emittingBits = false;
bool declaredBitVar = false;
int bitOffset = 0;
// Parse fields
amqpMethod.descendants
.where((xml.XmlNode node) =>
node is xml.XmlElement && node.name.local == "field")
.forEach((xml.XmlNode node) {
xml.XmlElement amqpMethodField = node as xml.XmlElement;
// Convert dashed field name to camelCase
String fieldName = amqpMethodField
.getAttribute("name")!
.replaceAllMapped(RegExp(r"-([a-z])"), (Match m) {
return m.group(1)!.toUpperCase();
}).replaceAll("-", "_");
// Retrieve Dart type for field domain
String? fieldDomain = amqpMethodField.getAttribute("domain") ??
amqpMethodField.getAttribute("type");
String? amqpType = _amqpCustomTypeToBasicType.containsKey(fieldDomain)
? _amqpCustomTypeToBasicType[fieldDomain]
: fieldDomain;
String? dartType = _amqpTypeToDartType[amqpType];
logger.fine(" Field: $fieldName (=> $dartType)");
generatedClass.write(" $dartType $fieldName;\n");
String encoderFunc = "";
switch (amqpType) {
case "bit":
encoderFunc = "writeBits";
break;
case "octet":
encoderFunc = "writeUInt8";
break;
case "short":
encoderFunc = "writeUInt16";
break;
case "long":
encoderFunc = "writeUInt32";
break;
case "longlong":
encoderFunc = "writeUInt64";
break;
case "shortstr":
encoderFunc = "writeShortString";
break;
case "longstr":
encoderFunc = "writeLongString";
break;
case "timestamp":
encoderFunc = "writeTimestamp";
break;
case "table":
encoderFunc = "writeFieldTable";
break;
default:
throw ArgumentError(
"Not sure how to encode amqp type $amqpType for field $fieldName (field domain: $fieldDomain)");
}
if (amqpType == "bit") {
// If not emitting bits, start a block
if (!emittingBits) {
serializerMethod.write(" ..$encoderFunc([$fieldName");
emittingBits = true;
// Declare a temp var for parsing bitmasks in c-tor and reset bit offset
if (!declaredBitVar && implementedByClient) {
ctors.write("""
int bitmask;
""");
declaredBitVar = true;
}
if (implementedByClient) {
ctors.write("""
bitmask = decoder.readUInt8();
""");
}
// Unserialize field value from read bitmask
bitOffset = 0;
if (implementedByClient) {
ctors.write(
" $fieldName = bitmask & 0x${(1 << bitOffset).toRadixString(16)} != 0;\n");
}
bitOffset++;
} else {
serializerMethod.write(", $fieldName");
// Unserialize field value from read bitmask
if (implementedByClient) {
ctors.write(
" $fieldName = bitmask & 0x${(1 << bitOffset).toRadixString(16)} != 0;\n");
}
bitOffset++;
}
} else {
// If was emitting bits, flush the block
if (emittingBits) {
serializerMethod.write("])\n");
emittingBits = false;
}
serializerMethod.write(" ..$encoderFunc($fieldName)\n");
if (implementedByClient) {
ctors.write(
" $fieldName = decoder.${encoderFunc.replaceAll("write", "read")}(${amqpType == "table" ? '"$fieldName"' : ""});\n");
}
}
// Emit to string part
toStringMethod.write(
"$fieldName : \${${amqpType == "table" ? "indentingJsonEncoder.convert($fieldName)" : fieldName}}\n");
});
// If was emitting bits, flush the block
if (emittingBits) {
serializerMethod.write("])\n");
}
// Finish toString block
toStringMethod.write("\"\"\";\n }\n");
// Finish c-tor block
if (implementedByClient) {
ctors.write(" }");
}
// End casacade
serializerMethod
..write(" ;\n")
..write(" }\n");
generatedClass
..write("\n")
..write(ctors);
if (implementedByServer || !implementedByClient) {
generatedClass
..write("\n")
..write(serializerMethod);
} else {
// Write an empty serializer stub to avoid warnings
generatedClass
..write("\n\n")
..write("""
void serialize(TypeEncoder encoder) {}
""");
}
// ..write("\n")
// ..write(toStringMethod)
generatedClass.write("}\n");
return generatedClass.toString();
}
void _parseClass(xml.XmlElement amqpClass) {
// Convert dashed field name to class case
String className = amqpClass
.getAttribute("name")!
.replaceAllMapped(RegExp(r"^([a-z])"), (Match m) {
return m.group(1)!.toUpperCase();
}).replaceAllMapped(RegExp(r"-([a-z])"), (Match m) {
return m.group(1)!.toUpperCase();
});
// Extract class id
int classId = int.parse(amqpClass.getAttribute("index")!, radix: 10);
logger.fine(" Class: $className (id: $classId)");
// Update message factory for the new class
generatedMessageFactoryFile.write("""
case $classId: // Class: $className
switch (msgMethodId) {
""");
// Begin generation of method classes for this message class
StringBuffer generatedMethodsFile = StringBuffer("""
// The file contains all method messages for AMQP class $className (id: $classId)
//
// File was auto-generated by generate_bindings.dart at ${DateTime.now()}
//
// Do not modify
// ignore_for_file: empty_constructor_bodies
part of dart_amqp.protocol;
""");
// Fetch methods
amqpClass.descendants
.where((xml.XmlNode node) =>
node is xml.XmlElement && node.name.local == "method")
.where((xml.XmlNode elemNode) {
xml.XmlElement node = elemNode as xml.XmlElement;
// Apply method exclusion list
String methodName = node
.getAttribute("name")!
.replaceAllMapped(RegExp(r"^([a-z])"), (Match m) {
return m.group(1)!.toUpperCase();
}).replaceAllMapped(RegExp(r"-([a-z])"), (Match m) {
return m.group(1)!.toUpperCase();
});
String fullClassName = "$className$methodName";
return !excludedMessages.contains(fullClassName);
}).forEach((xml.XmlNode elemNode) {
xml.XmlElement node = elemNode as xml.XmlElement;
generatedMethodsFile
..write("\n")
..write(_parseMethod(className, classId, node));
});
//logger.fine(generatedFile.toString());
// Write method class file file
File methodFile = File(
"../lib/src/protocol/messages/bindings/${className.toLowerCase()}.dart");
methodFile.writeAsStringSync(generatedMethodsFile.toString());
// Update message factory
generatedMessageFactoryFile.write("""
}
break;
""");
}
void _parseDomain(xml.XmlElement amqpDomain) {
// If this is an unknown domain but has an alias to a known type add it to the list
String name = amqpDomain.getAttribute("name")!;
String type = amqpDomain.getAttribute("type")!;
// Already there
if (_amqpTypeToDartType.containsKey(name) ||
_amqpCustomTypeToBasicType.containsKey(name)) {
return;
}
// We can map the domain type to an existing amqp type
if (_amqpTypeToDartType.containsKey(type)) {
_amqpCustomTypeToBasicType[name] = type;
return;
}
throw Exception(
"Could not map domain $name of type $type to a known Dart type");
}
void _parseSchema(xml.XmlDocument schema) {
logger.info("- Processing custom domains");
schema.descendants
.whereType<xml.XmlElement>()
.where((xml.XmlElement node) => node.name.local == "domain")
.forEach(_parseDomain);
logger.info("- Processing amqp classes");
schema.descendants
.where((xml.XmlNode node) =>
node is xml.XmlElement && node.name.local == "class")
.forEach((xml.XmlNode elemNode) {
xml.XmlElement amqpClassElement = elemNode as xml.XmlElement;
String className = amqpClassElement.getAttribute("name")!.toLowerCase();
generatedLibraryFile
.write("part \"protocol/messages/bindings/$className.dart\";\n");
_parseClass(amqpClassElement);
});
// Write output files
File libFile = File("../lib/src/protocol.dart");
libFile.writeAsStringSync(generatedLibraryFile.toString());
File messageFile = File("../lib/src/protocol/messages/message.dart");
generatedMessageFactoryFile.write(generatedMessageFactoryFooter);
messageFile.writeAsStringSync(generatedMessageFactoryFile.toString());
}
void build(String schemaUrl) async {
_parseSchema(await _retrieveSchema(schemaUrl));
}
}
main() {
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((LogRecord rec) {
print("${rec.level.name}: ${rec.time}: ${rec.message}");
});
logger.info("Building amqp bindings");
AmqpBindingsBuilder()
.build("https://www.rabbitmq.com/resources/specs/amqp0-9-1.xml");
}