-
Notifications
You must be signed in to change notification settings - Fork 38
/
emitter.d
1696 lines (1490 loc) · 57.5 KB
/
emitter.d
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Ferdinand Majerech 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
* YAML emitter.
* Code based on PyYAML: http://www.pyyaml.org
*/
module dyaml.emitter;
import std.algorithm;
import std.array;
import std.ascii;
import std.container;
import std.conv;
import std.exception;
import std.format;
import std.range;
import std.string;
import std.system;
import std.typecons;
import std.utf;
import dyaml.stream;
import dyaml.anchor;
import dyaml.encoding;
import dyaml.escapes;
import dyaml.event;
import dyaml.exception;
import dyaml.fastcharsearch;
import dyaml.flags;
import dyaml.linebreak;
import dyaml.queue;
import dyaml.style;
import dyaml.tag;
import dyaml.tagdirective;
package:
/**
* Exception thrown at Emitter errors.
*
* See_Also:
* YAMLException
*/
class EmitterException : YAMLException
{
mixin ExceptionCtors;
}
private alias EmitterException Error;
//Stores results of analysis of a scalar, determining e.g. what scalar style to use.
align(4) struct ScalarAnalysis
{
//Scalar itself.
string scalar;
///Analysis results.
Flags!("empty", "multiline", "allowFlowPlain", "allowBlockPlain",
"allowSingleQuoted", "allowDoubleQuoted", "allowBlock", "isNull") flags;
}
///Quickly determines if a character is a newline.
private mixin FastCharSearch!"\n\u0085\u2028\u2029"d newlineSearch_;
// override the canFind added by the FastCharSearch mixins
private alias canFind = std.algorithm.canFind;
//Emits YAML events into a file/stream.
struct Emitter
{
private:
alias dyaml.tagdirective.TagDirective TagDirective;
///Default tag handle shortcuts and replacements.
static TagDirective[] defaultTagDirectives_ =
[TagDirective("!", "!"), TagDirective("!!", "tag:yaml.org,2002:")];
///Stream to write to.
YStream stream_;
///Encoding can be overriden by STREAM-START.
Encoding encoding_ = Encoding.UTF_8;
///Stack of states.
Array!(void delegate()) states_;
///Current state.
void delegate() state_;
///Event queue.
Queue!Event events_;
///Event we're currently emitting.
Event event_;
///Stack of previous indentation levels.
Array!int indents_;
///Current indentation level.
int indent_ = -1;
///Level of nesting in flow context. If 0, we're in block context.
uint flowLevel_ = 0;
/// Describes context (where we are in the document).
enum Context
{
/// Root node of a document.
Root,
/// Sequence.
Sequence,
/// Mapping.
MappingNoSimpleKey,
/// Mapping, in a simple key.
MappingSimpleKey
}
/// Current context.
Context context_;
///Characteristics of the last emitted character:
///Line.
uint line_ = 0;
///Column.
uint column_ = 0;
///Whitespace character?
bool whitespace_ = true;
///indentation space, '-', '?', or ':'?
bool indentation_ = true;
///Does the document require an explicit document indicator?
bool openEnded_;
///Formatting details.
///Canonical scalar format?
bool canonical_;
///Best indentation width.
uint bestIndent_ = 2;
///Best text width.
uint bestWidth_ = 80;
///Best line break character/s.
LineBreak bestLineBreak_;
///Tag directive handle - prefix pairs.
TagDirective[] tagDirectives_;
///Anchor/alias to process.
string preparedAnchor_ = null;
///Tag to process.
string preparedTag_ = null;
///Analysis result of the current scalar.
ScalarAnalysis analysis_;
///Style of the current scalar.
ScalarStyle style_ = ScalarStyle.Invalid;
public:
@disable int opCmp(ref Emitter);
@disable bool opEquals(ref Emitter);
/**
* Construct an emitter.
*
* Params: stream = YStream to write to. Must be writable.
* canonical = Write scalars in canonical form?
* indent = Indentation width.
* lineBreak = Line break character/s.
*/
this(YStream stream, const bool canonical, const int indent, const int width,
const LineBreak lineBreak) @trusted
in{assert(stream.writeable, "Can't emit YAML to a non-writable stream");}
body
{
states_.reserve(32);
indents_.reserve(32);
stream_ = stream;
canonical_ = canonical;
state_ = &expectStreamStart;
if(indent > 1 && indent < 10){bestIndent_ = indent;}
if(width > bestIndent_ * 2) {bestWidth_ = width;}
bestLineBreak_ = lineBreak;
analysis_.flags.isNull = true;
}
///Destroy the emitter.
@trusted ~this()
{
stream_ = null;
states_.destroy();
events_.destroy();
indents_.destroy();
tagDirectives_.destroy();
tagDirectives_ = null;
preparedAnchor_.destroy();
preparedAnchor_ = null;
preparedTag_.destroy();
preparedTag_ = null;
}
///Emit an event. Throws EmitterException on error.
void emit(Event event) @trusted
{
events_.push(event);
while(!needMoreEvents())
{
event_ = events_.pop();
state_();
event_.destroy();
}
}
private:
///Pop and return the newest state in states_.
void delegate() popState() @trusted
{
enforce(states_.length > 0,
new YAMLException("Emitter: Need to pop a state but there are no states left"));
const result = states_.back;
states_.length = states_.length - 1;
return result;
}
///Pop and return the newest indent in indents_.
int popIndent() @trusted
{
enforce(indents_.length > 0,
new YAMLException("Emitter: Need to pop an indent level but there"
" are no indent levels left"));
const result = indents_.back;
indents_.length = indents_.length - 1;
return result;
}
///Write a string to the file/stream.
void writeString(const string str) @system
{
try final switch(encoding_)
{
case Encoding.UTF_8:
stream_.writeExact(str.ptr, str.length * char.sizeof);
break;
case Encoding.UTF_16:
const buffer = to!wstring(str);
stream_.writeExact(buffer.ptr, buffer.length * wchar.sizeof);
break;
case Encoding.UTF_32:
const buffer = to!dstring(str);
stream_.writeExact(buffer.ptr, buffer.length * dchar.sizeof);
break;
}
catch(Exception e)
{
throw new Error("Unable to write to stream: " ~ e.msg);
}
}
///In some cases, we wait for a few next events before emitting.
bool needMoreEvents() @trusted nothrow
{
if(events_.length == 0){return true;}
const event = events_.peek();
if(event.id == EventID.DocumentStart){return needEvents(1);}
if(event.id == EventID.SequenceStart){return needEvents(2);}
if(event.id == EventID.MappingStart) {return needEvents(3);}
return false;
}
///Determines if we need specified number of more events.
bool needEvents(in uint count) @system nothrow
{
int level = 0;
//Rather ugly, but good enough for now.
//Couldn't be bothered writing a range as events_ should eventually
//become a Phobos queue/linked list.
events_.startIteration();
events_.next();
while(!events_.iterationOver())
{
const event = events_.next();
static starts = [EventID.DocumentStart, EventID.SequenceStart, EventID.MappingStart];
static ends = [EventID.DocumentEnd, EventID.SequenceEnd, EventID.MappingEnd];
if(starts.canFind(event.id)) {++level;}
else if(ends.canFind(event.id)){--level;}
else if(event.id == EventID.StreamStart){level = -1;}
if(level < 0)
{
return false;
}
}
return events_.length < (count + 1);
}
///Increase indentation level.
void increaseIndent(const Flag!"flow" flow = No.flow, const bool indentless = false) @trusted
{
indents_ ~= indent_;
if(indent_ == -1)
{
indent_ = flow ? bestIndent_ : 0;
}
else if(!indentless)
{
indent_ += bestIndent_;
}
}
///Determines if the type of current event is as specified. Throws if no event.
bool eventTypeIs(in EventID id) const pure @trusted
{
enforce(!event_.isNull,
new Error("Expected an event, but no event is available."));
return event_.id == id;
}
//States.
//Stream handlers.
///Handle start of a file/stream.
void expectStreamStart() @trusted
{
enforce(eventTypeIs(EventID.StreamStart),
new Error("Expected YStreamStart, but got " ~ event_.idString));
encoding_ = event_.encoding;
writeStreamStart();
state_ = &expectDocumentStart!(Yes.first);
}
///Expect nothing, throwing if we still have something.
void expectNothing() const @trusted
{
throw new Error("Expected nothing, but got " ~ event_.idString);
}
//Document handlers.
///Handle start of a document.
void expectDocumentStart(Flag!"first" first)() @trusted
{
enforce(eventTypeIs(EventID.DocumentStart) || eventTypeIs(EventID.StreamEnd),
new Error("Expected DocumentStart or YStreamEnd, but got "
~ event_.idString));
if(event_.id == EventID.DocumentStart)
{
const YAMLVersion = event_.value;
auto tagDirectives = event_.tagDirectives;
if(openEnded_ && (YAMLVersion !is null || tagDirectives !is null))
{
writeIndicator("...", Yes.needWhitespace);
writeIndent();
}
if(YAMLVersion !is null)
{
writeVersionDirective(prepareVersion(YAMLVersion));
}
if(tagDirectives !is null)
{
tagDirectives_ = tagDirectives;
sort!"icmp(a.handle, b.handle) < 0"(tagDirectives_);
foreach(ref pair; tagDirectives_)
{
writeTagDirective(prepareTagHandle(pair.handle),
prepareTagPrefix(pair.prefix));
}
}
bool eq(ref TagDirective a, ref TagDirective b){return a.handle == b.handle;}
//Add any default tag directives that have not been overriden.
foreach(ref def; defaultTagDirectives_)
{
if(!std.algorithm.canFind!eq(tagDirectives_, def))
{
tagDirectives_ ~= def;
}
}
const implicit = first && !event_.explicitDocument && !canonical_ &&
YAMLVersion is null && tagDirectives is null &&
!checkEmptyDocument();
if(!implicit)
{
writeIndent();
writeIndicator("---", Yes.needWhitespace);
if(canonical_){writeIndent();}
}
state_ = &expectRootNode;
}
else if(event_.id == EventID.StreamEnd)
{
if(openEnded_)
{
writeIndicator("...", Yes.needWhitespace);
writeIndent();
}
writeStreamEnd();
state_ = &expectNothing;
}
}
///Handle end of a document.
void expectDocumentEnd() @trusted
{
enforce(eventTypeIs(EventID.DocumentEnd),
new Error("Expected DocumentEnd, but got " ~ event_.idString));
writeIndent();
if(event_.explicitDocument)
{
writeIndicator("...", Yes.needWhitespace);
writeIndent();
}
stream_.flush();
state_ = &expectDocumentStart!(No.first);
}
///Handle the root node of a document.
void expectRootNode() @trusted
{
states_ ~= &expectDocumentEnd;
expectNode(Context.Root);
}
///Handle a mapping node.
//
//Params: simpleKey = Are we in a simple key?
void expectMappingNode(const bool simpleKey = false)
{
expectNode(simpleKey ? Context.MappingSimpleKey : Context.MappingNoSimpleKey);
}
///Handle a sequence node.
void expectSequenceNode()
{
expectNode(Context.Sequence);
}
///Handle a new node. Context specifies where in the document we are.
void expectNode(const Context context) @trusted
{
context_ = context;
const flowCollection = event_.collectionStyle == CollectionStyle.Flow;
switch(event_.id)
{
case EventID.Alias: expectAlias(); break;
case EventID.Scalar:
processAnchor("&");
processTag();
expectScalar();
break;
case EventID.SequenceStart:
processAnchor("&");
processTag();
if(flowLevel_ > 0 || canonical_ || flowCollection || checkEmptySequence())
{
expectFlowSequence();
}
else
{
expectBlockSequence();
}
break;
case EventID.MappingStart:
processAnchor("&");
processTag();
if(flowLevel_ > 0 || canonical_ || flowCollection || checkEmptyMapping())
{
expectFlowMapping();
}
else
{
expectBlockMapping();
}
break;
default:
throw new Error("Expected Alias, Scalar, SequenceStart or "
"MappingStart, but got: " ~ event_.idString);
}
}
///Handle an alias.
void expectAlias() @trusted
{
enforce(!event_.anchor.isNull(), new Error("Anchor is not specified for alias"));
processAnchor("*");
state_ = popState();
}
///Handle a scalar.
void expectScalar() @trusted
{
increaseIndent(Yes.flow);
processScalar();
indent_ = popIndent();
state_ = popState();
}
//Flow sequence handlers.
///Handle a flow sequence.
void expectFlowSequence() @trusted
{
writeIndicator("[", Yes.needWhitespace, Yes.whitespace);
++flowLevel_;
increaseIndent(Yes.flow);
state_ = &expectFlowSequenceItem!(Yes.first);
}
///Handle a flow sequence item.
void expectFlowSequenceItem(Flag!"first" first)() @trusted
{
if(event_.id == EventID.SequenceEnd)
{
indent_ = popIndent();
--flowLevel_;
static if(!first) if(canonical_)
{
writeIndicator(",", No.needWhitespace);
writeIndent();
}
writeIndicator("]", No.needWhitespace);
state_ = popState();
return;
}
static if(!first){writeIndicator(",", No.needWhitespace);}
if(canonical_ || column_ > bestWidth_){writeIndent();}
states_ ~= &expectFlowSequenceItem!(No.first);
expectSequenceNode();
}
//Flow mapping handlers.
///Handle a flow mapping.
void expectFlowMapping() @trusted
{
writeIndicator("{", Yes.needWhitespace, Yes.whitespace);
++flowLevel_;
increaseIndent(Yes.flow);
state_ = &expectFlowMappingKey!(Yes.first);
}
///Handle a key in a flow mapping.
void expectFlowMappingKey(Flag!"first" first)() @trusted
{
if(event_.id == EventID.MappingEnd)
{
indent_ = popIndent();
--flowLevel_;
static if (!first) if(canonical_)
{
writeIndicator(",", No.needWhitespace);
writeIndent();
}
writeIndicator("}", No.needWhitespace);
state_ = popState();
return;
}
static if(!first){writeIndicator(",", No.needWhitespace);}
if(canonical_ || column_ > bestWidth_){writeIndent();}
if(!canonical_ && checkSimpleKey())
{
states_ ~= &expectFlowMappingSimpleValue;
expectMappingNode(true);
return;
}
writeIndicator("?", Yes.needWhitespace);
states_ ~= &expectFlowMappingValue;
expectMappingNode();
}
///Handle a simple value in a flow mapping.
void expectFlowMappingSimpleValue() @trusted
{
writeIndicator(":", No.needWhitespace);
states_ ~= &expectFlowMappingKey!(No.first);
expectMappingNode();
}
///Handle a complex value in a flow mapping.
void expectFlowMappingValue() @trusted
{
if(canonical_ || column_ > bestWidth_){writeIndent();}
writeIndicator(":", Yes.needWhitespace);
states_ ~= &expectFlowMappingKey!(No.first);
expectMappingNode();
}
//Block sequence handlers.
///Handle a block sequence.
void expectBlockSequence() @safe
{
const indentless = (context_ == Context.MappingNoSimpleKey ||
context_ == Context.MappingSimpleKey) && !indentation_;
increaseIndent(No.flow, indentless);
state_ = &expectBlockSequenceItem!(Yes.first);
}
///Handle a block sequence item.
void expectBlockSequenceItem(Flag!"first" first)() @trusted
{
static if(!first) if(event_.id == EventID.SequenceEnd)
{
indent_ = popIndent();
state_ = popState();
return;
}
writeIndent();
writeIndicator("-", Yes.needWhitespace, No.whitespace, Yes.indentation);
states_ ~= &expectBlockSequenceItem!(No.first);
expectSequenceNode();
}
//Block mapping handlers.
///Handle a block mapping.
void expectBlockMapping() @safe
{
increaseIndent(No.flow);
state_ = &expectBlockMappingKey!(Yes.first);
}
///Handle a key in a block mapping.
void expectBlockMappingKey(Flag!"first" first)() @trusted
{
static if(!first) if(event_.id == EventID.MappingEnd)
{
indent_ = popIndent();
state_ = popState();
return;
}
writeIndent();
if(checkSimpleKey())
{
states_ ~= &expectBlockMappingSimpleValue;
expectMappingNode(true);
return;
}
writeIndicator("?", Yes.needWhitespace, No.whitespace, Yes.indentation);
states_ ~= &expectBlockMappingValue;
expectMappingNode();
}
///Handle a simple value in a block mapping.
void expectBlockMappingSimpleValue() @trusted
{
writeIndicator(":", No.needWhitespace);
states_ ~= &expectBlockMappingKey!(No.first);
expectMappingNode();
}
///Handle a complex value in a block mapping.
void expectBlockMappingValue() @trusted
{
writeIndent();
writeIndicator(":", Yes.needWhitespace, No.whitespace, Yes.indentation);
states_ ~= &expectBlockMappingKey!(No.first);
expectMappingNode();
}
//Checkers.
///Check if an empty sequence is next.
bool checkEmptySequence() const @trusted pure nothrow
{
return event_.id == EventID.SequenceStart && events_.length > 0
&& events_.peek().id == EventID.SequenceEnd;
}
///Check if an empty mapping is next.
bool checkEmptyMapping() const @trusted pure nothrow
{
return event_.id == EventID.MappingStart && events_.length > 0
&& events_.peek().id == EventID.MappingEnd;
}
///Check if an empty document is next.
bool checkEmptyDocument() const @trusted pure nothrow
{
if(event_.id != EventID.DocumentStart || events_.length == 0)
{
return false;
}
const event = events_.peek();
const emptyScalar = event.id == EventID.Scalar && event.anchor.isNull() &&
event.tag.isNull() && event.implicit && event.value == "";
return emptyScalar;
}
///Check if a simple key is next.
bool checkSimpleKey() @trusted
{
uint length = 0;
const id = event_.id;
const scalar = id == EventID.Scalar;
const collectionStart = id == EventID.MappingStart ||
id == EventID.SequenceStart;
if((id == EventID.Alias || scalar || collectionStart)
&& !event_.anchor.isNull())
{
if(preparedAnchor_ is null)
{
preparedAnchor_ = prepareAnchor(event_.anchor);
}
length += preparedAnchor_.length;
}
if((scalar || collectionStart) && !event_.tag.isNull())
{
if(preparedTag_ is null){preparedTag_ = prepareTag(event_.tag);}
length += preparedTag_.length;
}
if(scalar)
{
if(analysis_.flags.isNull){analysis_ = analyzeScalar(event_.value);}
length += analysis_.scalar.length;
}
if(length >= 128){return false;}
return id == EventID.Alias ||
(scalar && !analysis_.flags.empty && !analysis_.flags.multiline) ||
checkEmptySequence() ||
checkEmptyMapping();
}
///Process and write a scalar.
void processScalar() @trusted
{
if(analysis_.flags.isNull){analysis_ = analyzeScalar(event_.value);}
if(style_ == ScalarStyle.Invalid)
{
style_ = chooseScalarStyle();
}
//if(analysis_.flags.multiline && (context_ != Context.MappingSimpleKey) &&
// ([ScalarStyle.Invalid, ScalarStyle.Plain, ScalarStyle.SingleQuoted, ScalarStyle.DoubleQuoted)
// .canFind(style_))
//{
// writeIndent();
//}
auto writer = ScalarWriter(this, analysis_.scalar,
context_ != Context.MappingSimpleKey);
with(writer) final switch(style_)
{
case ScalarStyle.Invalid: assert(false);
case ScalarStyle.DoubleQuoted: writeDoubleQuoted(); break;
case ScalarStyle.SingleQuoted: writeSingleQuoted(); break;
case ScalarStyle.Folded: writeFolded(); break;
case ScalarStyle.Literal: writeLiteral(); break;
case ScalarStyle.Plain: writePlain(); break;
}
analysis_.flags.isNull = true;
style_ = ScalarStyle.Invalid;
}
///Process and write an anchor/alias.
void processAnchor(const string indicator) @trusted
{
if(event_.anchor.isNull())
{
preparedAnchor_ = null;
return;
}
if(preparedAnchor_ is null)
{
preparedAnchor_ = prepareAnchor(event_.anchor);
}
if(preparedAnchor_ !is null && preparedAnchor_ != "")
{
writeIndicator(indicator, Yes.needWhitespace);
writeString(preparedAnchor_);
}
preparedAnchor_ = null;
}
///Process and write a tag.
void processTag() @trusted
{
Tag tag = event_.tag;
if(event_.id == EventID.Scalar)
{
if(style_ == ScalarStyle.Invalid){style_ = chooseScalarStyle();}
if((!canonical_ || tag.isNull()) &&
(style_ == ScalarStyle.Plain ? event_.implicit : event_.implicit_2))
{
preparedTag_ = null;
return;
}
if(event_.implicit && tag.isNull())
{
tag = Tag("!");
preparedTag_ = null;
}
}
else if((!canonical_ || tag.isNull()) && event_.implicit)
{
preparedTag_ = null;
return;
}
enforce(!tag.isNull(), new Error("Tag is not specified"));
if(preparedTag_ is null){preparedTag_ = prepareTag(tag);}
if(preparedTag_ !is null && preparedTag_ != "")
{
writeIndicator(preparedTag_, Yes.needWhitespace);
}
preparedTag_ = null;
}
///Determine style to write the current scalar in.
ScalarStyle chooseScalarStyle() @trusted
{
if(analysis_.flags.isNull){analysis_ = analyzeScalar(event_.value);}
const style = event_.scalarStyle;
const invalidOrPlain = style == ScalarStyle.Invalid || style == ScalarStyle.Plain;
const block = style == ScalarStyle.Literal || style == ScalarStyle.Folded;
const singleQuoted = style == ScalarStyle.SingleQuoted;
const doubleQuoted = style == ScalarStyle.DoubleQuoted;
const allowPlain = flowLevel_ > 0 ? analysis_.flags.allowFlowPlain
: analysis_.flags.allowBlockPlain;
//simple empty or multiline scalars can't be written in plain style
const simpleNonPlain = (context_ == Context.MappingSimpleKey) &&
(analysis_.flags.empty || analysis_.flags.multiline);
if(doubleQuoted || canonical_)
{
return ScalarStyle.DoubleQuoted;
}
if(invalidOrPlain && event_.implicit && !simpleNonPlain && allowPlain)
{
return ScalarStyle.Plain;
}
if(block && flowLevel_ == 0 && context_ != Context.MappingSimpleKey &&
analysis_.flags.allowBlock)
{
return style;
}
if((invalidOrPlain || singleQuoted) &&
analysis_.flags.allowSingleQuoted &&
!(context_ == Context.MappingSimpleKey && analysis_.flags.multiline))
{
return ScalarStyle.SingleQuoted;
}
return ScalarStyle.DoubleQuoted;
}
///Prepare YAML version string for output.
static string prepareVersion(const string YAMLVersion) @trusted
{
enforce(YAMLVersion.split(".")[0] == "1",
new Error("Unsupported YAML version: " ~ YAMLVersion));
return YAMLVersion;
}
///Encode an Unicode character for tag directive and write it to writer.
static void encodeChar(Writer)(ref Writer writer, in dchar c) @trusted
{
char[4] data;
const bytes = encode(data, c);
//For each byte add string in format %AB , where AB are hex digits of the byte.
foreach(const char b; data[0 .. bytes])
{
formattedWrite(writer, "%%%02X", cast(ubyte)b);
}
}
///Prepare tag directive handle for output.
static string prepareTagHandle(const string handle) @trusted
{
enforce(handle !is null && handle != "",
new Error("Tag handle must not be empty"));
if(handle.length > 1) foreach(const dchar c; handle[1 .. $ - 1])
{
enforce(isAlphaNum(c) || "-_"d.canFind(c),
new Error("Invalid character: " ~ to!string(c) ~
" in tag handle " ~ handle));
}
return handle;
}
///Prepare tag directive prefix for output.
static string prepareTagPrefix(const string prefix) @trusted
{
enforce(prefix !is null && prefix != "",
new Error("Tag prefix must not be empty"));
auto appender = appender!string();
const offset = prefix[0] == '!' ? 1 : 0;
size_t start = 0;
size_t end = 0;
foreach(const size_t i, const dchar c; prefix)
{
const size_t idx = i + offset;
if(isAlphaNum(c) || "-;/?:@&=+$,_.!~*\'()[]%"d.canFind(c))
{
end = idx + 1;
continue;
}
if(start < idx){appender.put(prefix[start .. idx]);}
start = end = idx + 1;
encodeChar(appender, c);
}
end = min(end, prefix.length);
if(start < end){appender.put(prefix[start .. end]);}
return appender.data;
}
///Prepare tag for output.
string prepareTag(in Tag tag) @trusted
{
enforce(!tag.isNull(), new Error("Tag must not be empty"));
string tagString = tag.get;
if(tagString == "!"){return tagString;}
string handle = null;
string suffix = tagString;
//Sort lexicographically by prefix.
sort!"icmp(a.prefix, b.prefix) < 0"(tagDirectives_);
foreach(ref pair; tagDirectives_)
{
auto prefix = pair.prefix;
if(tagString.startsWith(prefix) &&
(prefix != "!" || prefix.length < tagString.length))
{
handle = pair.handle;
suffix = tagString[prefix.length .. $];
}
}
auto appender = appender!string();
appender.put(handle !is null && handle != "" ? handle : "!<");
size_t start = 0;
size_t end = 0;
foreach(const dchar c; suffix)
{
if(isAlphaNum(c) || "-;/?:@&=+$,_.~*\'()[]"d.canFind(c) ||
(c == '!' && handle != "!"))
{
++end;
continue;
}
if(start < end){appender.put(suffix[start .. end]);}
start = end = end + 1;
encodeChar(appender, c);
}
if(start < end){appender.put(suffix[start .. end]);}
if(handle is null || handle == ""){appender.put(">");}
return appender.data;
}
///Prepare anchor for output.
static string prepareAnchor(const Anchor anchor) @trusted
{
enforce(!anchor.isNull() && anchor.get != "",
new Error("Anchor must not be empty"));
const str = anchor.get;
foreach(const dchar c; str)
{
enforce(isAlphaNum(c) || "-_"d.canFind(c),