-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibYAML_Wrapper.hpp
More file actions
1973 lines (1699 loc) · 85.2 KB
/
Copy pathLibYAML_Wrapper.hpp
File metadata and controls
1973 lines (1699 loc) · 85.2 KB
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
#ifndef RUNCPP2_LIB_YAML_WRAPPER_HPP
#define RUNCPP2_LIB_YAML_WRAPPER_HPP
#include "DSResult/DSResult.hpp"
#include "mpark/variant.hpp"
#include "nonstd/string_view.hpp"
#include "yaml.h"
#include "runcpp2/DeferUtil.hpp"
#include "ssLogger/ssLog.hpp"
#include <stack>
#include <utility>
#include <string>
#include <unordered_map>
#include <vector>
#include <memory>
#include <exception>
#include <limits>
#include <cctype>
#include <cstdint>
typedef yaml_event_s yaml_event_t;
typedef yaml_parser_s yaml_parser_t;
#if RUNCPP2_YAML_PRINT_PARSE
#include <cstdio>
#define RUNCPP2_YAML_PRINT(...) printf(__VA_ARGS__)
#else
#define RUNCPP2_YAML_PRINT(...) do{} while(false)
#endif
//Alias mpark::holds_alternative to mpark::is
namespace mpark
{
template <std::size_t I, typename... Ts>
inline constexpr bool is(const variant<Ts...> &v) noexcept
{
return holds_alternative<I, Ts...>(v);
}
template <typename T, typename... Ts>
inline constexpr bool is(const variant<Ts...> &v) noexcept
{
return holds_alternative<T, Ts...>(v);
}
}
namespace runcpp2
{
using StringView = nonstd::string_view;
namespace YAML
{
struct Node;
using ScalarValue = StringView;
struct Alias;
using NodePtr = std::shared_ptr<Node>;
using Sequence = std::vector<NodePtr>;
struct OrderedMap;
using NodeValue = mpark::variant<ScalarValue, Alias, Sequence, OrderedMap>;
}
}
namespace
{
std::string EscapeString(const runcpp2::StringView string);
std::string ScalarToString(const runcpp2::YAML::ScalarValue& scalar);
std::string AliasToString(const runcpp2::YAML::Alias& alias);
template<bool pushToStack, typename YamlValueType>
DS::Result<void> AddValueToMap( std::stack<std::pair< runcpp2::YAML::Node*,
int>>& nodeValCountStack,
const YamlValueType& newVal,
const yaml_event_t& event);
DS::Result<void> ParseHandleMap(yaml_event_t& event,
std::stack<std::pair< runcpp2::YAML::Node*,
int>>& nodeValCountStack);
DS::Result<void> ParseHandleSequence( yaml_event_t& event,
std::stack<std::pair< runcpp2::YAML::Node*,
int>>& nodeValCountStack);
DS::Result<void> ParseHandleScalar( yaml_event_t& event,
std::stack<std::pair< runcpp2::YAML::Node*,
int>>& nodeValCountStack);
DS::Result<void> ParseHandleAlias( yaml_event_t& event,
std::stack<std::pair< runcpp2::YAML::Node*,
int>>& nodeValCountStack);
DS::Result<void> CopyVariant(runcpp2::YAML::NodeValue& dest, const runcpp2::YAML::NodeValue& src);
DS::Result<void> UpdateParentsRecursively(runcpp2::YAML::Node& currentNode);
//NOTE: This doesn't update OrderedMap.StringMap
DS::Result<void> ResolveMergeKey( runcpp2::YAML::OrderedMap& currentMap,
int mergeKeyIndex,
const std::unordered_map< runcpp2::StringView,
runcpp2::YAML::Node*>& anchors);
}
namespace runcpp2
{
namespace YAML
{
enum class NodeType
{
Scalar,
Alias,
Sequence,
Map,
Count //4
};
inline StringView NodeTypeToString(NodeType type);
using NodePtr = std::shared_ptr<Node>;
using ConstNodePtr = std::shared_ptr<const Node>;
struct ReadWriteBuffer
{
std::vector<std::shared_ptr<yaml_event_t>> ReadData = {};
//NOTE: Needs to be unique_ptr due to small string optimizations
std::vector<std::shared_ptr<std::string>> WriteData = {};
inline std::string& CreateString()
{
WriteData.emplace_back(std::unique_ptr<std::string>(new std::string()));
return *WriteData.back().get();
}
inline std::string& CreateString(StringView view)
{
WriteData.emplace_back(std::unique_ptr<std::string>(new std::string(view.data(),
view.size())));
return *WriteData.back().get();
}
};
using ResourceHandle = std::pair<yaml_parser_t*, ReadWriteBuffer>;
inline NodePtr CreateNodePtr() { return std::make_shared<Node>(); }
//NOTE: all parameters must be alive while using the node
inline DS::Result<std::vector<NodePtr>> ParseYAML( StringView yamlString,
ResourceHandle& outResource);
#ifdef ParseYAML_TryDefer
#error "ParseYAML_TryDefer is already defined"
#else
//Same as:
//inline std::vector<NodePtr> ParseYAML_TryDefer( StringView yamlString,
// ResourceHandle& outResource);
#define ParseYAML_TryDefer(yamlString, outResource) \
ParseYAML(yamlString, outResource).DS_VALUE_OR(); \
DEFER { FreeYAMLResource(outResource); }; \
DS_CHECK_PREV()
#endif
inline DS::Result<void> ResolveAnchors(NodePtr rootNode);
inline void FreeYAMLResource(ResourceHandle& resourceHandleToFree);
inline std::vector<NodePtr> ParseYAML_DeferTry( StringView yamlString,
ResourceHandle& outResource);
struct Alias
{
StringView Value;
};
using Sequence = std::vector<NodePtr>;
using ScalarValue = StringView;
struct OrderedMap
{
std::vector<NodePtr> InsertedKeys;
std::unordered_map<NodePtr, NodePtr> Map;
std::unordered_map<ScalarValue, NodePtr> StringMap;
};
using NodeValue = mpark::variant<ScalarValue, Alias, Sequence, OrderedMap>;
struct Node
{
NodeValue Value = "";
StringView Anchor = "";
int LineNumber = -1;
Node* Parent = nullptr;
//--------------------------------------------------
//Reading
//--------------------------------------------------
inline NodeType GetType() const { return (NodeType)Value.index(); }
inline bool IsAlias() const { return mpark::is<Alias>(Value); };
inline bool IsScalar() const { return mpark::is<ScalarValue>(Value); };
inline bool IsSequence() const { return mpark::is<Sequence>(Value); };
inline bool IsMap() const { return mpark::is<OrderedMap>(Value); };
template<typename T>
inline DS::Result<T> GetAlias() const;
template<typename T>
inline DS::Result<T> GetScalar() const;
inline NodePtr GetSequenceChildNode(uint32_t index);
inline ConstNodePtr GetSequenceChildNode(uint32_t index) const;
template<typename T>
inline DS::Result<T> GetSequenceChildAlias(uint32_t index) const;
template<typename T>
inline DS::Result<T> GetSequenceChildScalar(uint32_t index) const;
inline bool HasMapKey(StringView key) const;
inline NodePtr GetMapValueNode(StringView key);
inline ConstNodePtr GetMapValueNode(StringView key) const;
template<typename T>
inline DS::Result<T> GetMapValueAlias(StringView key) const;
template<typename T>
inline DS::Result<T> GetMapValueScalar(StringView key) const;
inline NodePtr GetMapKeyNodeAt(uint32_t index);
inline ConstNodePtr GetMapKeyNodeAt(uint32_t index) const;
template<typename T>
inline DS::Result<T> GetMapKeyAliasAt(uint32_t index) const;
template<typename T>
inline DS::Result<T> GetMapKeyScalarAt(uint32_t index) const;
inline NodePtr GetMapValueNodeAt(uint32_t index);
inline ConstNodePtr GetMapValueNodeAt(uint32_t index) const;
template<typename T>
inline DS::Result<T> GetMapValueAliasAt(uint32_t index) const;
template<typename T>
inline DS::Result<T> GetMapValueScalarAt(uint32_t index) const;
inline Node* GetParent() const;
inline uint32_t GetChildrenCount() const;
//--------------------------------------------------
//Writing
//--------------------------------------------------
//NOTE: `val` will be copied
inline DS::Result<void> InitScalar(ScalarValue val, ResourceHandle& yamlResource);
//NOTE: `alias` will be copied
inline DS::Result<void> InitAlias(ScalarValue alias, ResourceHandle& yamlResource);
//TODO: Support ordering sequence child
inline DS::Result<void> InitSequence();
inline DS::Result<NodePtr> CloneToSequenceChild(NodePtr parentNode,
ResourceHandle& yamlResource) const;
inline DS::Result<void> RemoveSequenceChildAt(uint32_t index);
inline DS::Result<NodePtr> CreateSequenceChild();
inline DS::Result<NodePtr> CreateSequenceChildAt(uint32_t index);
//NOTE: `key` will be copied
inline DS::Result<void> InitMap();
inline DS::Result<NodePtr> CloneToMapChild( StringView key,
NodePtr parentNode,
ResourceHandle& yamlResource) const;
//TODO: Support ordering map child
inline DS::Result<void> RemoveMapChild(StringView key);
inline DS::Result<void> RemoveMapChildAt(uint32_t index);
//NOTE: `newKey` will be copied
inline DS::Result<void> UpdateMapKey( StringView oldKey,
StringView newKey,
ResourceHandle& resourceHandle);
inline DS::Result<void> UpdateMapValue( StringView oldKey,
StringView newKey,
ResourceHandle& resourceHandle);
//NOTE: `key` will be copied
inline DS::Result<NodePtr> CreateMapChild(StringView key, ResourceHandle& resourceHandle);
inline DS::Result<NodePtr> CreateMapChildAt(StringView key,
uint32_t index,
ResourceHandle& resourceHandle);
//TODO: Support null (null tag and ~)?
inline DS::Result<void> ToString(std::string& outString) const;
inline DS::Result<NodePtr> Clone(bool shallow, ResourceHandle& yamlResource) const;
};
//==================================================
//Node functions inline implementations
//==================================================
inline StringView NodeTypeToString(NodeType type)
{
switch(type)
{
case NodeType::Scalar:
return "Scalar";
case NodeType::Alias:
return "Alias";
case NodeType::Sequence:
return "Sequence";
case NodeType::Map:
return "Map";
default:
return "";
}
}
inline DS::Result<std::vector<NodePtr>> ParseYAML( StringView yamlString,
ResourceHandle& outResource)
{
ssLOG_FUNC_DEBUG();
std::vector<NodePtr> rootNodes;
outResource.first = nullptr;
outResource.first = new yaml_parser_t();
DS_ASSERT_TRUE(outResource.first != nullptr);
yaml_parser_t& parser = *outResource.first;
ReadWriteBuffer& readBuffer = outResource.second;
DS_ASSERT_EQ(yaml_parser_initialize(&parser), 1);
yaml_parser_set_input_string( &parser,
(const unsigned char*)yamlString.data(),
yamlString.size());
std::stack<std::pair<Node*, int>> nodeValCountStack;
while(true)
{
readBuffer.ReadData.emplace_back(std::shared_ptr<yaml_event_t>(new yaml_event_t()));
yaml_event_t& event = *readBuffer.ReadData.back().get();
if(!yaml_parser_parse(&parser, &event))
{
if(parser.problem_mark.line || parser.problem_mark.column)
{
return DS_ERROR_MSG(DS_STR("Parsing failed: ") + parser.problem + " on line " +
DS_STR(parser.problem_mark.line + 1) + ", column" +
DS_STR(parser.problem_mark.column + 1));
}
else
return DS_ERROR_MSG(DS_STR("Parsing failed: ") + parser.problem);
}
switch(event.type)
{
case YAML_NO_EVENT:
ssLOG_DEBUG("???\n");
break;
case YAML_STREAM_START_EVENT:
ssLOG_DEBUG("+STR\n");
break;
case YAML_STREAM_END_EVENT:
ssLOG_DEBUG("-STR\n");
break;
case YAML_DOCUMENT_START_EVENT:
if(!event.data.document_start.implicit)
ssLOG_DEBUG("+DOC ---");
else
ssLOG_DEBUG("+DOC");
rootNodes.push_back(CreateNodePtr());
nodeValCountStack.push(std::pair<Node*, int>(rootNodes.back().get(), -1));
break;
case YAML_DOCUMENT_END_EVENT:
if(!event.data.document_end.implicit)
ssLOG_DEBUG("-DOC ...");
else
ssLOG_DEBUG("-DOC");
//NOTE: Node is popped either by map end or sequence end event,
// hence it should be empty.
DS_ASSERT_TRUE(nodeValCountStack.empty());
break;
case YAML_MAPPING_START_EVENT:
DS_UNWRAP_VOID(ParseHandleMap(event, nodeValCountStack));
break;
case YAML_MAPPING_END_EVENT:
nodeValCountStack.pop();
ssLOG_DEBUG("-MAP");
break;
case YAML_SEQUENCE_START_EVENT:
DS_UNWRAP_VOID(ParseHandleSequence(event, nodeValCountStack));
break;
case YAML_SEQUENCE_END_EVENT:
ssLOG_DEBUG("-SEQ");
nodeValCountStack.pop();
break;
case YAML_SCALAR_EVENT:
DS_UNWRAP_VOID(ParseHandleScalar(event, nodeValCountStack));
break;
case YAML_ALIAS_EVENT:
DS_UNWRAP_VOID(ParseHandleAlias(event, nodeValCountStack));
break;
default:
return DS_ERROR_MSG(DS_STR("Unrecognize event type: ") +
DS_STR((int)event.type));
} //switch(event.type)
if(event.type == YAML_STREAM_END_EVENT)
break;
} //while(true)
return rootNodes;
}
inline DS::Result<void> ResolveAnchors(NodePtr rootNode)
{
DS_ASSERT_FALSE(mpark::is<ScalarValue>(rootNode->Value) ||
mpark::is<Alias>(rootNode->Value));
std::stack<std::pair<Node*, int>> nodeValCountStack;
nodeValCountStack.push(std::pair<Node*, int>(rootNode.get(), 0));
std::unordered_map<StringView, Node*> anchors;
std::vector<Node*> mapsToUpdateStringMapKeys;
while(!nodeValCountStack.empty())
{
Node& currentNode = *nodeValCountStack.top().first;
int visitCount = nodeValCountStack.top().second++;
//We visited once already, all the children are processed.
if(visitCount >= 1)
{
nodeValCountStack.pop();
continue;
}
if(mpark::is<Alias>(currentNode.Value))
{
StringView aliasValue = mpark::get_if<Alias>(¤tNode.Value)->Value;
DS_ASSERT_FALSE(aliasValue.empty());
if(anchors.count(aliasValue) == 0)
{
return DS_ERROR_MSG("Cannot find anchor value: " + DS_STR(aliasValue) +
" on line " + DS_STR(currentNode.LineNumber));
}
//Check parents don't have the anchor we want
Node* parent = ¤tNode;
while(parent != nullptr)
{
if(parent->Anchor == aliasValue)
{
return DS_ERROR_MSG("Cannot alias parent anchor: " +
DS_STR(aliasValue) +
" on line " + DS_STR(currentNode.LineNumber) +
" with parent on line " +
DS_STR(parent->LineNumber));
}
parent = parent->Parent;
}
//Resolve alias with the anchor we found
DS_UNWRAP_VOID(CopyVariant(currentNode.Value, anchors[aliasValue]->Value));
//Check if parent is map, remember to update the string map
if( currentNode.Parent != nullptr &&
mpark::is<OrderedMap>(currentNode.Parent->Value))
{
mapsToUpdateStringMapKeys.push_back(currentNode.Parent);
}
//The parent entry for this node is correct, but not the children, update them.
DS_UNWRAP_VOID(UpdateParentsRecursively(currentNode));
}
else if(mpark::is<ScalarValue>(currentNode.Value))
++(nodeValCountStack.top().second);
else if(mpark::is<Sequence>(currentNode.Value))
{
Sequence& sequence = *mpark::get_if<Sequence>(¤tNode.Value);
for(int i = sequence.size() - 1; i >= 0; --i)
nodeValCountStack.push(std::pair<Node*, int>(sequence[i].get(), 0));
}
else if(mpark::is<OrderedMap>(currentNode.Value))
{
OrderedMap& orderedMap = *mpark::get_if<OrderedMap>(¤tNode.Value);
bool hasMergeKeys = false;
//Resolve merge keys first if any
for(int i = 0; i < orderedMap.InsertedKeys.size(); ++i)
{
NodePtr currentKey = orderedMap.InsertedKeys[i];
if(!mpark::is<Alias>(currentKey->Value))
continue;
//TODO: Add support for alias map key
if(mpark::get_if<Alias>(¤tKey->Value)->Value != "<<")
return DS_ERROR_MSG("Alias key must be a merge key");
//Move all the alias children to current map
DS_UNWRAP_VOID(ResolveMergeKey(orderedMap, i, anchors));
hasMergeKeys = true;
}
//Need to udpate the parent entry for the children coming from merge keys, if any.
//Then we need to update the string map.
if(hasMergeKeys)
{
DS_UNWRAP_VOID(UpdateParentsRecursively(currentNode));
mapsToUpdateStringMapKeys.push_back(¤tNode);
}
//Push all the children to the stack to be resolved
for(int i = orderedMap.InsertedKeys.size() - 1; i >= 0; --i)
{
NodePtr currentKey = orderedMap.InsertedKeys[i];
nodeValCountStack.push(std::pair<Node*, int>(orderedMap.Map[currentKey].get(), 0));
nodeValCountStack.push(std::pair<Node*, int>(currentKey.get(), 0));
}
}
else
return DS_ERROR_MSG("Invalid type");
if(!currentNode.Anchor.empty())
anchors[currentNode.Anchor] = ¤tNode;
} //while(!nodeValCountStack.empty())
//Update string map for maps in mapsToUpdateStringMapKeys for any missing scalar keys
for(int i = 0; i < mapsToUpdateStringMapKeys.size(); ++i)
{
DS_ASSERT_TRUE(mpark::is<OrderedMap>(mapsToUpdateStringMapKeys[i]->Value));
OrderedMap& currentMap =
*mpark::get_if<OrderedMap>(&mapsToUpdateStringMapKeys[i]->Value);
for(int j = 0; j < currentMap.InsertedKeys.size(); ++j)
{
if(mpark::is<ScalarValue>(currentMap.InsertedKeys[j]->Value))
{
ScalarValue& curKey =
*mpark::get_if<ScalarValue>(¤tMap.InsertedKeys[j]->Value);
DS_ASSERT_TRUE(currentMap.Map.count(currentMap.InsertedKeys[j]) > 0);
if(currentMap.StringMap.count(curKey) == 0)
currentMap.StringMap[curKey] = currentMap.Map[currentMap.InsertedKeys[j]];
}
}
}
return {};
}
inline void FreeYAMLResource(ResourceHandle& resourceHandleToFree)
{
if(resourceHandleToFree.first != nullptr)
{
for(int i = 0; i < resourceHandleToFree.second.ReadData.size(); ++i)
yaml_event_delete(resourceHandleToFree.second.ReadData[i].get());
yaml_parser_delete(resourceHandleToFree.first);
delete resourceHandleToFree.first;
}
resourceHandleToFree.first = nullptr;
resourceHandleToFree.second = ReadWriteBuffer();
}
template<>
inline DS::Result<StringView> Node::GetAlias<StringView>() const
{
DS_ASSERT_TRUE(IsAlias());
return mpark::get_if<Alias>(&Value)->Value;
}
template<>
inline DS::Result<std::string> Node::GetAlias<std::string>() const
{
DS_ASSERT_TRUE(IsAlias());
return (std::string)mpark::get_if<Alias>(&Value)->Value;
}
#define INTERNAL_RUNCPP2_TRY_CONVERT_SCALAR(convertFunc) \
do \
{ \
try \
{ \
return convertFunc((std::string)*mpark::get_if<ScalarValue>(&Value)); \
} \
catch(std::exception& ex) \
{ \
return DS_ERROR_MSG(ex.what()); \
} \
} while(false)
template<>
inline DS::Result<int> Node::GetScalar<int>() const
{
DS_ASSERT_TRUE(IsScalar());
INTERNAL_RUNCPP2_TRY_CONVERT_SCALAR(std::stoi);
}
template<>
inline DS::Result<unsigned long> Node::GetScalar<unsigned long>() const
{
DS_ASSERT_TRUE(IsScalar());
INTERNAL_RUNCPP2_TRY_CONVERT_SCALAR(std::stoul);
}
template<>
inline DS::Result<long> Node::GetScalar<long>() const
{
DS_ASSERT_TRUE(IsScalar());
INTERNAL_RUNCPP2_TRY_CONVERT_SCALAR(std::stol);
}
template<>
inline DS::Result<unsigned long long> Node::GetScalar<unsigned long long>() const
{
DS_ASSERT_TRUE(IsScalar());
INTERNAL_RUNCPP2_TRY_CONVERT_SCALAR(std::stoull);
}
template<>
inline DS::Result<long long> Node::GetScalar<long long>() const
{
DS_ASSERT_TRUE(IsScalar());
INTERNAL_RUNCPP2_TRY_CONVERT_SCALAR(std::stoll);
}
template<>
inline DS::Result<unsigned int> Node::GetScalar<unsigned int>() const
{
DS_UNWRAP_DECL(unsigned long long ull, GetScalar<unsigned long long>());
DS_ASSERT_LT_EQ(ull, std::numeric_limits<unsigned int>::max());
return (unsigned int)ull;
}
template<>
inline DS::Result<float> Node::GetScalar<float>() const
{
DS_ASSERT_TRUE(IsScalar());
INTERNAL_RUNCPP2_TRY_CONVERT_SCALAR(std::stof);
}
template<>
inline DS::Result<double> Node::GetScalar<double>() const
{
DS_ASSERT_TRUE(IsScalar());
INTERNAL_RUNCPP2_TRY_CONVERT_SCALAR(std::stod);
}
#undef INTERNAL_RUNCPP2_TRY_CONVERT_SCALAR
template<>
inline DS::Result<bool> Node::GetScalar<bool>() const
{
DS_ASSERT_TRUE(IsScalar());
std::string v = (std::string)*mpark::get_if<ScalarValue>(&Value);
for(int i = 0; i < v.size(); ++i)
v[i] = std::tolower(v[i]);
//TODO: Strict mode which only allows lowercase true and false?
bool isTrue = v == "true" || v == "yes" || v == "on" || v == "1";
if(isTrue)
return true;
else if(v == "false" || v == "no" || v == "off" || v == "0")
return false;
else
return DS_ERROR_MSG("Invalid scalar value \"" + v + "\" to be converted to bool");
}
template<>
inline DS::Result<StringView> Node::GetScalar<StringView>() const
{
DS_ASSERT_TRUE(IsScalar());
return *mpark::get_if<ScalarValue>(&Value);
}
template<>
inline DS::Result<std::string> Node::GetScalar<std::string>() const
{
DS_ASSERT_TRUE(IsScalar());
return (std::string)*mpark::get_if<ScalarValue>(&Value);
}
inline NodePtr Node::GetSequenceChildNode(uint32_t index)
{
if(!IsSequence() || index >= mpark::get_if<Sequence>(&Value)->size())
return nullptr;
return (*mpark::get_if<Sequence>(&Value))[index];
}
inline ConstNodePtr Node::GetSequenceChildNode(uint32_t index) const
{
if(!IsSequence() || index >= mpark::get_if<Sequence>(&Value)->size())
return nullptr;
return (*mpark::get_if<Sequence>(&Value))[index];
}
template<typename T>
inline DS::Result<T> Node::GetSequenceChildAlias(uint32_t index) const
{
DS_ASSERT_TRUE(IsSequence());
DS_ASSERT_LT(index, mpark::get_if<Sequence>(&Value)->size());
return (*mpark::get_if<Sequence>(&Value))[index]->GetAlias<T>();
}
template<typename T>
inline DS::Result<T> Node::GetSequenceChildScalar(uint32_t index) const
{
DS_ASSERT_TRUE(IsSequence());
DS_ASSERT_LT(index, mpark::get_if<Sequence>(&Value)->size());
return (*mpark::get_if<Sequence>(&Value))[index]->GetScalar<T>();
}
inline bool Node::HasMapKey(StringView key) const
{
if(!IsMap())
return false;
return mpark::get_if<OrderedMap>(&Value)->StringMap.count(key) > 0;
}
inline NodePtr Node::GetMapValueNode(StringView key)
{
if(!IsMap() || mpark::get_if<OrderedMap>(&Value)->StringMap.count(key) == 0)
return nullptr;
return mpark::get_if<OrderedMap>(&Value)->StringMap.at(key);
}
inline ConstNodePtr Node::GetMapValueNode(StringView key) const
{
if(!IsMap() || mpark::get_if<OrderedMap>(&Value)->StringMap.count(key) == 0)
return nullptr;
return mpark::get_if<OrderedMap>(&Value)->StringMap.at(key);
}
template<typename T>
inline DS::Result<T> Node::GetMapValueAlias(StringView key) const
{
DS_ASSERT_TRUE(IsMap());
DS_ASSERT_TRUE(HasMapKey(key));
return mpark::get_if<OrderedMap>(&Value)->StringMap.at(key)->GetAlias<T>();
}
template<typename T>
inline DS::Result<T> Node::GetMapValueScalar(StringView key) const
{
DS_ASSERT_TRUE(IsMap());
DS_ASSERT_TRUE(HasMapKey(key));
return mpark::get_if<OrderedMap>(&Value)->StringMap.at(key)->GetScalar<T>();
}
inline NodePtr Node::GetMapKeyNodeAt(uint32_t index)
{
if(!IsMap() || index >= mpark::get_if<OrderedMap>(&Value)->InsertedKeys.size())
return nullptr;
return mpark::get_if<OrderedMap>(&Value)->InsertedKeys[index];
}
inline ConstNodePtr Node::GetMapKeyNodeAt(uint32_t index) const
{
if(!IsMap() || index >= mpark::get_if<OrderedMap>(&Value)->InsertedKeys.size())
return nullptr;
return mpark::get_if<OrderedMap>(&Value)->InsertedKeys[index];
}
template<typename T>
inline DS::Result<T> Node::GetMapKeyAliasAt(uint32_t index) const
{
DS_ASSERT_TRUE(IsMap());
DS_ASSERT_LT(index, mpark::get_if<OrderedMap>(&Value)->InsertedKeys.size());
return mpark::get_if<OrderedMap>(&Value)->InsertedKeys[index]->GetAlias<T>();
}
template<typename T>
inline DS::Result<T> Node::GetMapKeyScalarAt(uint32_t index) const
{
DS_ASSERT_TRUE(IsMap());
DS_ASSERT_LT(index, mpark::get_if<OrderedMap>(&Value)->InsertedKeys.size());
return mpark::get_if<OrderedMap>(&Value)->InsertedKeys[index]->GetScalar<T>();
}
inline NodePtr Node::GetMapValueNodeAt(uint32_t index)
{
if(!IsMap() || index >= mpark::get_if<OrderedMap>(&Value)->InsertedKeys.size())
return nullptr;
NodePtr keyNode = mpark::get_if<OrderedMap>(&Value)->InsertedKeys[index];
if(mpark::get_if<OrderedMap>(&Value)->Map.count(keyNode) == 0)
return nullptr;
return mpark::get_if<OrderedMap>(&Value)->Map.at(keyNode);
}
inline ConstNodePtr Node::GetMapValueNodeAt(uint32_t index) const
{
if(!IsMap() || index >= mpark::get_if<OrderedMap>(&Value)->InsertedKeys.size())
return nullptr;
NodePtr keyNode = mpark::get_if<OrderedMap>(&Value)->InsertedKeys[index];
if(mpark::get_if<OrderedMap>(&Value)->Map.count(keyNode) == 0)
return nullptr;
return mpark::get_if<OrderedMap>(&Value)->Map.at(keyNode);
}
template<typename T>
inline DS::Result<T> Node::GetMapValueAliasAt(uint32_t index) const
{
DS_ASSERT_TRUE(IsMap());
DS_ASSERT_LT(index, mpark::get_if<OrderedMap>(&Value)->InsertedKeys.size());
NodePtr keyNode = mpark::get_if<OrderedMap>(&Value)->InsertedKeys[index];
DS_ASSERT_NOT_EQ(mpark::get_if<OrderedMap>(&Value)->Map.count(keyNode), 0);
return mpark::get_if<OrderedMap>(&Value)->Map.at(keyNode)->GetAlias<T>();
}
template<typename T>
inline DS::Result<T> Node::GetMapValueScalarAt(uint32_t index) const
{
DS_ASSERT_TRUE(IsMap());
DS_ASSERT_LT(index, mpark::get_if<OrderedMap>(&Value)->InsertedKeys.size());
NodePtr keyNode = mpark::get_if<OrderedMap>(&Value)->InsertedKeys[index];
DS_ASSERT_NOT_EQ(mpark::get_if<OrderedMap>(&Value)->Map.count(keyNode), 0);
return mpark::get_if<OrderedMap>(&Value)->Map.at(keyNode)->GetScalar<T>();
}
inline Node* Node::GetParent() const
{
return Parent;
}
inline uint32_t Node::GetChildrenCount() const
{
if(IsAlias() || IsScalar())
return 0;
else if(IsMap())
return mpark::get_if<OrderedMap>(&Value)->InsertedKeys.size();
else if(IsSequence())
return mpark::get_if<Sequence>(&Value)->size();
else
return 0;
}
inline DS::Result<void> Node::InitScalar(ScalarValue val, ResourceHandle& yamlResource)
{
Value = StringView(yamlResource.second.CreateString(val));
return {};
}
inline DS::Result<void> Node::InitAlias(ScalarValue alias, ResourceHandle& yamlResource)
{
Value = Alias{StringView(yamlResource.second.CreateString(alias))};
return {};
}
inline DS::Result<void> Node::InitSequence()
{
Value = Sequence();
return {};
}
//TODO: Reorder the whole thing to match declaration order
inline DS::Result<NodePtr> Node::CloneToSequenceChild( NodePtr parentNode,
ResourceHandle& yamlResource) const
{
DS_ASSERT_TRUE(parentNode->IsSequence());
NodePtr clonedThis = Clone(false, yamlResource).DS_TRY();
clonedThis->Parent = parentNode.get();
mpark::get_if<Sequence>(&parentNode->Value)->push_back(clonedThis);
return clonedThis;
}
inline DS::Result<void> Node::RemoveSequenceChildAt(uint32_t index)
{
DS_ASSERT_TRUE(IsSequence());
DS_ASSERT_LT(index, mpark::get<Sequence>(Value).size());
mpark::get<Sequence>(Value).erase(mpark::get<Sequence>(Value).begin() + index);
return {};
}
inline DS::Result<NodePtr> Node::CreateSequenceChild()
{
DS_ASSERT_TRUE(IsSequence());
mpark::get<Sequence>(Value).emplace_back();
return mpark::get<Sequence>(Value).back();
}
inline DS::Result<NodePtr> Node::CreateSequenceChildAt(uint32_t index)
{
DS_ASSERT_TRUE(IsSequence());
DS_ASSERT_LT_EQ(index, mpark::get<Sequence>(Value).size());
mpark::get<Sequence>(Value).insert(mpark::get<Sequence>(Value).begin() + index, {});
return mpark::get<Sequence>(Value)[index];
}
inline DS::Result<void> Node::InitMap()
{
Value = OrderedMap();
return {};
}
inline DS::Result<NodePtr> Node::CloneToMapChild( StringView key,
NodePtr parentNode,
ResourceHandle& yamlResource) const
{
DS_ASSERT_TRUE(parentNode->IsMap());
NodePtr clonedThis = Clone(false, yamlResource).DS_TRY();
clonedThis->Parent = parentNode.get();
NodePtr keyNode = CreateNodePtr();
std::string& keyStr = yamlResource.second.CreateString(key);
keyNode->Value = keyStr;
keyNode->LineNumber = LineNumber;
mpark::get_if<OrderedMap>(&parentNode->Value)->InsertedKeys.push_back(keyNode);
mpark::get_if<OrderedMap>(&parentNode->Value)->Map[keyNode] = clonedThis;
mpark::get_if<OrderedMap>(&parentNode->Value)->StringMap[keyStr] = clonedThis;
return clonedThis;
}
inline DS::Result<void> Node::RemoveMapChild(StringView key)
{
DS_ASSERT_TRUE(IsMap());
OrderedMap& orderedMap = *mpark::get_if<OrderedMap>(&Value);
if(orderedMap.StringMap.count(key) == 0)
return {};
//NodePtr valueNode = orderedMap.StringMap[key];
NodePtr keyNode = nullptr;
int keyNodeIndex = -1;
for(int i = 0; i < orderedMap.InsertedKeys.size(); ++i)
{
if( orderedMap.InsertedKeys[i]->IsScalar() &&
orderedMap.InsertedKeys.at(i)->GetScalar<StringView>().Value() == key)
{
keyNode = orderedMap.InsertedKeys[i];
keyNodeIndex = i;
break;
}
}
DS_ASSERT_TRUE(keyNodeIndex != -1);
orderedMap.InsertedKeys.erase(orderedMap.InsertedKeys.begin() + keyNodeIndex);
orderedMap.Map.erase(keyNode);
orderedMap.StringMap.erase(key);
return {};
}
inline DS::Result<void> Node::RemoveMapChildAt(uint32_t index)
{
DS_ASSERT_TRUE(IsMap());
OrderedMap& orderedMap = *mpark::get_if<OrderedMap>(&Value);
DS_ASSERT_LT(index, orderedMap.InsertedKeys.size());
NodePtr keyNode = orderedMap.InsertedKeys[index];
DS_ASSERT_NOT_EQ(orderedMap.Map.count(keyNode), 0);
StringView keyView = orderedMap.Map.at(keyNode)->GetScalar<StringView>().DS_TRY();
return RemoveMapChild(keyView);
}
inline DS::Result<void> Node::UpdateMapKey( StringView oldKey,
StringView newKey,
ResourceHandle& resourceHandle)
{
DS_ASSERT_TRUE(IsMap());
OrderedMap& orderedMap = *mpark::get_if<OrderedMap>(&Value);
DS_ASSERT_GT(orderedMap.StringMap.count(oldKey), 0);
NodePtr keyNode = nullptr;
for(int i = 0; i < orderedMap.InsertedKeys.size(); ++i)
{
if( orderedMap.InsertedKeys[i]->IsScalar() &&
orderedMap.InsertedKeys.at(i)->GetScalar<StringView>().Value() == oldKey)
{
keyNode = orderedMap.InsertedKeys[i];
break;
}
}
DS_ASSERT_TRUE(keyNode != nullptr);
std::string& newKeyStr = resourceHandle.second.CreateString(newKey);
keyNode->Value = newKeyStr;
orderedMap.StringMap.erase(oldKey);
DS_ASSERT_GT(orderedMap.Map.count(keyNode), 0);
orderedMap.StringMap[newKey] = orderedMap.Map[keyNode];
return {};
}
inline DS::Result<NodePtr> Node::CreateMapChild(StringView key,
ResourceHandle& resourceHandle)
{
DS_ASSERT_TRUE(IsMap());
OrderedMap& orderedMap = *mpark::get_if<OrderedMap>(&Value);
DS_ASSERT_EQ(orderedMap.StringMap.count(key), 0);
std::string& keyStr = resourceHandle.second.CreateString(key);